Back to results for “File System”
PHP › File Handling & File System Functions

What security risks are associated with file handling operations that involve user supplied file paths, and how does path traversal attack prevention work?

Advanced

Answer

A path traversal attack occurs when an attacker manipulates a file path input, often by including sequences like a double dot to navigate up directory levels, attempting to access files outside of the intended directory, such as sensitive configuration files, and preventing this requires carefully validating and sanitizing any user supplied path components, ideally by using a whitelist of allowed characters or file names rather than trying to blacklist dangerous patterns, and by resolving the final path and verifying it still falls within the intended base directory before performing any file operation.
$baseDir = realpath('/var/www/uploads');
$requestedFile = realpath($baseDir . '/' . $userInput);
if ($requestedFile === false || !str_starts_with($requestedFile, $baseDir)) {
    throw new SecurityException('Invalid file path');
}
Real-world example A file download feature validates that a user requested file path, after being fully resolved, still falls within the intended uploads directory, blocking an attempted path traversal attack where a malicious user tried to include double dot sequences to access an unrelated system file.

Common follow-ups: What is the difference between blacklisting and whitelisting when it comes to validating file paths?;How does the realpath function help defend against path traversal attacks?