![]() |
Path traversal, commonly referred to as Directory Traversal, is a security flaw that arises when user-supplied input file names are not sufficiently validated for security or sanitized. This vulnerability might be used by an attacker to read, write, or access files that they shouldn’t be permitted to access or modify. This frequently requires working with file-related functions in PHP applications that accept file paths, including fopen(), file_get_contents(), include(), and so on. Working of Path Traversal AttacksYou have a PHP script that will, in response to user input, show an image file from a directory. PHP
Now, if the user provides a value like “my_image.jpg” for filename, the script will read the file /images/my_image.jpg. However, if someone provides a value like “../../etc/passwd”, the script will read the file “/etc/passwd”, leaking sensitive information. Techniques to Prevent Path Traversal Attacks
When the PHP basename() function is used, directory paths are removed and just the file name is retained. $filename = basename($_GET['filename']);
$allowed_files = ["image1.jpg", "image2.jpg"]; if (!in_array($_GET['filename'], $allowed_files)) { die("Not allowed!"); }
ini_set('display_errors', '0');
$file_extension = pathinfo($_GET['filename'], PATHINFO_EXTENSION); if (!in_array($file_extension, ['jpg', 'png'])) { die("Not allowed!"); }
$filepath = realpath("/images" . $filename); if (strpos($filepath, "/images") !== 0) { die("Not allowed!"); } You may aid in preventing path traversal vulnerabilities in your PHP application by implementing these security-recommended practices. |
Reffered: https://www.geeksforgeeks.org
PHP |
Related |
---|
![]() |
![]() |
![]() |
![]() |
![]() |
Type: | Geek |
Category: | Coding |
Sub Category: | Tutorial |
Uploaded by: | Admin |
Views: | 11 |