如果您必须下载的文件大于允许的内存限制(memory_limit ini 设置) ,这将导致 PHP Fatal error: Allowed memory size of 5242880 bytes exhausted错误,您可以这样做:
// File to download.
$file = '/path/to/file';
// Maximum size of chunks (in bytes).
$maxRead = 1 * 1024 * 1024; // 1MB
// Give a nice name to your download.
$fileName = 'download_file.txt';
// Open a file in read mode.
$fh = fopen($file, 'r');
// These headers will force download on browser,
// and set the custom file name for the download, respectively.
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="' . $fileName . '"');
// Run this until we have read the whole file.
// feof (eof means "end of file") returns `true` when the handler
// has reached the end of file.
while (!feof($fh)) {
// Read and output the next chunk.
echo fread($fh, $maxRead);
// Flush the output buffer to free memory.
ob_flush();
}
// Exit to make sure not to output anything else.
exit;