在PHP中,檢查某個鏈接是否存在,有兩個方法,一個是使用curl,另外一個是獲得HTTP的header的響應(yīng)碼,如果是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個參數(shù),是true的話,結(jié)果將會是個關(guān)聯(lián)數(shù)組
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指定了只是建立連接,而不取整個報文的內(nèi)容