Sygmoral
Sygmoral

Reputation: 7181

PHP 5.4: prevent headers from being set after output

I am used to headers not being able to be sent after output has started. In fact, I count on it.

In the application I'm working on, after every succesful updating or inserting query, the page is reloaded with a header('Location: ...') call. That's because I don't want the page with the POST data to be refresh-able.

But while developing, one of these queries might just have a bug in them - and then I'm printing out some debug information (with echo). This would then prevent the page from being reloaded - but ever since I upgraded to php 5.4, it simply reloads anyway. I can only read the debug information if I exit; after printing the debug information - which I don't like, because some more debug information might follow later in the script.

If I check headers_sent() in one of those echo calls, it says headers have not been sent yet. So it looks like it's being buffered without me (knowingly) having turned that on.

It might of course be a php.ini setting rather than the mere fact I'm now using version 5.4, but I can't find it.

Someone have an idea?

Upvotes: 1

Views: 1513

Answers (2)

Sygmoral
Sygmoral

Reputation: 7181

jeroen answered my question (in a comment on my original question) by pointing me to the output_buffering setting in php.ini. Thank you!

Upvotes: 1

Marcin Orlowski
Marcin Orlowski

Reputation: 75629

Use output buffering to solve this. Basically all you need to do is to call ob_start(); as soon as you can. Then, instead of sending stuff out instantly, PHP would buffer the output. So it does not really matter what you set first, body or headers. They will be set in buffer, so manipulation is not a problem unless buffer is sent. If you do not flush buffer explicitly it will be sent by PHP when your script ends. See Output Buffering Control chapter in PHP manual.

Upvotes: 1

Related Questions