范文 |
在PHP中,检查某个链接是否存在,有两个方法,一个是使用curl,另外一个是获得HTTP的header的响应码,如果是200的则是OK,如果是404的话就找不到了,例子如下: 1) 使用get_headers: <?php $url = "http://www.abc.com/demo.jpg"; $headers = @get_headers($url); if($headers[0] == 'HTTP/1.1 404 Not Found') { echo "URL not Exists"; } else { echo "URL Exists"; } ?> get_headers中有第2个参数,是true的话,结果将会是个关联数组 2) 使用CURL <?php $url = "http://www.domain.com/demo.jpg"; $curl = curl_init($url); curl_setopt($curl, CURLOPT_NOBODY, true); $result = curl_exec($curl); if ($result !== false) { $statusCode = curl_getinfo($curl, CURLINFO_HTTP_CODE); if ($statusCode == 200) { echo "URL Exists" } } else { echo "URL not Exists"; } ?> CURLOPT_NOBODY指定了只是建立连接,而不取整个报文的内容
|