Sobes.tech
Senior

$filename = $_GET['file']; $content = file_get_contents("/var/www/files/" . $filename); echo $content;

sobes.tech AI

Answer from AI

This code has a Path Traversal vulnerability. The $filename parameter is taken directly from the GET request and inserted into the file path without validation, allowing an attacker to access any files on the server.

Example attack: passing file=../../etc/passwd will read the system file.

To fix this:

  • Validate and filter the filename, allowing only permitted values.
  • Use functions to normalize the path and check that the file is within the intended directory.

Example of a safe PHP version:

$filename = basename($_GET['file']); // removes paths
$filepath = '/var/www/files/' . $filename;
if (file_exists($filepath)) {
    echo file_get_contents($filepath);
} else {
    echo 'File not found';
}