What is the best practice for offering multiple files for download on a PHP website?

When offering multiple files for download on a PHP website, it is best practice to create a download script that handles the file downloads securely. This script should check for valid file paths, set appropriate headers to force the browser to download the file, and prevent direct access to the files outside of the script.

<?php
// Define an array of file paths
$files = array(
    'file1.pdf' => 'File 1',
    'file2.zip' => 'File 2'
);

// Check if the requested file exists in the array
if(isset($_GET['file']) && array_key_exists($_GET['file'], $files)){
    $file = $_GET['file'];
    $filepath = $files[$file];

    // Set headers to force download
    header("Content-Type: application/octet-stream");
    header("Content-Disposition: attachment; filename=" . basename($filepath));
    readfile($filepath);
    exit;
} else {
    // Handle invalid file requests
    echo "Invalid file request";
}
?>