听老歌 发表于 2011-05-17 13:10

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

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




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

1) 使用get_headers: <?php

$url = "http://www.abc.com/demo.jpg";
$headers = @get_headers($url);
if($headers == '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指定了只是建立连接,而不取整个报文的内容

amazergling 发表于 2011-05-17 15:15

好办法,以前光想着用curl了,没想到php还内置了这样的方法

大呀 发表于 2011-05-17 16:58

学习了,还不知道有这么一个函数

a.a 发表于 2011-05-17 18:39

如果,返回的不是404而是一个定制的页面呢?
页: [1]
查看完整版本: php中检查某个链接是否存在的两个方法