2010-03-29 91 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);