首页 > 解决方案 > 为什么我的代码返回 http 0 响应而不是预期的 200?

问题描述

我有一个 php 函数,可以检查 URL 列表是否仍然存在(检查 HTTP 状态代码),并且效果很好。无法访问 URL 时,显示的状态码为“0”(例如:http://81.200.15.122/mjpg/video.mjpg)。但在某些情况下,即使 URL 是活动的,响应也是“0”。

例如,此 URL 有效,但我的代码返回“0”HTTP 状态代码:http: //81.149.56.38:8083/mjpg/ video.mjpg

如果我使用在线 HTTP 检查器(https://www.portcheckers.com/http-header-check),它确认状态代码应该是 200。我认为问题可能与它是 mjpg 的事实有关视频流 URL,但此其他类似 URL 返回预期的 200 状态代码:http: //204.195.155.5/mjpg/video.mjpg

这是代码:

function get_response($url) {
    $handles = curl_init($url);
    curl_setopt($handles, CURLOPT_NOBODY, true);
    curl_setopt($handles, CURLOPT_FOLLOWLOCATION, true);
    curl_setopt($handles, CURLOPT_TIMEOUT, 1);
    curl_exec($handles);
    $httpresponse = curl_getinfo($handles, CURLINFO_HTTP_CODE);
    echo ("http status code: ". $httpresponse);
}

感谢您的任何帮助。

标签: php

解决方案


cURL 在超时时返回 0。一些 URL 的延迟时间可能比其他 URL 高。如果 cURL 达到超时,它将返回 0,因为查询不完整。

function get_response($url) {
    $handles = curl_init($url);
    curl_setopt($handles, CURLOPT_NOBODY, true);
    curl_setopt($handles, CURLOPT_FOLLOWLOCATION, true);
    curl_setopt($handles, CURLOPT_CONNECTTIMEOUT, 30);
    curl_setopt($handles, CURLOPT_TIMEOUT, 30);
    curl_exec($handles);
    $httpresponse = curl_getinfo($handles, CURLINFO_HTTP_CODE);
    echo ("http status code: ". $httpresponse);
}

更改值以优化您的代码。您应该在 cron 中运行它并将结果保存在您的 sql 表中以避免减慢页面速度。您还可以添加“1 小时前上次扫描”或类似的内容。用户将立即获得列表服务,服务器端将有充足的时间查询每个 url。


推荐阅读