When PHP downloads files through the header method, it cannot be submitted using the ajax method. This method will return the header results to ajax
(1) When downloading large files, it is usually necessary to For a long time, PHP has a default execution time, usually 30s. If it exceeds this time, the download will fail, so you need to set the timeout `set_time_limit(0);`
This statement Description Function execution does not set a timeout. Another thing that needs to be set is memory usage. Just set `ini_set('memory_limit', '128M');`
.
(2) The file name of the downloaded file may be garbled when downloaded. Of course, this situation occurs when the file name contains Chinese or special characters. At this time, you can set the header:
$contentDispositionField = 'Content-Disposition: attachment; ' . sprintf('filename="%s"; ', basename($file)) . sprintf("filename*=utf-8''%s", basename($file)); header($contentDispositionField);
(3) Download buffer size, this can be set according to the server bandwidth, generally 4096 is enough
(4) When downloading, you can set sleep(1) after the echo buffer to let the program sleep
(5) Before setting the header, use ob_clean() to clear the cache contents
1. Force download of local files
function forceDownload($file = '') { set_time_limit(0); //超时设置 ini_set('memory_limit', '128M'); //内存大小设置 ob_clean(); header("Pragma: public"); header("Expires: 0"); header("Cache-Control: must-revalidate, post-check=0, pre-check=0"); header("Content-Type: application/force-download"); header("Content-Type: application/octet-stream"); header("Content-Type: application/download"); $contentDispositionField = 'Content-Disposition: attachment; ' . sprintf('filename="%s"; ', basename($file)) . sprintf("filename*=utf-8''%s", basename($file)); //处理文件名称 header($contentDispositionField); header("Content-Transfer-Encoding: binary"); header("Content-Length: " . filesize($file)); $read_buffer = 4096; //设置buffer大小 $handle = fopen($file, 'rb'); //总的缓冲的字节数 $sum_buffer = 0; //只要没到文件尾,就一直读取 while (!feof($handle) && $sum_buffer < filesize($file)) { echo fread($handle, $read_buffer); $sum_buffer += $read_buffer; } //关闭句柄 fclose($handle); exit; }
2. Limit download rate
/** * @param $localFile 本地文件 * @param $saveFileName 另存文件名 * @param $downloadRate 下载速率 */ function download_with_limitRate($localFile = '',$saveFileName = '',$downloadRate = 20.5) { if(file_exists($localFile) && is_file($localFile)) { ob_clean(); header('Cache-control: private'); header('Content-Type: application/octet-stream'); header('Content-Length: '.filesize($localFile)); header('Content-Disposition: filename='.$saveFileName); flush(); // 打开文件流 $file = fopen($localFile, "r"); while(!feof($file)) { // 发送当前块到浏览器 print fread($file, round($downloadRate * 1024)); // 输出到浏览器 flush(); // sleep one second sleep(1); } //关闭文件流 fclose($file);} else { die('Error: The file '.$localFile.' does not exist!'); } }
3. Download network files
function downloadFromUrl($url = '', $savePath = 'uploads/') { set_time_limit(0); ini_set('max_execution_time', '0'); $pi = pathinfo($url); $ext = $pi['extension']; $name = $pi['filename']; $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_HEADER, false); curl_setopt($ch, CURLOPT_BINARYTRANSFER, true); curl_setopt($ch, CURLOPT_AUTOREFERER, true); curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $opt = curl_exec($ch); curl_close($ch); $saveFile = $name . '.' . $ext; if (preg_match("/[^0-9a-z._-]/i", $saveFile)) { $saveFile = $savePath . '/' . md5(microtime(true)) . '.' . $ext; } else { $saveFile = $savePath . '/' . $name . '.' . $ext; } $handle = fopen($saveFile, 'wb'); if(fwrite($handle, $opt)){ echo 'download success'; } fclose($handle); exit; }
4. Get the network file size
function remote_filesize($url, $user = "", $pw = "") { ob_start(); $ch = curl_init($url); curl_setopt($ch, CURLOPT_HEADER, 1); curl_setopt($ch, CURLOPT_NOBODY, 1); if (!empty($user) && !empty($pw)) { $headers = array('Authorization: Basic ' . base64_encode("$user:$pw")); curl_setopt($ch, CURLOPT_HTTPHEADER, $headers); } curl_exec($ch); curl_close($ch); $head = ob_get_contents(); ob_end_clean(); $regex = '/Content-Length:\s([0-9].+?)\s/'; preg_match($regex, $head, $matches); return isset($matches[1]) ? $matches[1] : "unknown"; }
Summary:
1. Download through header method and must not request through ajax method
2. Set timeout
3. Set memory_limit
4. Ob_clean() before header
5. Set buffer size
6. You can set sleep() to reduce memory pressure
The above is the detailed content of PHP download file tutorial through header method. For more information, please follow other related articles on the PHP Chinese website!