PHP cURL无信号

时间:2012-10-20 23:01:30

标签: php curl

我有一个简单的cURL脚本,效果很好。 但我很好奇如何检测坏网址。而“坏”我指的是一个不存在的URL,或者如果我正在呼叫的服务器停机了一段时间,或者我犯了一个错误并输入了错误的URL。 (仅举例)

这是我到目前为止所拥有的:

<?php

$url = 'http://someurl_or_ip.com/some_file.php';
$post_fields = "type=whatever";
$post_fields .= "&first=".$first;
$post_fields .= "&last=".$last;


$ch = curl_init($url); // create a new cURL resource 
curl_setopt($ch, CURLOPT_POST,1); 
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_fields); 
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST,  2); 
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); 
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);   
curl_setopt($ch, CURLOPT_TIMEOUT, 1800);  

// Execute the request. 
$raw_response = curl_exec($ch); 
$succeeded  = curl_errno($ch) == 0 ? true : false; 

echo $raw_response;

?>

通常$ raw_response是我可以解析并用于其他事情的东西,比如我想向用户显示数据。

我只是用一个不存在的文件(但是到一个有效的域)替换了$ url,我得到“Not Found ....在这个服务器上找不到请求的URL .....”

这是否意味着我需要解析此apache服务器消息以确定它不是一个好的URL?或者cURL是否有办法通过标题信息检测它?

1 个答案:

答案 0 :(得分:2)

您可以查看标题中的HTTP响应代码,对于找不到的文件,该代码为404;

$http = curl_init($url);
$result = curl_exec($http);
$http_status = curl_getinfo($http, CURLINFO_HTTP_CODE);
curl_close($http);
echo $http_status;

如果服务器不可用,您显然根本无法从服务器获得响应,因此没有HTTP响应代码。在这种情况下,curl_exec()将返回false,在这种情况下,您可以处理错误:

if(curl_exec($ch) !== false) {
    // Success
} else {
    // Error
    $error_str = curl_error($ch);
    $error_num = curl_errno($ch);
}