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!

3 Answers 3

8

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.

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks - so just to clarify, if I specify exit() immediately after the header() command, it will ignore further commands, even with output buffering enabled?
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.
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.
2

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.

Comments

1

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.

2 Comments

So, if I were to replace $a with $_SESSSION['a'], then it will get messy, unless I exit() after the header call, correct?
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)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.