存在简单的CURL网址将无法正常工作

时间:2012-03-07 10:33:46

标签: php http curl

我有两个用PHP编写的代码

<?php
error_reporting(1);

function url_exists($url) 
{
    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_HEADER, TRUE);
    curl_setopt($ch, CURLOPT_NOBODY, TRUE);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, FALSE);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
    $status = array();
    preg_match('/HTTP\/.* ([0-9]+) .*/', curl_exec($ch) , $status);
    return ($status[1] == 200);
}

echo "EX:".url_exists("http://www.google.com");

?>

<?php
error_reporting(1);

$ch = curl_init("www.yahoo.com");  
curl_setopt($ch, CURLOPT_TIMEOUT, 2);  
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 2);  
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);  
$data = curl_exec($ch);  
$httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);  
curl_close($ch);  
if($httpcode>=200 && $httpcode<300)
{  
    echo "Found@";  
} 
else 
{  
    echo "Not found";  
}  

?>

上述这些都不起作用吗?为什么???昨天工作得很好,为什么PHP有些时候无法解释?

我有来自php.ini的curl扩展...我试过3个不同的服务器......

我做错了什么?谢谢。

1 个答案:

答案 0 :(得分:1)

echo "EX:".url_exists("http://www.google.com");

将始终回显EX:,因为url_exists返回一个布尔值。尝试:

echo "EX:" . (url_exists("http://www.google.com") ? 'true' : 'false');

也许这有用吗?

$ch = curl_init("http://www.example.com/favicon.ico");
curl_setopt($ch, CURLOPT_NOBODY, true);
curl_exec($ch);
$retcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
// $retcode > 400 -> not found, $retcode = 200, found.
curl_close($ch);

来源https://stackoverflow.com/a/982045/956397