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);
Keywords
Related Questions
- Can you recommend any specific resources or books for beginners looking to learn PHP for WordPress plugin development?
- What are some common pitfalls in PHP code organization and readability, as seen in the provided forum thread?
- What are the differences in error reporting levels between different versions of XAMPP and how can they impact PHP development?