tags:

views:

201

answers:

4

Is there any way to have PHP automatically call a function, before a script outputs any HTTP headers?

I'm looking for something like register-shutdown-function, but to register a function that's called before the output is already sent, not after. I want my function to send a header, so I need something that's called earlier.

A: 

Check out http://www.webmasterworld.com/forum88/1225.htm You'd be using PHP's header() function to send a header (which must be called before any other output), but using your function before/during the call.

Andrew Coleson
Thanks, but that's not quite what I'm looking for. I could always call header() manually, but I'm trying to avoid making a change to every place where I return output.
JW
In other words, I want the function to be evaluated as late as possible, before the headers are sent. I don't want to start sending the headers earlier than I was before.
JW
+5  A: 

You could also trap everything with ob_start and then register a callback function to be used when you send the page with ob_end_flush. Check out the PHP manual for OB_START

charlesbridge
Looks like this is about as close as you can get.
JW
+1  A: 

I don't know if it is what you are looking for but you might want to investigate using auto_prepend_file in your php.ini or setting it in an .htaccess file. If you set an auto_prepend_file it will automatically include that file before running each script.

auto_prepend_file

ejunker
A: 

What do you mean by "automatically call a function" ? .. No headers are sent by PHP until either you emit html or issue a header() call. So it sounds like the solution is pretty trivial ?

Scott Evernden
In other words, I'm looking for something like register-shutdown-function, but something that's called before the output, rather than after it.
JW