The failure to download the php file is because when readfile reads the file, it will put the file into the cache, causing memory overflow. The solution is to implement segmented download and limit the download speed.
Recommended: "PHP Video Tutorial"
Solve PHP failure to download large files and limit downloads Speed
1. Problem:
When PHP uses the readfile function to define a download file, the file cannot be too large, otherwise the download will fail, the file will be damaged, and no error will be reported;
2. Reason:
This is because when readfile reads the file, it will put the file into the cache, causing memory overflow;
3. Solution: Download in segments and limit downloads Speed;
<?php //设置文件最长执行时间 set_time_limit(0); if (isset($_GET['filename']) && !empty($_GET['filename'])) { $file_name = $_GET['filename']; $file = __DIR__ . '/assets/' . $file_name; } else { echo 'what are your searching for?'; exit(); } if (file_exists($file) && is_file($file)) { $filesize = filesize($file); header('Content-Description: File Transfer'); header('Content-Type: application/octet-stream'); header('Content-Transfer-Encoding: binary'); header('Accept-Ranges: bytes'); header('Expires: 0'); header('Cache-Control: must-revalidate'); header('Pragma: public'); header('Content-Length: ' . $filesize); header('Content-Disposition: attachment; filename=' . $file_name); // 打开文件 $fp = fopen($file, 'rb'); // 设置指针位置 fseek($fp, 0); // 开启缓冲区 ob_start(); // 分段读取文件 while (!feof($fp)) { $chunk_size = 1024 * 1024 * 2; // 2MB echo fread($fp, $chunk_size); ob_flush(); // 刷新PHP缓冲区到Web服务器 flush(); // 刷新Web服务器缓冲区到浏览器 sleep(1); // 每1秒 下载 2 MB } // 关闭缓冲区 ob_end_clean(); fclose($fp); } else { echo 'file not exists or has been removed!'; } exit();
The above is the detailed content of Why downloading php file fails. For more information, please follow other related articles on the PHP Chinese website!