当前位置:Gxlcms > PHP教程 > php中稽查某个链接是否存在的两个方法

php中稽查某个链接是否存在的两个方法

时间:2021-07-01 10:21:17 帮助过:14人阅读

php中检查某个链接是否存在的两个方法
在PHP中,检查某个链接是否存在,有两个方法,一个是使用curl,另外一个是
获得HTTP的header的响应码,如果是200的则是OK,如果是404的话就找不到了,例子如下:

1) 使用get_headers:

$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
$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指定了只是建立连接,而不取整个报文的内容

人气教程排行