php - 为什么我的代码返回 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);
}
感谢您的任何帮助。
解决方案
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。
推荐阅读
- python-3.x - 我如何使用输入框输入作为 f(x)
- use-case - 需求分析和用例
- sqlite - EF Core InMemory 使用 SQLite DB - 删除行为上的外键设置为空问题
- java - apache netbeans 11.3 是否兼容 jdk 13 jdk 13 是否包含 derby 数据库?
- assembly - nasm 是否支持将浮点表达式转换为整数?
- quantum-computing - 在 qiskit 中实现量子隐形传态
- c# - 为什么方法内的代码执行了两次?
- php - 刷新后如何保存/重新提交表单信息
- java - 单击对象拖动它时,它会直接跳到角落
- clojure - 无法使用 bidi 正确路由