Home > Backend Development > PHP Problem > PHP download file tutorial through header method

PHP download file tutorial through header method

一朵云彩
Release: 2023-02-28 21:38:02
Original
2863 people have browsed it

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);
Copy after login

(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;
}
Copy after login

2. Limit download rate

/**
 * @param  $localFile 本地文件
 * @param  $saveFileName  另存文件名
 * @param  $downloadRate  下载速率
 */
function download_with_limitRate($localFile = &#39;&#39;,$saveFileName = &#39;&#39;,$downloadRate = 20.5)
{
	if(file_exists($localFile) && is_file($localFile)) {
		ob_clean();
		header(&#39;Cache-control: private&#39;);
		header(&#39;Content-Type: application/octet-stream&#39;); 
		header(&#39;Content-Length: &#39;.filesize($localFile));
		header(&#39;Content-Disposition: filename=&#39;.$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(&#39;Error: The file &#39;.$localFile.&#39; does not exist!&#39;);
	}
}
Copy after login

3. Download network files

function downloadFromUrl($url = &#39;&#39;, $savePath = &#39;uploads/&#39;)
{
    set_time_limit(0);
    ini_set(&#39;max_execution_time&#39;, &#39;0&#39;);
    $pi = pathinfo($url);
    $ext = $pi[&#39;extension&#39;];
    $name = $pi[&#39;filename&#39;];

    $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 . &#39;.&#39; . $ext;
    if (preg_match("/[^0-9a-z._-]/i", $saveFile)) {
        $saveFile = $savePath . &#39;/&#39; . md5(microtime(true)) . &#39;.&#39; . $ext;
    } else {
        $saveFile = $savePath . &#39;/&#39; . $name . &#39;.&#39; . $ext;
    }

    $handle = fopen($saveFile, &#39;wb&#39;);
    if(fwrite($handle, $opt)){
        echo &#39;download success&#39;;
    }
    fclose($handle);
    exit;
}
Copy after login

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(&#39;Authorization: Basic &#39; . base64_encode("$user:$pw"));
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    }
    curl_exec($ch);
    curl_close($ch);
    $head = ob_get_contents();
    ob_end_clean();
    $regex = &#39;/Content-Length:\s([0-9].+?)\s/&#39;;
    preg_match($regex, $head, $matches);
    return isset($matches[1]) ? $matches[1] : "unknown";
}
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template