下面這段代碼錯哪了

來源:互聯網
上載者:User
下面這段代碼哪裡錯了?


/**
* 下載遠程圖片
* @param string $url 圖片的絕對url
* @param string $filepath 檔案的完整路徑(包括目錄,不包括尾碼名,例如/www/images/test) ,此函數會自動根據圖片url和http頭資訊確定圖片的尾碼名
* @return mixed 下載成功返回一個描述圖片資訊的數組,下載失敗則返回false
*/
function downloadImage($url, $filepath) {
//伺服器返回的頭資訊
$responseHeaders = array();
//原始圖片名
$originalfilename = '';
//圖片的尾碼名
$ext = '';
$ch = curl_init($url);
//設定curl_exec返回的值包含Http頭
curl_setopt($ch, CURLOPT_HEADER, 1);
//設定curl_exec返回的值包含Http內容
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
//設定抓取跳轉(http 301,302)後的頁面
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
//設定最多的HTTP重新導向的數量
curl_setopt($ch, CURLOPT_MAXREDIRS, 2);

//伺服器返回的資料(包括http頭資訊和內容)
$html = curl_exec($ch);
//擷取此次抓取的相關資訊
$httpinfo = curl_getinfo($ch);
curl_close($ch);
if ($html !== false) {
//分離response的header和body,由於伺服器可能使用了302跳轉,所以此處需要將字串分離為 2+跳轉次數 個子串
$httpArr = explode("\r\n\r\n", $html, 2 + $httpinfo['redirect_count']);
//倒數第二段是伺服器最後一次response的http頭
$header = $httpArr[count($httpArr) - 2];
//倒數第一段是伺服器最後一次response的內容
$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];
}
}
  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.