Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does this header location redirect work after content has already been echoed?

<?
echo "lalala";
header("Location: http://www.google.com/");

If i put this in a plain php file and deliver over a standard apache2 server with mod-php (PHP Version 5.3.2-1ubuntu4.10) the redirect to google works.

<?
echo "lalala";
flush();
header("Location: http://www.google.com/");

this code does obviously not produce a working redirect.

My question is how the first code is beeing processed and why it works. Because I remember times when things like this were not possible. Is mod-php or apache intelligent enough to buffer the whole request and arrange headers before content?

And:

Can I rely on this if I make sure I don't flush the output manually? Because it would make my application much easier...

like image 756
The Surrican Avatar asked Dec 21 '25 05:12

The Surrican


2 Answers

Output buffering is probably enabled by default. You should enable it manually if you want to rely on this functionality.

http://php.net/manual/en/function.ob-start.php

like image 161
diolemo Avatar answered Dec 22 '25 20:12

diolemo


The header function ADDS an http common header to the HTTP response. So, the redirect is setted and the browser gets the 302 message before showing you the output.

flush orders php to send the http response already prepared at the point it is called. That's why the second code won't set the header (it must be setted before sending ANY output).

And, the PHP should not output a single thing until:

  • The script is processed (even if an error stops the parsing)
  • you set it to send the output somewhere in the script with flush()

Finally, check this on output control http://www.php.net/manual/en/intro.outcontrol.php

like image 29
Alfabravo Avatar answered Dec 22 '25 19:12

Alfabravo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!