重定向后的 HTTP 响应代码
有一个到服务器的信息重定向,一旦来自服务器的响应,我想检查 HTTP 代码以抛出异常(如果有任何以 4XX 开头的代码)。为此,我需要知道如何从标头中仅获取 HTTP 代码?这里还涉及到服务器的重定向,所以我担心curl 对我来说没有用。
到目前为止,我已经尝试了 此解决方案,但它非常慢,并且在我的情况下会导致脚本超时。我不想增加脚本超时时间并等待更长的时间来获取 HTTP 代码。
预先感谢您的任何建议。
There is a redirect to server for information and once response comes from server, I want to check HTTP code to throw an exception if there is any code starting with 4XX. For that I need to know how can I get only HTTP code from header? Also here redirection to server is involved so I afraid curl will not be useful to me.
So far I have tried this solution but it's very slow and creates script time out in my case. I don't want to increase script time out period and wait longer just to get an HTTP code.
Thanks in advance for any suggestion.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
使用
get_headers
并请求第一个响应行的方法将返回重定向的状态代码(如果有),更重要的是,它将执行 GET 请求,该请求将传输整个文件。您只需要一个 HEAD 请求,然后解析标头并返回 last 状态代码。以下是执行此操作的代码示例,它使用
$http_response_header
而不是get_headers
,但数组的格式是相同的:有关详细信息,请参阅:HEAD 首先使用 PHP Streams,最后包含如何使用
get_headers
执行 HEAD 请求的示例代码。相关:如何检查使用 PHP 查看远程文件是否存在?
Your method with
get_headers
and requesting the first response line will return the status code of the redirect (if any) and more importantly, it will do a GET request which will transfer the whole file.You need only a HEAD request and then to parse the headers and return the last status code. Following is a code example that does this, it's using
$http_response_header
instead ofget_headers
, but the format of the array is the same:For more information see: HEAD first with PHP Streams, at the end it contains example code how you can do the HEAD request with
get_headers
as well.Related: How can one check to see if a remote file exists using PHP?
例如:
您应该尝试 HttpEngine 类。
希望这有帮助。
-
编辑
Something like:
You should try the HttpEngine Class.
Hope this helps.
--
EDIT
您找到的解决方案看起来不错。如果服务器无法及时向您发送 http 标头,则问题是另一台服务器已损坏或负载非常重。
The solution you found looks good. If the server is not able to send you the http headers in time your problem is that the other server is broken or under very heavy load.