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);
Related Questions
- What are the advantages of using a FunctionLoader class for including functions in PHP scripts?
- How can one ensure that all values from a MySQL table are correctly displayed in a dropdown field using PHP?
- How can PEAR classes, such as HTTP_Request, be effectively used in PHP scripts for handling HTTP requests?