PHP實(shí)例代碼:實(shí)現(xiàn)遠(yuǎn)程下載文件到本地的函數(shù)
來源:程序員人生 發(fā)布時間:2013-10-17 07:09:39 閱讀次數(shù):2417次
經(jīng)常寫采集器發(fā)布接口需要使用到遠(yuǎn)程附件的功能,所以自己寫了一個PHP遠(yuǎn)程下載文件到本地的函數(shù),一般情況下已經(jīng)夠用了,如果服務(wù)器支持CURL函數(shù),程序則會優(yōu)先選擇CURL,因?yàn)闇y試結(jié)果表明CURL的響應(yīng)時間及資源占用率比file_get_contents小得多;如果大家有好的建議及改進(jìn)方案,歡迎留言給我哦!
代碼:
Copy to Clipboard
引用的內(nèi)容:
[www.veryhuo.com] <?php
echo httpcopy("http://www.baidu.com/img/baidu_sylogo1.gif");
function httpcopy($url, $file="", $timeout=60) {
$file = empty($file) ? pathinfo($url,PATHINFO_BASENAME) : $file;
$dir = pathinfo($file,PATHINFO_DIRNAME);
!is_dir($dir) && @mkdir($dir,0755,true);
$url = str_replace(" ","%20",$url);
if(function_exists('curl_init')) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
$temp = curl_exec($ch);
if(@file_put_contents($file, $temp) && !curl_error($ch)) {
return $file;
} else {
return false;
}
} else {
$opts = array(
"http"=>array(
"method"=>"GET",
"header"=>"",
"timeout"=>$timeout)
);
$context = stream_context_create($opts);
if(@copy($url, $file, $context)) {
//$http_response_header
return $file;
} else {
return false;
}
}
}
?>
生活不易,碼農(nóng)辛苦
如果您覺得本網(wǎng)站對您的學(xué)習(xí)有所幫助,可以手機(jī)掃描二維碼進(jìn)行捐贈