PHP instance code: implements a function to remotely download files to a local device. The function of remote attachment is often used for writing Collector Publishing interfaces, so I wrote a function for remotely downloading files from PHP to a local place, which is usually enough, if the server frequently writes the collector's publishing interface to use the remote attachment function, you have written a function for remotely downloading files from PHP to a local location, which is usually enough, if the server supports the CURL function, the program selects CURL first, because the test result shows that the response time and resource usage of CURL are much smaller than that of file_get_contents. if you have good suggestions and improvement solutions, please leave a message to me!
Code:
Copy to ClipboardReference: [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;
}
}
}
?>
...