Are there best practices for handling file downloads in PHP to avoid security issues?

When handling file downloads in PHP, it is crucial to avoid direct access to files on the server to prevent security vulnerabilities such as unauthorized access or execution of malicious scripts. One best practice is to store files outside the web root directory and use PHP to serve the files to users, ensuring proper validation and sanitization of file paths.

<?php
// Validate and sanitize the file path
$filePath = '/path/to/file.pdf';

if (file_exists($filePath)) {
    // Set appropriate headers for file download
    header('Content-Description: File Transfer');
    header('Content-Type: application/pdf');
    header('Content-Disposition: attachment; filename=' . basename($filePath));
    header('Content-Length: ' . filesize($filePath));
    
    // Read and output the file contents
    readfile($filePath);
    exit;
} else {
    // Handle file not found error
    echo 'File not found';
}
?>