How I Fix PHP “Header already sent” Error

I was writing a PHP website script some days ago and when previewing it on a web browser, i got the below error message

Warning: Cannot modify header information – headers already sent by (output started at /home/zzz/public_html/header.php)

For hours, i tried solving it but all my effort prove abortive. the cause of the problem was because i was sending an HTTP headers after outputting sections of my webscript. to avoid this kind of problem, make sure all HTTP headers must be sent before any output from your script. This requires that you place calls to any PHP header function prior to any output, including < html> and < head> tags as well as any whitespace.

Using setcookie() PHP function our example header. Take a look at the code snippet below;


<!DOCTYPE html PUBLIC "-//WAPFORUM//DTD XHTML Mobile 1.2//EN"
"http://www.openmobilealliance.org/tech/DTD/xhtml-mobile12.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
  <head><title><?php echo (isset($webtitile)) ? $webtitile : "WAPDEN.NET - full wap portal";?></title>
  <link href="styles.css" rel="stylesheet" type="text/css"/></head>
<?php $Adq_COOKIE = "adq_site_cookie";
if(! isset($_COOKIE[$Adq_COOKIE])) {
        $value =  time().rand();
        setcookie($Adq_COOKIE, $value, time()+3600*24*75, "/");
    } ?>
</head>

IF you look at the code above, you will see that am setting and sending a cookie after an output from my script. such coding practise usually result to PHP Header already sent error.

Now that we know that sending header after outputting your script could lead to this error, below is the correction of code above.


<?php $Adq_COOKIE = "adq_site_cookie";
if(! isset($_COOKIE[$Adq_COOKIE])) {
        $value =  time().rand();
        setcookie($Adq_COOKIE, $value, time()+3600*24*75, "/");
    } ?>
<!DOCTYPE html PUBLIC "-//WAPFORUM//DTD XHTML Mobile 1.2//EN"
"http://www.openmobilealliance.org/tech/DTD/xhtml-mobile12.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
  <head><title><?php echo (isset($webtitile)) ? $webtitile : "WAPDEN.NET - full wap portal";?></title>
  <link href="styles.css" rel="stylesheet" type="text/css"/></head>

From the correction above, the cookie was sent before the script was outputted.

Don’t miss out!
Subscribe to My Newsletter
Invalid email address