How can the PHP script be improved to prevent directory traversal vulnerabilities and unauthorized access to files?
Directory traversal vulnerabilities and unauthorized access to files can be prevented by validating user input and ensuring that file paths are properly sanitized before being used. One way to achieve this is by using the realpath() function in PHP to resolve the full path of a file and compare it against a base directory to restrict access.
<?php
$baseDir = '/path/to/secure/directory/';
// Get the requested file path from user input
$requestedFile = $_GET['file'];
// Resolve the full path of the requested file
$realPath = realpath($baseDir . $requestedFile);
// Check if the resolved path is within the base directory
if (strpos($realPath, $baseDir) === 0) {
// Access is allowed, serve the file
readfile($realPath);
} else {
// Access is not allowed, show an error message
echo 'Unauthorized access';
}
?>
Keywords
Related Questions
- How can one troubleshoot the lack of PHP output or feedback in a web browser?
- What potential pitfalls should be avoided when trying to access a user-selected database in PHP?
- How can the error message "Warning: mysql_num_rows(): supplied argument is not a valid MySQL result resource" be resolved in PHP 5 when querying a database?