安利兩種php的下載函數(shù)
1.readfile
,獲取文件的句柄(注意:這里是句柄而不是文件,所以只占用很小的內(nèi)存)并將句柄輸出到緩沖區(qū)
function readfile_download($url, $filename,$opt = null)
{
//設(shè)置http下載消息報(bào)文
header("Content-Disposition: attachment; filename=" . $filename);
header("Pragma: no-cache");
header("Expires: 0");
//有些下載需要附帶cookie和useragent
$cookie = $opt['cookie'] ? $opt['cookie'] : '';
$useragent = $opt['useragent'] ? $opt['useragent'] : '';
$opts = array(
'http' => array(
'method' => 'GET',
'header' =>
"UserAgent:$useragent\r\n" .
"Cookie:$cookie \r\n",
)
);
$context = stream_context_create($opts);
readfile($url,false,$context);
}
但是緩沖區(qū)同樣有限制大小,默認(rèn)的緩沖區(qū)只有4k,一旦緩沖區(qū)溢出,同樣也會(huì)占用內(nèi)存,所以如果要進(jìn)行多人大文件下載,緩沖區(qū)也要被限制
2.使用fopen
獲取遠(yuǎn)程文件的句柄,然后使用fread
分段獲取并輸出,這樣不僅占用的內(nèi)存少,而且占據(jù)的緩沖區(qū)也少,可以用于多人大文件下載場(chǎng)景
function0 fopen_download($url, $filename,$opt = null,$limit = 1024)
{
//設(shè)置http下載消息報(bào)文
header("Content-Disposition: attachment; filename=" . $filename);
header("Pragma: no-cache");
header("Expires: 0");
//有些下載需要附帶cookie和useragent
$cookie = $opt['cookie'] ? $opt['cookie'] : '';
$useragent = $opt['useragent'] ? $opt['useragent'] : '';
$opts = array(
'http' => array(
'method' => 'GET',
'header' =>
"UserAgent:$useragent\r\n" .
"Cookie:$cookie \r\n",
)
);
$context = stream_context_create($opts);
$handle = fopen($url, "r", false, $context);
//輸出
while (!feof($handle)) {
$content = fread($handle, intval($limit));
echo $content;
ob_flush();
}
}
3.有些考慮到安全的項(xiàng)目,是會(huì)禁用fopen打開URL,又或是考慮到打開URL的穩(wěn)定性和性能,所以想使用cURL
函數(shù)
function download($url,$filename,$opt=null,$limit = 1024)
{
//curl獲取遠(yuǎn)程文件并儲(chǔ)存在臨時(shí)文件內(nèi)
$ch = curl_init();
$fp = tmpfile();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_FILE, $fp);
$cookie = $opt['cookie'] ? $opt['cookie'] : null;
$useragent = $opt['useragent'] ? $opt['useragent'] : $_SERVER['HTTP_USER_AGENT'];
curl_setopt($ch, CURLOPT_COOKIE, $cookie);
curl_setopt($ch, CURLOPT_USERAGENT, $useragent);
curl_exec($ch);
curl_close ($ch);
//設(shè)置http下載消息報(bào)文
header("Content-Disposition: attachment; filename=" . $filename);
header("Pragma: no-cache");
header("Expires: 0");
rewind($fp);
//輸出
while (!feof($fp) && is_resource($fp)) {
$content = fread($fp, $limit);
echo $content;
ob_flush();
}
//關(guān)閉并銷毀臨時(shí)文件
fclose($fp);
}