Often write collector release interface need to use the function of remote attachment, so write a php remote download file to the local function, generally enough, if the server support Curl function, the program will choose Curl, Because the test results show that curl response time and resource occupancy rate is much smaller than file_get_contents; if you have good suggestions and improvement plans, please leave a message to me Oh!
Code:
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;
}
}
}
?>