Header Redirect after echo in PHP

teammatt3's picture

He has: 2,102 posts

Joined: Sep 2003

In a PHP script, I have something like:

<?php
// lots of stuff

echo "some debug output or something";
header("Location: somepage.php");
?>

On one server, that works perfectly fine, on another server I just setup, it won't work. I get the classic "Warning: Cannot modify header information..."

Do you know what setting in PHP or Apache that allows the header to change even after an echo? Is there a setting that suppresses echo and print statements until the end of execution?

pr0gr4mm3r's picture

He has: 1,502 posts

Joined: Sep 2006

Using output buffering is a good way to ensure that no output gets in the way of sending headers, cookies, etc. At the beginning of the script, put

<?php
ob_start
()
?>
, and at the end, put
<?php
ob_end_flush
();
?>
.

teammatt3's picture

He has: 2,102 posts

Joined: Sep 2003

Genius!

I looked in the PHP.ini file for something about output buffering, and it was turned off on the second server. That fixed it.

It's probably best to leave output buffering off by default, and use it manually, but I have a lot of legacy scripts I don't want to fix Smiling

Want to join the discussion? Create an account or log in if you already have one. Joining is fast, free and painless! We’ll even whisk you back here when you’ve finished.