How can the PHP code be improved to prevent directory traversal attacks?
Directory traversal attacks can be prevented in PHP by sanitizing user input and ensuring that file paths are properly validated before accessing them. One way to do this is by using the realpath() function to resolve the full path of a file and then comparing it to a base directory to ensure it is within the expected directory structure. Additionally, limiting access to only specific directories can help mitigate the risk of directory traversal attacks.
$baseDir = '/path/to/secure/directory/';
$requestedFile = $_GET['file'];
$fullPath = realpath($baseDir . $requestedFile);
if (strpos($fullPath, $baseDir) === 0) {
// File path is within the secure directory
// Proceed with accessing the file
} else {
// File path is outside the secure directory
// Handle the error or prevent access
}