PHP 可以检测它已经或准备发送到浏览器的状态代码吗?

发布于 2024-08-17 23:42:45 字数 437 浏览 2 评论 0原文

我通过标头函数发送状态代码,例如 header('HTTP/1.1 403');,并且希望在代码的另一个区域中检测要发送的状态代码(特别是如果我发送了某种性质的错误代码)。正如其他地方提到的,headers_list() 不会返回这个特定的项目,而且我不清楚它是否真的算作一个标头,因为 Firebug 和 Fiddler2 都不将它与标头一起对待。那么 - PHP 脚本如何检测哪个状态代码将被发送到浏览器?

我不想在标头方法周围使用包装函数(或对象),或者在发送状态代码的同时设置一些全局变量。出于性能方面的考虑,我也不想使用curl 等从自身调用我的代码。请告诉我您的想法。

I am sending a status code via the header function, such as header('HTTP/1.1 403');, and would like to in another area of my code detect what status code is to be sent (in particular if I have sent an error code of some nature). As has been mentioned elsewhere, headers_list() does not return this particular item, and it's unclear to me if it actually counts as a header, as neither Firebug nor Fiddler2 treat it with the headers. So - how can a PHP script detect which status code is about to be sent to the browser?

I would rather not use a wrapper function (or object) around the header method, or otherwise set some global variable along with the sending of the status code. I'd also rather not call my code from itself using curl or the like, due to performance concerns. Please let me know what you think.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

烦人精 2024-08-24 23:42:45

考虑设置一个常量:

define('HTTP_STATUS', 403);

并稍后使用 define 函数:

if(defined('HTTP_STATUS') && HTTP_STATUS == 403) // ...or whatever you're looking to do

实际上回看标头本身就是一种黑客行为,因为它太慢了:您正在处理字符串和数组以及所有各种其他混乱的数据。为自己设置一个简单的常量:它的速度非常快,它做同样的事情,并且它不会创建任何“真正的”全局变量。

Consider setting a constant:

define('HTTP_STATUS', 403);

and using the defined function later on:

if(defined('HTTP_STATUS') && HTTP_STATUS == 403) // ...or whatever you're looking to do

Actually peeking back at the headers themselves is kind of a hack in itself as it's simply too slow: you're dealing with strings and arrays and all sorts of other messy data. Set for yourself a simple constant: it's blazing fast, it does the same thing, and it doesn't create any "true" global variables.

別甾虛僞 2024-08-24 23:42:45

PHP 5.4 中的 http_response_code()现在就这样做。

http_response_code() in PHP 5.4 does this now.

独留℉清风醉 2024-08-24 23:42:45

这是另一个调用,但作为最后的手段,你可以使用它而不是curl。如果你有 php 5.0,get_headers() 怎么样?

It's another call, but as a last resort you could use this rather than curl. If you have php 5.0, What about get_headers()?

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文