PHP cURL HTTP CODE 返回 0 [英] PHP cURL HTTP CODE return 0

查看:109
本文介绍了PHP cURL HTTP CODE 返回 0的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不明白当我回显 $httpCode 时我总是得到 0,当我将 $html_brand 更改为损坏的 url 时,我期待 404.有什么我想念或不知道的吗?谢谢.

I dont understand when I echo $httpCode I always get 0, I was expecting 404 when I change $html_brand into a broken url. Is there anything that I miss or do not know of? Thanks.

 //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);

推荐答案

如果你连接到服务器,那么你可以从它那里得到一个返回码,否则它会失败并且你得到一个 0.所以如果你尝试连接到www.google.com/lksdfk",你会得到一个 400 的返回码,如果你直接去 google.com,你会得到 302(如果你转发到下一页,然后是 200......我这样做是因为它转发到 google.com.br,所以你可能不会得到它),如果你去googlecom"你会得到一个 0(找不到主机),所以最后一个,没有人可以发回代码.

If you connect with the server, then you can get a return code from it, otherwise it will fail and you get a 0. So if you try to connect to "www.google.com/lksdfk" you will get a return code of 400, if you go directly to google.com, you will get 302 (and then 200 if you forward to the next page... well I do because it forwards to google.com.br, so you might not get that), and if you go to "googlecom" you will get a 0 (host no found), so with the last one, there is nobody to send a code back.

使用以下代码进行测试.

Tested using the code below.

<?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} 
"
        .curl_error($ch);
} else {
    echo "<pre>".htmlspecialchars($response)."</pre>";
}

curl_close($ch);

这篇关于PHP cURL HTTP CODE 返回 0的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆