我不明白当我回显$httpCode的时候我总是得到0,当我把$html_brand改成一个坏掉的url时我还以为是404呢。有什么是我错过或不知道的吗?谢谢。
//check if url exist
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $html_brand);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
if ($httpCode == 404) {
echo "The Web Page Cannot Be Found";
return;
}
curl_close($ch);
发布于 2012-04-19 20:50:33
如果你与服务器连接,你可以从它得到一个返回码,否则它会失败,你会得到一个0。因此,如果你尝试连接到"www.google.com/lksdfk“,你会得到一个400的返回码,如果你直接进入google.com,你会得到302 (如果你转到下一页,你会得到200……我这样做了,因为它转发到google.com.br,所以你可能得不到它),如果你去"googlecom“,你会得到一个0(主机没有找到),所以对于最后一个,没有人会发回代码。
使用以下代码进行了测试。
<?php
$html_brand = "www.google.com";
$ch = curl_init();
$options = array(
CURLOPT_URL => $html_brand,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HEADER => true,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_ENCODING => "",
CURLOPT_AUTOREFERER => true,
CURLOPT_CONNECTTIMEOUT => 120,
CURLOPT_TIMEOUT => 120,
CURLOPT_MAXREDIRS => 10,
);
curl_setopt_array( $ch, $options );
$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
if ( $httpCode != 200 ){
echo "Return code is {$httpCode} \n"
.curl_error($ch);
} else {
echo "<pre>".htmlspecialchars($response)."</pre>";
}
curl_close($ch);
发布于 2012-04-19 20:28:31
在curl_exec之后尝试一下,看看问题出在哪里:
print curl_error($ch);
如果打印内容类似于“错误格式”,请检查您的URL格式。
发布于 2014-11-20 22:22:09
检查curl_getinfo后面的curl_error,找出隐藏的错误。
if(curl_errno($ch)){
echo 'Curl error: ' . curl_error($ch);
}
https://stackoverflow.com/questions/10227879
复制相似问题