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';
}
?>