How can PHP code be optimized to handle file downloads more efficiently?

To optimize PHP code for handling file downloads more efficiently, it is important to use appropriate headers to control caching, compression, and content delivery. This can help reduce the load on the server and improve the overall performance of file downloads. Additionally, using the readfile() function instead of file_get_contents() can help to efficiently stream the file to the client without loading the entire file into memory.

$file = 'path/to/file.pdf';

if (file_exists($file)) {
    header('Content-Description: File Transfer');
    header('Content-Type: application/octet-stream');
    header('Content-Disposition: attachment; filename="' . basename($file) . '"');
    header('Expires: 0');
    header('Cache-Control: must-revalidate');
    header('Pragma: public');
    header('Content-Length: ' . filesize($file));
    readfile($file);
    exit;
} else {
    echo 'File not found.';
}