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
- What are some potential pitfalls to avoid when implementing word filtering in PHP search functions?
- What are the best practices for structuring and accessing values in nested arrays in PHP to improve code readability and efficiency?
- What potential issues could arise from using the mysql_connect function in PHP for database connections?