Home  >  Article  >  Backend Development  >  PHP example code: implement the function of downloading files remotely to the local_PHP tutorial

PHP example code: implement the function of downloading files remotely to the local_PHP tutorial

WBOY
WBOYOriginal
2016-07-21 14:58:29718browse

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 ClipboardLiehuo.Net CodesQuoted 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;
}
}
}
?>

www.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...
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn