What are best practices for ensuring that the correct file is downloaded in PHP scripts?

To ensure that the correct file is downloaded in PHP scripts, it is important to validate the file path and name before initiating the download. This can help prevent users from accessing unauthorized files or potentially harmful files. Additionally, setting appropriate headers in the response can ensure that the file is downloaded correctly by the browser.

<?php
$file_path = '/path/to/file.pdf';

if (file_exists($file_path)) {
    header('Content-Description: File Transfer');
    header('Content-Type: application/pdf');
    header('Content-Disposition: attachment; filename=' . basename($file_path));
    header('Content-Length: ' . filesize($file_path));
    readfile($file_path);
    exit;
} else {
    echo 'File not found';
}
?>