Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP warning: headers already sent in Unknown [duplicate]

I'm looking for things that might trigger the following PHP warning:

PHP Warning: Cannot modify header information - headers already sent in Unknown on line 0

like image 205
kari.patila Avatar asked Mar 07 '09 17:03

kari.patila


2 Answers

Turned out that it was the line

ob_start("ob_gzhandler");

that caused the warning. This has been reported and fixed in 2001, it seems, but for some reason it keeps coming back.

like image 161
kari.patila Avatar answered Oct 30 '22 16:10

kari.patila


It might be a lot of things, but as the others said, it's often just a space lying around somewhere that gets outputted and then a header() command is sent which normally is fine, but not after starting to send content back (potentially just a space in this case).

Using ob_start() stops the output from going out right away by buffering it. So it's a potential solution, or at least way to diagnose where it's coming from as zodeus said.


One common thing that causes those lose spaces are in this scenario.

global.php

<?php
  $variable = 1;
  $database = 'something else';
?> <-- A space here
 <-- Or here

index.php

<?php

  require('global.php');
  $var = dosomething();
  header('Location: http://www.example.com/');

?>

One way to fix that is to remove the ?> at the end of the global.php file. You don't need those, they are only useful if you start putting HTML for example after your PHP code. So you'd have:

<?php
  $variable = 1;
  $database = 'something else';

And when you do the require(), the space is not outputted before the header().


Just to illustrate the problems with content outputted and headers is that other common case that gives a similar error. It happens when you forget to stop the processing after a redirection using header().

if ($notLoggedIn) {
  header('Location: http://www.example.com/login.php');
}
echo 'Welcome to my website'; // this will be outputted, 
                              // you should have an exit() 
                              // right after the header()
like image 38
lpfavreau Avatar answered Oct 30 '22 14:10

lpfavreau