What are the best practices for handling file requests and responses in PHP scripts?

When handling file requests and responses in PHP scripts, it is important to ensure security by validating user input and sanitizing file paths to prevent directory traversal attacks. It is also good practice to set appropriate headers for file downloads, such as Content-Type and Content-Disposition. Additionally, consider implementing file caching to improve performance and reduce server load.

// Example of handling file download request in PHP

// Validate and sanitize file path
$file = 'path/to/file.pdf';
if (file_exists($file)) {
    // Set appropriate headers for file download
    header('Content-Type: application/pdf');
    header('Content-Disposition: attachment; filename="' . basename($file) . '"');
    
    // Output the file contents
    readfile($file);
} else {
    // Handle file not found error
    echo 'File not found';
}