tags:

views:

64

answers:

3

Simple question:

If I enable output buffering...

ob_start();
  $a = true;
  header('Location: page.php'); 
  $a = false;
ob_end_flush();

... will $a be registered as false, or will it just redirect the page without processing the command (as it would if output buffering were not enabled)?

Thanks!

+5  A: 

Unless you call exit() or die() after the header redirect, $a will be false as the rest of the page continues to parse (with or without the buffering).

Unless you have a special reason, header("Location: ..."); should always be followed by one of the above functions as to not waste cpu cycles or memory.

Mike B
Thanks - so just to clarify, if I specify exit() immediately after the header() command, it will ignore further commands, even with output buffering enabled?
RC
Yes, using `exit()` will automatically flush whatever is in the buffer to the browser. You can prevent this by using `ob_end_clean()` before exiting.
Mike B
Keep in mind that `header('Location:...')` advises _the client_ to send a new request (at some time in the future; you don't _know_ if and when this will happen) . For each request a new instance of php is created. Setting $a=false within the old instance has no influence on the new instance.
VolkerK
A: 

Output buffering does exactly what the name infers, nothing more. It only buffers the output, not variable assignment or object state. In this case $a would be set to false at the end of the code sample you provided. What happens after that is up to your code execution.

Doug Neiner
A: 

It would redirect to page.php without* processing the rest of the commands.

*Technically, execution continues on past the header call unless you specifically stop it after (die, exit). You'll never notice this if you are just setting variables and displaying stuff, but if you have commands that change a database, it can be very difficult to find out where those changes are coming from.

davethegr8
So, if I were to replace $a with $_SESSSION['a'], then it will get messy, unless I exit() after the header call, correct?
RC
The default session handler of php keeps a lock on the session file. The php instance for the "new" request would have to wait until the old instance stops the session mechanism (by calling session_write_close() or terminating the script)
VolkerK
@RC - That's correct.
davethegr8