How can you securely handle file paths in PHP to prevent directory traversal attacks?
Directory traversal attacks can occur when user input is not properly sanitized and allows an attacker to access files outside of the intended directory. To prevent this, always validate and sanitize user input before using it in file paths. Use PHP functions like realpath() or basename() to ensure that file paths are normalized and do not contain any unexpected characters.
// Example of securely handling file paths in PHP to prevent directory traversal attacks
// Sanitize user input
$userInput = $_GET['file'];
$cleanPath = realpath('uploads/' . basename($userInput));
// Check if the sanitized path is within the uploads directory
if (strpos($cleanPath, 'uploads/') === 0) {
// Proceed with accessing the file
$fileContents = file_get_contents($cleanPath);
echo $fileContents;
} else {
// Invalid file path
echo "Invalid file path";
}