PHP instance code: Function _ PHP Tutorial for remotely downloading files to a local machine

Source: Internet
Author: User
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;
}
}
}
?>

...

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.