views:

176

answers:

4

Hello.

I'm having problems understanding how a header("Location: http://www.google.com/"); can work in the middle of a HTML page's <body>.
Shouldn't there be an error since the header has already been sent due to the HTML output, way before the <?php ... ?> part started.

I'm referring to the warning Cannot modify header information - headers already sent by... that I'm expecting to get.

I'm testing this on my local PHP dev environment (Apache/2.2.15 (Win32) PHP/5.3.2).

Here's an example:

<html>
<head>
</head>
<body>
<?php header("Location: http://www.google.com/"); ?>
</body>
</html>

Any ideas? Thanks.

+7  A: 

It's because of output buffering...

ircmaxell
+1  A: 

If you have output buffering enabled (see ob_start()), no output is sent until the whole page is finished.

Sjoerd
+1  A: 

If you have output buffering autoenabled in php.ini then you can emit headers at any time before the output is actually sent.

Ignacio Vazquez-Abrams
+1, this is probably what the problem is - http://www.php.net/manual/en/outcontrol.configuration.php
Andy E
Is that a good thing and should I leave it enabled? It's actually pretty convenient to be able to do the forwarding with a PHP script within the HTML body instead of having a PHP script at the top of the document (IMO). Is this recommended? Thanks.
tshabala
It will prevent things such as incremental updates. I myself prefer to turn it on manually in the script than to hope that it has been enabled in the configuration of the server my script has been deployed to.
Ignacio Vazquez-Abrams
Okay, I think I'm going to enable it in my script too, then. Will this guarantee that output buffering will actually work, or is it possible that some server setting prevents it form working? Also, please tell me what the best way to turn it on manually in my scripts is.
tshabala
If you explicitly enable it in your script then there is no way for the server configuration to disable it. `ob_start()` enables it, and `ob_end_flush()` is used to send the buffer to the client.
Ignacio Vazquez-Abrams
A: 

I noticed this recently when doing some dev with a WAMP package on Windows. Caused a lot of hell when I moved to running it on a Linux box. I believe there was a config value set causing it to buffer all pages.

Sam