When working with relative paths, it's crucial to safeguard against directory traversal attacks that can compromise sensitive system information.
Consider the scenario where you have a base path of '/whatever/foo/' and need to allow relative paths using the $_GET['path'] variable. However, malicious actors may attempt to exploit this mechanism by injecting path traversal sequences (like '..' or './') to access restricted directories.
To effectively prevent directory traversal while allowing relative paths, you can utilize the following technique:
$basepath = '/foo/bar/baz/'; $realBase = realpath($basepath); $userpath = $basepath . $_GET['path']; $realUserPath = realpath($userpath); if ($realUserPath === false || strpos($realUserPath, $realBase) !== 0) { // Directory Traversal Attempt Detected } else { // Valid Path }
This method leverages the realpath() function to determine the absolute physical paths of both the base and user-provided paths. By comparing these absolute paths, you can verify that the user path does not traverse outside the designated base path. If it does, realpath() will return false or an incorrect path, triggering the detection of a directory traversal attempt.
The above is the detailed content of How Can I Prevent Directory Traversal Attacks in PHP While Allowing Relative Paths?. For more information, please follow other related articles on the PHP Chinese website!