Question

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.

Was it helpful?

Solution

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.

OTHER TIPS

http_response_code() in PHP 5.4 does this now.

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()?

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top