PHP get remote picture and download save to local

Source: Internet
Author: User
Tags file url
/** function: PHP Perfect implementation download remote picture saved to local * parameters: File URL, save file directory, save file name, use the download method * When the save file name is empty then use the original name of the remote file */function getImage ($url, $save _ Dir= ', $filename = ', $type =0) {if (trim ($url) = = ") {return array (' file_name ' = = ', ' save_path ' = = ', ' ERROR ' = 1);}    if (Trim ($save _dir) = = ") {$save _dir= './';}        if (Trim ($filename) = = ") {//Save file name $ext =strrchr ($url, '. ');        if ($ext! = '. gif ' && $ext! = '. jpg ') {return array (' file_name ' = = ', ' save_path ' = = ', ' ERROR ' =>3);}    $filename =time (). $ext; }if (0!==strrpos ($save _dir, '/')) {$save _dir.= '/';} Create a Save directory if (!file_exists ($save _dir) &&!mkdir ($save _dir,0777,true)) {return array (' file_name ' = ', ' save_    Path ' = = ', ' ERROR ' =>5); Gets the method used by the remote file if ($type) {$ch =curl_init (); $timeout =5;curl_setopt ($ch, Curlopt_url, $url); curl_setopt ($ch, Curlopt_    returntransfer,1) curl_setopt ($ch, Curlopt_connecttimeout, $timeout), $img =curl_exec ($ch); Curl_close ($ch);    }else{Ob_start ();   ReadFile ($url);    $img =ob_get_contents ();     Ob_end_clean (); }//$size =STRLen ($img);    File size $fp 2= @fopen ($save _dir. $filename, ' a ');    Fwrite ($fp 2, $img);    Fclose ($fp 2); unset ($img, $url); The return array (' file_name ' = $filename, ' save_path ' = = $save _dir. $filename, ' error ' =>0);}
  • Related Article

    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.