PHP 遠端圖片下載

來源:互聯網
上載者:User

標籤:http   io   os   ar   檔案   art   on   c   cti   

<?php/** *php實現下載遠程圖片到本地 *@param $url       string      遠程檔案地址 *@param $filename  string      儲存後的檔案名稱(為空白時則為隨機產生的檔案名稱,否則為原檔案名稱) *@param $fileType  array       允許的檔案類型 *@param $dirName   string      檔案儲存的路徑(路徑其餘部分根據時間系統自動產生) *@param $type      int         遠程擷取檔案的方式 *@return           json        返迴文件名、檔案的儲存路徑 *  * 例子:{‘fileName‘:13668030896.jpg, ‘saveDir‘:/www/test/img/2013/04/24/} */echo getImage(‘http://img.wan.renren.com/images/2013/0430/1367294093164.jpg‘, ‘‘, ‘/www/test/img/‘, array(‘jpg‘, ‘gif‘));function getImage($url, $filename=‘‘, $dirName, $fileType, $type=0){    if($url == ‘‘){return false;}    //擷取檔案原檔案名稱    $defaultFileName = basename($url);    //擷取檔案類型    $suffix = substr(strrchr($url,‘.‘), 1);    if(!in_array($suffix, $fileType)){        return false;    }    //設定儲存後的檔案名稱    $filename = $filename == ‘‘ ? time().rand(0,9).‘.‘.$suffix : $defaultFileName;              //擷取遠程檔案資源    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);        $file = curl_exec($ch);        curl_close($ch);    }else{        ob_start();        readfile($url);        $file = ob_get_contents();        ob_end_clean();    }    //設定檔案儲存路徑    $dirName = $dirName.‘/‘.date(‘Y‘, time()).‘/‘.date(‘m‘, time()).‘/‘.date(‘d‘,time()).‘/‘;    if(!file_exists($dirName)){        mkdir($dirName, 0777, true);    }    //儲存檔案    $res = fopen($dirName.$filename,‘a‘);    fwrite($res,$file);    fclose($res);    return "{‘fileName‘:$filename, ‘saveDir‘:$dirName}";}

PHP 遠端圖片下載

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.