php判斷遠程資源是否存在

<?php
$url1='http://www.91hi.net/web/demo/1.jpg' //exists
$url2='http://91hi.net/web/demo/www/jd/image/logo.png'; //not exists 



$get1=get_headers($url1);
$get2=get_headers($url2);

print_r($get1);
print_r($get2);


返回結果:

Array
(
    [0] => HTTP/1.1 404 Not Found
    [1] => Date: Tue, 14 Mar 2017 10:58:00 GMT
    [2] => Server: Apache
    [3] => Vary: User-Agent,Accept-Encoding
    [4] => Connection: close
    [5] => Content-Type: text/html
)
Array
(
    [0] => HTTP/1.1 200 OK
    [1] => Date: Tue, 14 Mar 2017 10:58:00 GMT
    [2] => Server: Apache
    [3] => Last-Modified: Wed, 09 Nov 2016 08:57:06 GMT
    [4] => ETag: "2162a05-13f5-540da70f97c80"
    [5] => Accept-Ranges: bytes
    [6] => Content-Length: 5109
    [7] => Vary: User-Agent
    [8] => Connection: close
    [9] => Content-Type: image/png
)

可以看到返回的http狀態信息組成的一維數組.且第一個數組單元爲響應狀態信息.


於是乎,通過獲取到的狀態碼,用來判斷遠程資源是否存在。

$statusCode=substr($get1[0], 9, 3);
if($statusCode == 200 || $statusCode == 304){
    echo "It's exists."
}else{
    echo "It's not exists."
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章