What are common issues encountered when using readfile for file downloads in PHP?

One common issue when using readfile for file downloads in PHP is that it may not handle large files efficiently, potentially causing memory exhaustion. To solve this, you can use a combination of readfile and output buffering to stream the file in chunks, rather than loading the entire file into memory at once.

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

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