I often need to use the remote attachment function when writing the collector publishing interface, so I wrote a PHP function to remotely download files to the local. Under normal circumstances, it is enough. If the server supports the CURL function, the program will CURL will be preferred because test results show that CURL's response time and resource usage are much smaller than file_get_contents; if you have good suggestions and improvement plans, please leave a message to me!
Code:
Copy to ClipboardQuoted content:
[www.bkjia.com]
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;
}
}
}
?>
http://www.bkjia.com/PHPjc/363836.htmlwww.bkjia.comtruehttp: //www.bkjia.com/PHPjc/363836.htmlTechArticleI often write collector publishing interfaces and need to use the remote attachment function, so I wrote a PHP remote download file to Local functions are generally sufficient. If the server...