Get Rid PHP Header Redirect Error

You use header(“location:address.html”); in your PHP script but keep getting the following error message?

Warning: Cannot modify header information – headers already sent by (output started at /path/yourscript.php:8) in /path/yourscript.php on line 18

The error is because your script has output before calling header().

“Remember that header() must be called before any actual output is sent, either by normal HTML tags, blank lines in a file, or from PHP…”

[ More information @ php.net ]

Beside ReWrite your script so that no output before header(), there is a dirty workaround — turn on output_buffering, a PHP setting in php.ini. Set output_buffering to On will allow you to send header lines even after you send body content, at the price of slowing PHP’s output layer a bit.(quoted from php.ini)

However, if your site are on share hosting environment then you probably no access to the php.ini file to change the setting…

No problem, we can use .htaccess!

  1. Create a .htaccess file with the following line:

    PHP_FLAG output_buffering on

  2. Then, upload it to the directory of your website.
  3. Done! You will not get the header redirection error message again.

Note: You may need to create a htaccess file then rename it to .htaccess after uploaded to web server, because Windows does not allow filename begin with a “.“(dot).

Thought:
Though it can get rid of the header error message but it is advisable to code in proper way. Here is a guideline:

  1. put your DB queries on top of the page
  2. have all (self-generated) functions return data only
  3. build you HTML code inside a variable
  4. print that variable at the end of the page

(quoted from: http://forums.devshed.com/archive/t-25099)

Similar Posts

3 Comments

  1. Put your header information on top of your page. so that you may not get header already sent error. I get php can’t redirect error. what would be the problem.

Leave a Reply

Your email address will not be published. Required fields are marked *