How does chunked readfile in PHP help in handling large file downloads and memory usage?

When downloading large files in PHP, reading the entire file into memory at once can lead to high memory usage and potential performance issues. To address this, we can use chunked reading of the file, where the file is read in smaller parts (chunks) rather than all at once. This helps in efficiently handling large file downloads and reduces memory usage.

$filePath = 'path/to/large/file.zip';
$chunkSize = 1024 * 1024; // 1MB chunk size

header('Content-Type: application/zip');
header('Content-Disposition: attachment; filename="file.zip"');

$handle = fopen($filePath, 'rb');
while (!feof($handle)) {
    echo fread($handle, $chunkSize);
    ob_flush();
    flush();
}
fclose($handle);