What are some best practices for preventing directory traversal attacks in PHP applications?
Directory traversal attacks occur when an attacker manipulates a file path in a web application to access files outside of the intended directory. To prevent this, it is important to validate and sanitize all user input related to file paths.
// Sanitize user input for file paths
$filePath = realpath('./uploads/' . $_GET['file']);
// Check if the sanitized path is within the uploads directory
if (strpos($filePath, realpath('./uploads/')) !== 0) {
die('Invalid file path');
}
// Proceed with file operations
// ...