PHP Headers Already Sent Error

Try running the following PHP script.

<?php
 echo 'browser output';
 session_start();
?>

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().

<?php
 session_start();
 echo 'browser output';
?>

These error messages can also be seen if you add any white space to your files before and after the <?php 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.

<?php
$d = dir('folder') or die('Can\'t find directory');
while (false !== ($f = $d->read())) {
  $file = $d->path.'/'.$f;
  if (is_file($file)) {
    copy($file, $file.'.bak');
    $contents = trim(join('',file($file)));
    $fh = fopen($file,'w') or die('Can\'t open file: '.$file);
    if (-1 == fwrite($fh,$contents)) {
      die('Can\'t write to file: '.$file);
    }
    fclose($fh) or die('Can\'t close file: '.$file);
  }
}
?>

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.
CAPTCHA
1 + 5 =
Solve this simple math problem and enter the result. E.g. for 1+3, enter 4.
This question is for testing whether or not you are a human visitor and to prevent automated spam submissions.