判斷鏈接是否為圖片


方式一
直接正則匹配URL鏈接,是否是以.png,.gif,.jpg,.jpeg結尾的。

preg_match('/.*(\.png|\.jpg|\.jpeg|\.gif)$/', $url);
1
這個是一個最簡單的方式,但是不夠精確,因為並不是所有的圖片鏈接都是以圖片名字+擴展名結尾的。

方式二
用CURL獲取圖片URL的response header

首先創建一個curl,並將頭文件的信息,作為數據流輸出

$url = "http://*************"; //圖片的鏈接地址
$ch = curl_init();
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1); //是否跟着爬取重定向的頁面
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); //將curl_exec()獲取的值以文本流的形式返回,而不是直接輸出。
curl_setopt($ch, CURLOPT_HEADER, 1); // 啟用時會將頭文件的信息作為數據流輸出
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5); //設置超時時間
curl_setopt($ch, CURLOPT_URL, $url); //設置URL
$content = curl_exec($ch);
$httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE); //curl的httpcode
$headerSize = curl_getinfo($ch, CURLINFO_HEADER_SIZE); //獲取頭大小
curl_close($ch);

此時content中包含頭信息和圖片的二進制內容,然后根據頭的大小($headerSize)截取出頭信息,剩下的就是圖片的二進制內容了。

$headers = substr($content, 0, $headerSize); //根據頭大小截取頭信息
1
頭信息輸出結構如下

HTTP/1.1 200 OK
Server: JSP3/2.0.14
Date: Sun, 30 Jul 2017 06:54:47 GMT
Content-Type: image/jpeg
Content-Length: 152094
Connection: keep-alive
ETag: "7751852900776331536"
Last-Modified: Tue, 02 May 2017 10:33:16 GMT
Expires: Wed, 18 Jul 2018 06:25:38 GMT
Age: 879492
Cache-Control: max-age=31536000
Accept-Ranges: bytes
Error-Message: OK
Ohc-Response-Time: 1 0 0 0 0 0

可以看到里面有個Content-Type: image/jpeg,然后處理頭信息,取出想要的內容

$head_data=preg_split('/\n/',$headers); //逐行放入數組中
$head_data = array_filter($head_data); //過濾空數組
$headers_arr = [];
foreach($head_data as $val){ //按:分割開
list($k,$v) = explode(":",$val); //:前面的作為key,后面的作為value,放入數組中
$headers_arr[$k] = $v;
}
$img_type = explode("/",trim($headers_arr['Content-Type'])); //然后將獲取到的Content-Type中的值用/分隔開
if ($httpcode == 200 && strcasecmp($img_type[0],'image') == 0) {//如果httpcode為200,並且Content-type前面的部分為image,則說明該鏈接可以訪問成功,並且是一個圖片類型的
$type = $img_type[1];
.............
} else {//否則........
............
}

注: curl_setopt($ch, CURLOPT_NOBODY,true); 可以設置只獲取頭信息,不要body

方式三
用PHP的get_headers() 函數,可以直接獲取響應的頭信息,但是相比於curl,不能設置超時時間。

<?php
$url = 'http://www.example.com';

print_r(get_headers($url));

print_r(get_headers($url, 1));
?>

Array
(
[0] => HTTP/1.1 200 OK
[1] => Date: Sat, 29 May 2004 12:28:13 GMT
[2] => Server: Apache/1.3.27 (Unix) (Red-Hat/Linux)
[3] => Last-Modified: Wed, 08 Jan 2003 23:11:55 GMT
[4] => ETag: "3f80f-1b6-3e1cb03b"
[5] => Accept-Ranges: bytes
[6] => Content-Length: 438
[7] => Connection: close
[8] => Content-Type: text/html
)

Array
(
[0] => HTTP/1.1 200 OK
[Date] => Sat, 29 May 2004 12:28:14 GMT
[Server] => Apache/1.3.27 (Unix) (Red-Hat/Linux)
[Last-Modified] => Wed, 08 Jan 2003 23:11:55 GMT
[ETag] => "3f80f-1b6-3e1cb03b"
[Accept-Ranges] => bytes
[Content-Length] => 438
[Connection] => close
[Content-Type] => text/html
)
---------------------


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM