Friday, October 17, 2025
HomeLanguagesExplain Path Traversal?

Explain Path Traversal?

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 Attacks

You have a PHP script that will, in response to user input, show an image file from a directory.

PHP




<?php
$filename = $_GET["filename"];
$filepath = "/images/" . $filename;
header("Content-Type: image/jpeg");
echo file_get_contents($filepath);
?>


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

  • Prior to utilizing user input in file operations, always sanitize it.

When the PHP basename() function is used, directory paths are removed and just the file name is retained.

$filename = basename($_GET['filename']);
  • Use whitelisting and only permit known beneficial values.
$allowed_files = ["image1.jpg", "image2.jpg"];
if (!in_array($_GET['filename'], $allowed_files)) {
   die("Not allowed!");
}
  • Disable Reporting PHP Errors to Client: To reduce information leakage, disable PHP error reporting to the client.
ini_set('display_errors', '0');
  • Verify the file’s anticipated extension by checking the file’s extension.
$file_extension = pathinfo($_GET['filename'], PATHINFO_EXTENSION);
if (!in_array($file_extension, ['jpg', 'png'])) {
   die("Not allowed!");
}
  • Always convert to an absolute path and confirm that it is located in the desired directory when using absolute paths.
$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.

RELATED ARTICLES

Most Popular

Dominic
32361 POSTS0 COMMENTS
Milvus
88 POSTS0 COMMENTS
Nango Kala
6728 POSTS0 COMMENTS
Nicole Veronica
11892 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11954 POSTS0 COMMENTS
Shaida Kate Naidoo
6852 POSTS0 COMMENTS
Ted Musemwa
7113 POSTS0 COMMENTS
Thapelo Manthata
6805 POSTS0 COMMENTS
Umr Jansen
6801 POSTS0 COMMENTS