這篇文章主要介紹了php如何實現(xiàn)下載圖片,具有一定借鑒價值,感興趣的朋友可以參考下,希望大家閱讀完這篇文章之后大有收獲,下面讓小編帶著大家一起了解一下。
php實現(xiàn)下載圖片的方法:1、使用“file_get_contents”實現(xiàn)下載圖片;2、通過使用CURL實現(xiàn)下載圖片;3、通過使用fopen實現(xiàn)下載圖片即可。
PHP下載遠程圖片的幾種方法總結(jié)
本文演示3個從遠程URL下載圖片,并保存到本地文件中的方法,包括file_get_contents,curl和fopen。
1、使用file_get_contents
function dlfile($file_url, $save_to) { $content = file_get_contents($file_url); file_put_contents($save_to, $content); }
2、使用CURL
function dlfile($file_url, $save_to) { $ch = curl_init(); curl_setopt($ch, CURLOPT_POST, 0); curl_setopt($ch,CURLOPT_URL,$file_url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); $file_content = curl_exec($ch); curl_close($ch); $downloaded_file = fopen($save_to, 'w'); fwrite($downloaded_file, $file_content); fclose($downloaded_file); }
3、使用fopen
function dlfile($file_url, $save_to) { $in= fopen($file_url, "rb"); $out= fopen($save_to, "wb"); while ($chunk = fread($in,8192)) { fwrite($out, $chunk, 8192); } fclose($in); fclose($out); }
下載與保存完整方法(輸出日志那行可刪除):
private function downloadImage($url) { $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30); $file = curl_exec($ch); curl_close($ch); $this->saveAsImage($url, $file); } private function saveAsImage($url, $file) { $filename = pathinfo($url, PATHINFO_BASENAME); $dirname = pathinfo(parse_url($url, PHP_URL_PATH), PATHINFO_DIRNAME); $path = 'public' . $dirname . '/'; $fullpath = 'public' . $dirname . '/' . $filename; // 如果目錄不存在,則創(chuàng)建 if(!is_dir($path)) { mkdir($path, 0777, true); } if(file_exists($fullpath)) { //$this->output->writeln("【已存在】輸出路徑" . $fullpath); } else { $resource = fopen($fullpath, 'a'); fwrite($resource, $file); fclose($resource); //$this->output->writeln("【已保存】輸出路徑" . $fullpath); } }
感謝你能夠認真閱讀完這篇文章,希望小編分享的“php如何實現(xiàn)下載圖片”這篇文章對大家有幫助,同時也希望大家多多支持創(chuàng)新互聯(lián)網(wǎng)站建設(shè)公司,,關(guān)注創(chuàng)新互聯(lián)行業(yè)資訊頻道,更多相關(guān)知識等著你來學習!
文章名稱:php如何實現(xiàn)下載圖片-創(chuàng)新互聯(lián)
網(wǎng)頁路徑:http://aaarwkj.com/article24/coesce.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供做網(wǎng)站、定制開發(fā)、響應(yīng)式網(wǎng)站、關(guān)鍵詞優(yōu)化、企業(yè)網(wǎng)站制作、網(wǎng)站設(shè)計公司
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時需注明來源: 創(chuàng)新互聯(lián)