This article introduces some problems and solutions encountered when downloading files in PHP. Friends in need can refer to them.
When using php to download files, the download box of the browser pops up and the save as operation appears. Sometimes memory overflow and timeout may occur. If it times out, you can set set_time_limit(0); If memory overflow occurs, it may be caused by too much data being retrieved from the database. If a memory overflow occurs when reading from a file, it means that the code reading method is incorrect and it requires calling files or filegetcontens. If it is fopen, give a buffer with a fixed size, read and then write, and there will be no memory overflow. Code: <?php //php下载文件 //by bbs.it-home.org if (file_exists($file_path)) { //如果文件存在 $handle = fopen($file_path, "r"); while (!feof($handle)) { $content = fgets($handle, 4096); //读取一行 echo $content; //输出到缓冲区,即php://stdout。 //达到缓冲区设置值后由tcp传给浏览器进行输出,一般到512字节就会通过网络输出给浏览器。 } fclose($handle); } ?> Copy after login Note: Before output, you need to call @ob_end_flush() once; it cannot be called in a loop, just call it once. @ob_end_flush();//Flush out (send) the contents of the output buffer and close the buffer. File download: content-type://Download format, if the format cannot be parsed by the browser, the download box will pop up <?php //php下载文件 //by bbs.it-home.org header("Content-Type: application/force-download"); header("Content-Type: application/download"); header("Content-Transfer-Encoding: binary"); header("Cache-Control: must-revalidate, post-check=0, pre-check=0"); header("Pragma: no-cache"); Header("Content-type: application/octet-stream"); //响应内容类型 Header("Accept-Ranges: bytes"); Header("Accept-Length: ".filesize($filename). ' bytes'); Header('Content-Disposition: attachment; filename='.$filename); //HTTP响应头 ?> Copy after login |