PHP通过header方式下载文件教程-PHP问题

资源魔 78 0

PHP经过header形式下载文件时,不克不及应用ajax形式提交,该形式会将header后果前往给ajax

(1) 正在下载年夜文件的时分,通常需求很长的工夫,PHP有默许执行工夫,普通是30s,超越该工夫,就是下载失败,以是需求设置一下超不时间`set_time_limit(0);`

该语句阐明函数执行没有设置超不时间。另外一个需求设置的就是内存应用,设置`ini_set('memory_limit', '128M');`便可。

(2) 关于下载文件的文件称号,下载上去可能会呈现乱码,当然,这类状况呈现正在文件名蕴含中文或许非凡字符的状况下,此时,能够设置一下header:

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

(3)下载buffer巨细,这个能够依据效劳器带宽设置,普通4096就能够

(4)下载时,能够正在echo buffer之后设置sleep(1)让顺序休眠

(5)正在设置header以前,ob_clean()一下,肃清缓存区内容

1.强迫下载内陆文件

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.限度下载速度

/**
 * @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.下载网络文件

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.猎取网络文件巨细

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

总结:

1.经过header形式下载肯定不克不及经过ajax形式申请

2.设置超不时间

3.设置memory_limit

4.正在header以前ob_clean()

5.设置buffer巨细

6.能够设置sleep()加重内存压力

以上就是PHP经过header形式下载文件教程的具体内容,更多请存眷资源魔其它相干文章!

标签: php php教程 header php故障解决 php使用问题

抱歉,评论功能暂时关闭!