What steps can be taken to improve the overall security and functionality of the PHP download script mentioned in the forum thread?

Issue: The PHP download script mentioned in the forum thread is vulnerable to directory traversal attacks, which can allow malicious users to access sensitive files on the server. To improve the security and functionality of the script, we need to sanitize the user input and validate the file path before allowing the download.

// Sanitize and validate the file path before allowing the download
$download_folder = '/path/to/downloads/';

if (isset($_GET['file'])) {
    $file = basename($_GET['file']);
    $download_path = $download_folder . $file;

    if (file_exists($download_path) && strpos($file, '/') === false) {
        // Set appropriate headers for the file download
        header('Content-Type: application/octet-stream');
        header('Content-Disposition: attachment; filename="' . $file . '"');
        header('Content-Length: ' . filesize($download_path));

        // Read the file and output its contents
        readfile($download_path);
        exit;
    } else {
        echo 'Invalid file path';
    }
} else {
    echo 'File parameter is missing';
}