<?php$file = 'path/to/your/largefile.pdf';// Make sure the file existsif (!file_exists($file)) { die('File not found.');}// Set headers to tell the browser to download the fileheader('Content-Type: application/octet-stream');header('Content-Disposition: attachment; filename="'.basename($file).'"');header('Content-Length: ' . filesize($file));// Open the file in binary mode$fp = fopen($file, 'rb');// Output the filewhile (!feof($fp)) { // Read and output a chunk of the file echo fread($fp, 8192); // Flush the output buffer to free up memory ob_flush(); flush();}// Close the filefclose($fp);exit;
在上面的代码中,我们利用 fopen() 打开文件,利用 fread() 一次读取 8192 字节的块(大约 8KB)。然后,我们利用和输出缓冲区输出此块以开释利用的内存。此过程将重复,直到文件末端(返回)。echoflushfeof($fp)true
在本教程中,您学习了如何利用 PHP 以节省内存的办法将大文件流式传输到浏览器。在处理可能花费大量做事器内存并导致性能问题的大型文件时,此方法非常有用。始终记住关闭任何打开的文件句柄并刷新输出缓冲区以开释内存。
