views:

125

answers:

2

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.

A: 

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

easement
It's a reasonable suggestion, though not one I hoped for ;). I'll keep the question open for now, meanwhile I've implemented the wrapper function that I wished to avoid as I've so far had no luck finding language support for it.
michaelc
+2  A: 

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.

mattbasta
It's a good answer, though I have decided to use a global function with an internal static variable to keep track of which code I have sent. Accepting, as it answers my question best.
michaelc