/** * 下載遠(yuǎn)程圖片 * @param string $url 圖片的絕對(duì)url * @param string $filepath 文件的完整路徑(例如/www/images/test) ,此函數(shù)會(huì)自動(dòng)根據(jù)圖片url和http頭信息確定圖片的后綴名 * @param string $filename 要保存的文件名(不含擴(kuò)展名) * @return mixed 下載成功返回一個(gè)描述圖片信息的數(shù)組,下載失敗則返回false */ static public function downloadImage($url, $filepath, $filename) { //服務(wù)器返回的頭信息 $responseHeaders = array(); //原始圖片名 $originalfilename = ''; //圖片的后綴名 $ext = ''; $ch = curl_init($url); //設(shè)置curl_exec返回的值包含Http頭 curl_setopt($ch, CURLOPT_HEADER, 1); //設(shè)置curl_exec返回的值包含Http內(nèi)容 curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); //設(shè)置抓取跳轉(zhuǎn)(http 301,302)后的頁面 curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1); //設(shè)置最多的HTTP重定向的數(shù)量 curl_setopt($ch, CURLOPT_MAXREDIRS, 3); //服務(wù)器返回的數(shù)據(jù)(包括http頭信息和內(nèi)容) $html = curl_exec($ch); //獲取此次抓取的相關(guān)信息 $httpinfo = curl_getinfo($ch); curl_close($ch); if ($html !== false) { //分離response的header和body,由于服務(wù)器可能使用了302跳轉(zhuǎn),所以此處需要將字符串分離為 2+跳轉(zhuǎn)次數(shù) 個(gè)子串 $httpArr = explode("\r\n\r\n", $html, 2 + $httpinfo['redirect_count']); //倒數(shù)第二段是服務(wù)器最后一次response的http頭 $header = $httpArr[count($httpArr) - 2]; //倒數(shù)第一段是服務(wù)器最后一次response的內(nèi)容 $body = $httpArr[count($httpArr) - 1]; $header.="\r\n"; //獲取最后一次response的header信息 preg_match_all('/([a-z0-9-_]+):\s*([^\r\n]+)\r\n/i', $header, $matches); if (!empty($matches) && count($matches) == 3 && !empty($matches[1]) && !empty($matches[1])) { for ($i = 0; $i < count($matches[1]); $i++) { if (array_key_exists($i, $matches[2])) { $responseHeaders[$matches[1][$i]] = $matches[2][$i]; } } } //獲取圖片后綴名 if (0 < preg_match('{(?:[^\/\\\\]+)\.(jpg|jpeg|gif|png|bmp)$}i', $url, $matches)) { $originalfilename = $matches[0]; $ext = $matches[1]; } else { if (array_key_exists('Content-Type', $responseHeaders)) { if (0 < preg_match('{image/(\w+)}i', $responseHeaders['Content-Type'], $extmatches)) { $ext = $extmatches[1]; } } } //保存文件 if (!empty($ext)) { //如果目錄不存在,則先要?jiǎng)?chuàng)建目錄 if(!is_dir($filepath)){ mkdir($filepath, 0777, true); } $filepath .= '/'.$filename.".$ext"; $local_file = fopen($filepath, 'w'); if (false !== $local_file) { if (false !== fwrite($local_file, $body)) { fclose($local_file); $sizeinfo = getimagesize($filepath); return array('filepath' => realpath($filepath), 'width' => $sizeinfo[0], 'height' => $sizeinfo[1], 'orginalfilename' => $originalfilename, 'filename' => pathinfo($filepath, PATHINFO_BASENAME)); } } } } return false; } |
免責(zé)聲明:本站部分文章和圖片均來自用戶投稿和網(wǎng)絡(luò)收集,旨在傳播知識(shí),文章和圖片版權(quán)歸原作者及原出處所有,僅供學(xué)習(xí)與參考,請勿用于商業(yè)用途,如果損害了您的權(quán)利,請聯(lián)系我們及時(shí)修正或刪除。謝謝!
始終以前瞻性的眼光聚焦站長、創(chuàng)業(yè)、互聯(lián)網(wǎng)等領(lǐng)域,為您提供最新最全的互聯(lián)網(wǎng)資訊,幫助站長轉(zhuǎn)型升級(jí),為互聯(lián)網(wǎng)創(chuàng)業(yè)者提供更加優(yōu)質(zhì)的創(chuàng)業(yè)信息和品牌營銷服務(wù),與站長一起進(jìn)步!讓互聯(lián)網(wǎng)創(chuàng)業(yè)者不再孤獨(dú)!
掃一掃,關(guān)注站長網(wǎng)微信