2010-03-29 94 views
1

任何人都可以告訴我,如果它可能驗證與PHP的鏈接?通過驗證,我的意思是檢查鏈接是否處於活動狀態,並且不僅僅是鏈接的實際格式。使用php驗證鏈接

+0

檢查了這一點。 http://www.tutorialcode.com/php/link-verifier-check-if-a-url-is-valid-or-not/ – 2010-03-29 17:31:50

+0

看看[此線程在堆棧溢出](http://stackoverflow.com /問題/ 408405 /易路 - 測試-A-網址爲-404功能於PHP)。 – Jage 2010-03-29 17:31:53

回答

8

您需要執行HEAD請求並檢查響應。 200表示請求成功。還有其他人可能是found here,您可能想視爲有效。 (301和302重定向春記)

如果使用捲曲,你可以使用類似這樣

$ch = curl_init($url); 
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE); 
curl_setopt($ch, CURLOPT_HEADER, TRUE); //Include the headers 
curl_setopt($ch, CURLOPT_NOBODY, TRUE); //Make HEAD request 

$response = curl_exec($ch); 

if ($response === false){ 
    //something went wrong, assume not valid 
} 

//list of status codes you want to treat as valid:  
$validStatus = array(200, 301, 302, 303, 307); 

if(!in_array(curl_getinfo($ch, CURLINFO_HTTP_CODE), $validStatus)) { 
    //the HTTP code is not valid. The url is not valid 
} 

curl_close($ch);