1

我正面临一种不寻常的卷曲行为。对于给定的页面,有时我得到 HTTP 响应代码为 200,有时我得到 0 作为 HTTP 响应代码。我无法理解此页面是否有效。如果您尝试给定的代码,请尝试至少 5-10 次,以便您看到差异。

function print_info()
{
    $url = 'bart.no';
    $arr = array(
    'bart.no',
    'bolandirekt.nu',
    'ekompassen.com',
    'ekompassen.nu',
    );

    foreach ($arr as $url)
    {
        echo "<br/>URL: " . $url;
        $temp = str_replace(array("www.", "http://", "https://"), "", strtolower($url));

        // From this array it will be decided which is to prepend
        $pre_array = array("", "www.", "https://", "http://", "https://www.", "http://www.");
        $status_code = array();

        // For each Value Status will be stored
        foreach ($pre_array as $pre)
        {

            $options = array(
                CURLOPT_RETURNTRANSFER => TRUE, // return web page
                CURLOPT_HEADER => TRUE, // don't return headers
                CURLOPT_FOLLOWLOCATION => FALSE, // follow redirects
                CURLOPT_ENCODING => "", // handle all encodings
                CURLOPT_USERAGENT => "spider", // who am i
                CURLOPT_AUTOREFERER => FALSE, // set referer on redirect
                CURLOPT_SSL_VERIFYHOST => FALSE, //ssl verify host
                CURLOPT_SSL_VERIFYPEER => FALSE, //ssl verify peer
                CURLOPT_NOBODY => FALSE,
                CURLOPT_CONNECTTIMEOUT => 20, // timeout on connect
                CURLOPT_TIMEOUT => 20, // timeout on response
            );

            // Initializing Curl
            $ch = curl_init($pre . $temp);
            // Set Curl Options
            curl_setopt_array($ch, $options);
            // Execute Curl
            $content = curl_exec($ch);

            $code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
            echo "<pre/>";
            if ($code == 200)
            {
                print_r(curl_getinfo($ch));
                break;
            }           
                            curl_close($ch);
        }
    }
}

所以我的最后一个疑问是:为什么我会为不存在或未在浏览器中打开的页面获得响应代码 200?另外,即使我保持请求之间的时间间隔,为什么有时我会得到同一页面的响应代码 0 和有时响应代码 200?

4

1 回答 1

2

CURL 请求未完成,因此没有响应代码。其原因可能是无效的主机名(无法解析)、格式错误的 URL、超时等。

您应该能够在 CodeCaster 的评论和 curl_error / curl_errno 文档中获得 CURL 错误代码。

一旦 CURL 请求正确完成,响应代码(来自服务器)应该可用且有意义。

于 2012-11-27T19:31:13.140 回答