經(jīng)常寫采集器發(fā)布接口需要使用到遠(yuǎn)程附件的功能,所以自己寫了一個(gè)PHP遠(yuǎn)程下載文件到本地的函數(shù),一般情況下已經(jīng)夠用了,如果服務(wù)器支持CURL函數(shù),程序則會(huì)優(yōu)先選擇CURL,因?yàn)闇y試結(jié)果表明CURL的響應(yīng)時(shí)間及資源占用率比file_get_contents小得多;如果大家有好的建議及改進(jìn)方案,歡迎留言給我哦!
代碼:
echo httpcopy("");
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;
}
}
}
?>
更多信息請查看IT技術(shù)專欄