Path traversal happens when attackers use sequences like ../ in file paths to move outside
the intended directory. If the code does not check paths, attackers may read sensitive files (e.g.,
/etc/passwd, app/etc/env.php) or overwrite important data.
File access in Magento must be restricted to safe directories. Validating and normalizing file paths stops attackers from escaping into system folders. Adding these protections keeps secrets, configs, and code safe from unauthorized access.
# Search for unsafe file access in custom modules
grep -R "file_get_contents(" app/code
grep -R "fopen(" app/code
grep -R "require" app/code
# Check if user input is validated before being used in file paths
realpath() before use.// Unsafe, uses user input directly
$path = $_GET['file'];
echo file_get_contents('media/' . $path);
// Safe, normalize and check path
$baseDir = realpath('media/');
$file = realpath($baseDir . '/' . $path);
if ($file !== false && strpos($file, $baseDir) === 0) {
echo file_get_contents($file);
} else {
throw new Exception("Invalid file path");
}