SyntaxStudy
Sign Up
PHP Directory Traversal Prevention
PHP Intermediate 4 min read

Directory Traversal Prevention

Path Traversal

Never use user input to build file paths. Use realpath() and verify the resolved path starts with an allowed base directory.

Example
$base = realpath("/var/app/uploads");
$requested = $_GET["file"] ?? "";
$path = realpath($base . "/" . basename($requested));
if ($path === false || strncmp($path, $base, strlen($base)) !== 0) {
    http_response_code(403); exit("Access denied");
}
readfile($path); // safe to serve
// basename() strips directory components: ../../etc/passwd → passwd
Pro Tip

realpath() resolves symlinks and .. — always compare its output against the allowed base directory.