In what scenarios would using readfile_chunked() be more beneficial than readfile() for downloading large files in PHP?
When downloading large files in PHP, using readfile_chunked() can be more beneficial than readfile() when dealing with files that are too large to fit into memory all at once. readfile_chunked() reads and outputs the file in smaller chunks, reducing memory usage and allowing for more efficient processing of large files.
function readfile_chunked($filename) {
$chunk_size = 1024 * 1024; // 1MB chunks
$handle = fopen($filename, 'rb');
if ($handle === false) {
return false;
}
while (!feof($handle)) {
echo fread($handle, $chunk_size);
ob_flush();
flush();
}
fclose($handle);
return true;
}
$file_path = 'path/to/large/file.zip';
readfile_chunked($file_path);