PHP Headers Already Sent Error

14th February 2008 - 3 minutes read time

Try running the following PHP script.

  1. <?php
  2. echo 'browser output';
  3. session_start();
  4. ?>

You will either see normal output or get the following error messages.

This is because when you try to start the session it adds items to the headers outputted by the browser, including the setting up of cookies. To stop this happening you need to ensure that the session_start() function call is put before any output from the browser. This is the case for all header modifying functions including set_cookie() and header().

  1. <?php
  2. session_start();
  3. echo 'browser output';
  4. ?>

These error messages can also be seen if you add any white space to your files before and after the  and tags. To get around this you can use the trim() function on all of the files that you include. The following code will run through a directory and trim all of the white space from all of the files after backing the files up in case anything goes wrong.

  1. <?php
  2. $d = dir('folder') or die('Can\'t find directory');
  3. while (false !== ($f = $d->read())) {
  4. $file = $d->path.'/'.$f;
  5. if (is_file($file)) {
  6. copy($file, $file.'.bak');
  7. $contents = trim(join('',file($file)));
  8. $fh = fopen($file,'w') or die('Can\'t open file: '.$file);
  9. if (-1 == fwrite($fh,$contents)) {
  10. die('Can\'t write to file: '.$file);
  11. }
  12. fclose($fh) or die('Can\'t close file: '.$file);
  13. }
  14. }
  15. ?>

If you don't see the above error messages then your PHP engine has been set up with output buffering on. Open up the php.ini file and look for the following line.

output_buffering = 4096

Change it to this and restart the server.

output_buffering = off

Output buffering works by stopping all output to the browser until PHP has run through the code, at least up until the first 4096 bytes (the default option set in the php.ini file). It will then run any header scripts and the send any output to the browser. The drawback of using this method is that it can appear to slow down the server while the preprocessing is taking place as no output is displayed to screen until the last possible moment.

Add new comment

The content of this field is kept private and will not be shown publicly.