PHP如何使用header方式下載文件?

PHP通過header方式下載文件時,不能使用ajax方式提交,該方式會將header結(jié)果返回給ajax

創(chuàng)新互聯(lián)科技有限公司專業(yè)互聯(lián)網(wǎng)基礎(chǔ)服務(wù)商,為您提供重慶服務(wù)器托管高防物理服務(wù)器租用,成都IDC機(jī)房托管,成都主機(jī)托管等互聯(lián)網(wǎng)服務(wù)。

(1) 在下載大文件的時候,通常需要很長的時間,PHP有默認(rèn)執(zhí)行時間,一般是30s,超過該時間,就是下載失敗,所以需要設(shè)置一下超時時間`set_time_limit(0);`

該語句說明函數(shù)執(zhí)行不設(shè)置超時時間。另一個需要設(shè)置的就是內(nèi)存使用,設(shè)置`ini_set('memory_limit', '128M');`即可。

(2) 對于下載文件的文件名稱,下載下來可能會出現(xiàn)亂碼,當(dāng)然,這種情況出現(xiàn)在文件名包含中文或者特殊字符的情況下,此時,可以設(shè)置一下header:

$contentDispositionField = 'Content-Disposition: attachment; '
                    . sprintf('filename="%s"; ', basename($file))      
                    . sprintf("filename*=utf-8''%s", basename($file));   
header($contentDispositionField);

(3)下載buffer大小,這個可以根據(jù)服務(wù)器帶寬設(shè)置,一般4096就可以

(4)下載時,可以在echo buffer之后設(shè)置sleep(1)讓程序休眠

(5)在設(shè)置header之前,ob_clean()一下,清除緩存區(qū)內(nèi)容

1.強(qiáng)制下載本地文件

function forceDownload($file = '')
{
    set_time_limit(0);     //超時設(shè)置
    ini_set('memory_limit', '128M');    //內(nèi)存大小設(shè)置
    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;                                    //設(shè)置buffer大小
	$handle = fopen($file, 'rb');
	//總的緩沖的字節(jié)數(shù)
	$sum_buffer = 0;
	//只要沒到文件尾,就一直讀取
	while (!feof($handle) && $sum_buffer < filesize($file)) {
		echo fread($handle, $read_buffer);
		$sum_buffer += $read_buffer;
	}
	//關(guān)閉句柄
	fclose($handle);
	exit;
}

2.限制下載速率

/**
 * @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)) {
			// 發(fā)送當(dāng)前塊到瀏覽器
			print fread($file, round($downloadRate * 1024));    
			// 輸出到瀏覽器
			flush();
			// sleep one second
			sleep(1);    
		}    
		//關(guān)閉文件流
		fclose($file);}
	else {
		die('Error: The file '.$localFile.' does not exist!');
	}
}

3.下載網(wǎng)絡(luò)文件

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.獲取網(wǎng)絡(luò)文件大小

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";
}

總結(jié):

1.通過header方式下載一定不能通過ajax方式請求

2.設(shè)置超時時間

3.設(shè)置memory_limit

4.在header之前ob_clean()

5.設(shè)置buffer大小

6.可以設(shè)置sleep()減輕內(nèi)存壓力

以上就是PHP通過header方式下載文件教程的詳細(xì)內(nèi)容,更多請關(guān)注創(chuàng)新互聯(lián)其它相關(guān)文章!

分享標(biāo)題:PHP如何使用header方式下載文件?
網(wǎng)站鏈接:http://bm7419.com/article20/pssdco.html

成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供云服務(wù)器、企業(yè)網(wǎng)站制作、企業(yè)建站、動態(tài)網(wǎng)站、網(wǎng)站策劃

廣告

聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時需注明來源: 創(chuàng)新互聯(lián)

網(wǎng)站托管運(yùn)營