php - 我正在用 php 编写链接检查器,当站点显示“找不到此页面”之类的屏幕时,我无法收到 HTTP 错误(例如 404 或 400)
问题描述
我正在制作一个链接检查器工具,以避免我们网站内容中的链接断开,并且当页面不存在或无法加载时它可以工作 - 除非外部网站用一个屏幕替换它,上面写着“这个页面没有似乎不存在。从我们的菜单中搜索您要查找的内容...'。除了这个工具的 html/css/js 代码,这里是检查链接的主要 PHP 代码
$headers = get_headers($url);
$headers = (is_array($headers)) ? implode( "\n ", $headers) : $headers;
$exists = (bool)preg_match('#^HTTP/.*\s+[(200|301|302)]+\s#i', $headers);
$status = (is_array($headers)) ? $headers[0] : $headers;
然后 js 使用包括 $status 在内的这些信息,但是当外部站点显示“未找到”屏幕(例如http://www.drdansiegel.com/resources/healthy_mind_platter
)时,它不会返回错误代码。
解决方案
在解析到 404 之前,您会返回重定向。我会颠倒您的逻辑,检查您是否有404
或400
曾经存在。
$notexists = (bool)preg_match('#^HTTP/.*\s40[04]\s#mi', $headers);
此外,您应该使用m
修饰符,以便前导锚匹配每一行,而不是整个字符串。
此外,请注意字符类是字符列表,您不能像以前那样在其中进行分组。[(200|301|302)]
说 a (
, 2
, 0
, 0
(again), |
, 3
, 0
(again) 等都是允许的。你会这样写,就(200|301|302)
好像你想要200
, 301
, or302
被允许的字符一样。您可以对重定向状态代码的最后一个整数使用字符类(并且应该添加7
和8
,就好像也是有效的重定向一样)。所以它可能是(200|30[1278])
。
这是您$headers
从示例链接中包含的内容:
Array
(
[0] => HTTP/1.1 301 Moved Permanently
[1] => Server: nginx
[2] => Date: Sat, 15 May 2021 01:57:44 GMT
[3] => Content-Type: text/html
[4] => Content-Length: 162
[5] => Connection: close
[6] => Location: https://www.drdansiegel.com/resources/healthy_mind_platter
[7] => HTTP/1.1 301 Moved Permanently
[8] => Server: nginx
[9] => Date: Sat, 15 May 2021 01:57:45 GMT
[10] => Content-Type: text/html; charset=UTF-8
[11] => Content-Length: 0
[12] => Connection: close
[13] => Expires: Sat, 15 May 2021 02:57:45 GMT
[14] => Cache-Control: max-age=3600
[15] => X-Redirect-By: WordPress
[16] => Location: https://drdansiegel.com/resources/healthy_mind_platter
[17] => HTTP/1.1 404 Not Found
[18] => Server: nginx
[19] => Date: Sat, 15 May 2021 01:57:46 GMT
[20] => Content-Type: text/html; charset=UTF-8
[21] => Connection: close
[22] => Vary: Accept-Encoding
[23] => Expires: Wed, 11 Jan 1984 05:00:00 GMT
[24] => Cache-Control: no-cache, must-revalidate, max-age=0
[25] => Link: <https://drdansiegel.com/wp-json/>; rel="https://api.w.org/"
)
推荐阅读
- html - 文本动画无法正常工作,其中存在小光标问题
- ember.js - EmberJS:无法读取未定义的属性“_application”
- macos - 专注于通过服务启动另一个应用程序的第一个应用程序
- object - firefox gBrowser.contentWindow 为空
- kubernetes - 更改挂载卷中的 Kubernetes 机密文件格式
- javascript - 如何使用 data-attr 在选择框中创建锚点
- c# - 读取具有不同编码的多个文件,保留所有字符
- angular - Angular PrimeNG p-chartchartsjs 未显示
- angular - 在 c3.generate 方法上设置 data.id
- java - OpenJFX / JavaFX 16 WebView 无法使用 WebGL 显示简单的网页