What are the potential memory issues when using readfile in PHP for large file downloads?

When using readfile in PHP for large file downloads, potential memory issues can arise if the entire file is read into memory before being sent to the client. To solve this, you can use a buffer to read and output the file in smaller chunks, preventing the entire file from being loaded into memory at once.

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

header('Content-Description: File Transfer');
header('Content-Type: application/zip');
header('Content-Disposition: attachment; filename=' . basename($file));
header('Content-Length: ' . filesize($file));

$chunkSize = 1024 * 1024; // 1MB chunks
$handle = fopen($file, 'rb');

while (!feof($handle)) {
    echo fread($handle, $chunkSize);
    ob_flush();
    flush();
}

fclose($handle);