Home > Backend Development > PHP Tutorial > How Can I Prevent Directory Traversal Attacks in PHP While Allowing Relative Paths?

How Can I Prevent Directory Traversal Attacks in PHP While Allowing Relative Paths?

Patricia Arquette
Release: 2024-12-07 16:13:12
Original
930 people have browsed it

How Can I Prevent Directory Traversal Attacks in PHP While Allowing Relative Paths?

Preventing Directory Traversal while Allowing Paths in PHP

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
}
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template