Solve PHP error: Cannot modify header information – headers already sent

Contributor Icon Contributed by qmchenry Date Icon July 10, 2006  
Tag Icon Tagged: PHP programming

This error message is commonly seen by programmers starting to use PHP. Understanding why this error occurs will help find the solution.


PHP handles lots of the work of generating web pages for you, without you even having to ask. A web page is composed of two parts, the header and the body.

The header is generally stuff that you don’t need to worry about, is generated automatically, and contains information about the page, the server, related cookies, and so on. The header information is important, but it is not typically seen by the user. Here are some examples:

Date: Mon, 10 Jul 2006 18:51:59 GMT
Server: Apache/2.2.0 (Unix) mod_ssl/2.2.0 OpenSSL/0.9.7g
Content-Encoding: gzip
Content-Type: text/html

Sometimes programmers want to change some of the header values. For example, if the PHP if generating XML output, the Content-Type should be changed to reflect this. Another common example is in redirecting the user’s browser to a different web page using the Location header element as described in this Tech-Recipe.

The header must come first in the response from a web server and is separated from the body by one blank line. The reason this error occurs is that some part of the body of the web page has been sent to the user already when a request is made to set a header value. Because PHP simplifies many things for you, the problem may be hiding in plain site. Here are some guidelines for finding the problem:

    1) Find the header() statement that is causing the problem. The error must be at or before this line.

    2) Look for any statements that could send output to the user before this header statement. If you find one or more, find some way to move the header statement before them. Complex conditional statements may complicate the issue, but they may also help solve the problem. Consider a conditional expression at the top of the PHP script that determines the header value as early as possible and sets it there.

    3) Make sure there is no white space outside of the php start and end tags. While a blank line before the <?php start tag may look innocent, when processed by PHP, it will turn into an echo statement printing out a blank line. This is a common culprit.

Previous recipe | Next recipe |
 
  • Anonymous
    In many occasions this is NOT a bug. Look at the following scenario:

    You run the code. It is stuck somewhere. You set display_errors=On (in php.ini or somewhere else) and run again. This time is shows some Notice then it is stuck at the point where there is a call for header function and displays this "Warning: Cannot modify header information - headers already sent by (output ...". You are thinking this is the bug you have to fix and try this and that. You are WRONG. Your bug is somewhere else past the header function.

    When you run the code with display_errors=On and when you see the first Notice about something, the browser already got the header to display the Notice and cannot change the header in the header function which follows after the Notice(s).

    That means you cannot see any errors past a header function with display_errors=On and there are some notice(s) you wish to ignore.

    The solution is resolve all the notices prior to that warning or keep the display_errors=Off and see the error log to find the real problem. Thanks
  • Anonymous
    Good Day!

    i do consider this as a bug. Setting display_error = Off only hides the message error from the user's GUI. And still your header('location: xxx.php') wont work. If you dont have much time tracing your scripts, try this solution:

    output_buffering = 4096

    good day
  • Anonymous
    <ul id="quote"><h6>mgingco wrote:</h6>Good Day!

    i do consider this as a bug. Setting display_error = Off only hides the message error from the user's GUI. And still your header('location: xxx.php') wont work. If you dont have much time tracing your scripts, try this solution:

    output_buffering = 4096

    good day</ul>

    Get rid of the white space before and after <?php ?> tag, it works.
  • Dan
    It did work! Colour me amazed! Ta!
  • RS
    that does NOT always work... (white space solution that is)...
    this error can be for different reasons....
  • Anonymous
    I am going through this very problem now and am having a hell of a time finding it and solving the issue. In fact I have separate scripts that are both having a redirect issue. I cannot find anything in these scripts that would be outputting data to the browser before the header redirect. I have no whitespace before or after <?php ;?> tags.

    I am baffled. These are hard to solve sometimes.

    Dave
  • qmchenry
    It can definitely be tough finding the culprit, particularly in a big set of scripts that you didn't write. Since the output has been sent already, it should be present above the error message in the page source that has been sent, so when you see the error, use your browser's View Source to look at what was sent before the error message and you might get something to search for in your source code. If it's something like <head> then you're in luck since you probably only have one of those in a file. If it's a
    then it may be a little tougher, but at least it's something.

    One additional tip is to exclude the final ?> tag in a file. This tag isn't necessary and if it isn't present, then there cannot be any whitespace after it.

    Good luck!
  • Anonymous
    Well, the problem is that there is no source to look at because it is PHP, which leads me to believe that no output has been written ... otherwise, I would see something in the source. So, one would think possibly whitespace but I have not found that to be the case either. Very frustrating getting stopped by something like this.

    Dave
  • Great this helped me out a bunch. I would also use these commands to help debug:

    ini_set('display_errors', true);
    ini_set('display_startup_errors', true);
    error_reporting (E_ALL);
  • elz
    i am getting this error even though i dont have header() redirect code.

    the lines that prints out the error are on my setcookie() events.
  • elz
    thought i would add that my problem was easily fixable via the same methods as it is still technically the same issue - setting values after outputting.

    just wanted to broaden the horizon on problems that generate this error output
  • That's great -- thanks for sharing! I haven't run into this before, but now that you point it out, it makes sense.
  • Andrei
    Thanks a lot for this post!
    #3 solved my problem! :)
  • Adrian Angelov
    Well, thank got I ran on this post.

    I have had this problem, however, no white spaces or whatsoever prior <?php tag. I was really frustrated as the file contained only one line <?php header("Location: /subdir/index.php");?> and this was not working as expected.

    The issue turned out to be that the file was a UTF-8 encoded file with BOM signature. This was causing the file header to be transferred prior the content has been processed, and therefore I have had the cannot modify headers error.

    Please check your files encoding as well as if it seems to you there is no error in your script.
  • MetalGarurumon
    Thanks! It works now :)))
  • U DA MAN... Removing DOM fixed it...
  • mark
    Uh, yeah, that's nice, but....

    what if you need your PHP file to be UTF8 because you need non-ANSI characters in your script defined strings?

    My UTF8 .php file works fine on Windows 5.2.5, but barfs on a linux build of same version.

    Sigh.
  • Anonymous
    UTF-8 should work fine on any OS. It's the BOM (Byte Order Mark) that causes the problem, but since UTF-8 always has the same byte order it doesn't need a BOM. See http://unicode.org/faq/utf_bom.html#bom5
  • Good advice thanks for the post
  • P M
    Very informative article. It was the blank line that was my problem. This article clearly explains subtle issues.

    Thanks
  • I had the same problem. the congif-sample file is having two empty lines at the end and they were causing trouble.
    Take care
    Problend
  • sigh , my god my I knew about the problems with the header since a long time ago, Ive been using PHP for years but today I just couldtn find what was wrong with mine, my header was on top of my page, no echos, everything seemed so clean...then I googled this and there you go, a single space was messin it up, this is exactly how my code was
    <?php
    ......
    ?>
    all i had to do was
    <?php
    ......
    ?>

    can you not the difference? i couldnt either :(
  • Jon
    This had me pulling my hair out for hours today.

    I had all my php code before the HEAD without any whitespace. (you can't imagine how many times I pressed the delete key trying to get rid of white space that wasn't there :)

    Anway, the culprit was that Dreamweaver saved the .php file as as a UTF-8 format file (I had renamed it from a UTF .html file .. so it's really my fault).

    When a .php file is saved as UTF it inserts a
    line break before everything, but it will be invisible in Dreamweaver.

    What you have to do is open the .php file in notepad, and 'Save as' ANSI.

    And now, you're good to go!
  • thanks jon for sharing , i have faced the same problem with Dreamweaver, your input helped me to over come it. Many many hours spent on this before I got this article on google.
  • Chris
    Thanks!
  • Fr
    Strange issue, I've removed header completely from html, actually, completely <html> tags, and only with
    <?php
    ......
    header("location:../first.php");
    ?>
    then it is working properly.
    I've got a line with echo before the header, and got the same warning - Cannot modify header information - headers already sent.
    This is happening on a linux environment, on windows (+Apache+mysql) I've got no such a messages, well, I didn't compared those two php.ini properly.
    Anyway, thanks for help.
  • Klaus
    Thanks, helped me a lot.
    Amazing what some additional unnoticed whitespace can cause havoc
    sometimes.
  • Sachin
    hi
    please help me.. please please please.
    please take a look at the following script:
    it is giving the following errors
    ---------------------------------------------------------------------------------------
    Warning: mysql_fetch_array(): supplied argument is not a valid MySQL result resource in /home/compkcom/public_html/cmpanel/check_login.php on line 11

    Warning: Cannot modify header information - headers already sent by (output started at /home/compkcom/public_html/cmpanel/check_login.php:11) in /home/compkcom/public_html/cmpanel/check_login.php on line 19
    ---------------------------------------------------------------------------------------
    here goes the php script
    ----------------------------------------------------------------------------------------------------
    <?php session_start();
    if((isset($_POST['username'])&&$_POST['username']!="")&&(isset($_POST['password'])&&$_POST['password']!="")){
    $error='';
    $conn = mysql_connect('localhost','compkcom_care','ptk')or die('Could not connect to MySQL database. ' . mysql_error());
    mysql_select_db(SQL_DB,$conn);
    $query = "SELECT COUNT(username) AS record FROM admin WHERE username ='" . $_POST['username']."' AND password = '".$_POST['password']."'";
    $result = mysql_query($query);
    $row = mysql_fetch_array($result);
    if($row['record']==1){
    $_SESSION['user_logged'] = $_POST['username'];
    $_SESSION['user_password'] = $_POST['password'];
    header("location:welcome.php");
    }
    else{
    $error .="Please+Enter+Correct+Username+and+password%21%0D%0A";
    header("location:index.php?&error=".$error);
    }
    }
    else{
    $error .="Please+Enter+the+Username+and+password+First%21%0D%0A";
    header("location:index.php?&error=".$error);
    }
    ?>:
    ----------------------------------------------------------------------------------------------------
    this script is running fine on my local windows server but giving the above mentioned errors on my linux hosted server..
    Please help me...
    Thanks..
  • Your database query may not be returning a valid result. It's good practice to make sure the result returned from your mysql_query command is valid.. something like:

    if (!$result) {
    die('Invalid query: ' . mysql_error());
    }

    Dumping the error message may help in this case, too.

    Good luck!
  • dave
    wwwwwwwwwwwwwoooooow thanks sir problem solved,, stupid white space
  • dominic
    This helped me to some my problem. Where i was trying to generate a xml file using php.

    Thanks
  • Fr
    Actually, there are some solution, problem is well documented on link:
    http://php.net/manual/en/function.header.php

    It is related to earlier versions of PHP, or to setup in php.ini
    I've put on the very first line:
    <?php
    ob_start();
    session_start();
    ?>
    Now, everything works fine, i-e you can have more than one header in your code.
  • RORO
    This did it! THANKS SO MUCH!! Nothing else worked and I tried it all!
  • NJY
    Gre8!! i've been tryin to solve this prob from the early morning.everything works fine now:D:D:D 1000x
  • manuel
    how can modify display_error in php script ?
  • Lito
    Warning: Cannot modify header information - headers already sent by (output started at /home/misaghi/public_html/config.php:47) in /home/misaghi/public_html/login_process.php on line 79
  • IMQ
    this error will be thrown if u have any white spaces or any print or echo above header call.
    There should be no print , no echo and no spaces before or after header statement.
  • bapo333
    thnks.........
    i have been working on the same for the past 5 days........... the error i had was a space before PHP tag..
  • Andy
    Legendary stuff... this article just saved my sanity. A white space after the close php tag in an 'include' file caused my hours of frustration.

    Thank you!
  • neoniflor
    That was fun..... whitespace really where a problem... thanks
  • Mithus
    That really great....thanx.....sooo mch....
  • Ugh. Of course!! My problem was, as you said, hiding in plain site. I was echoing a file upload verification right before calling header(), and I didn't even notice it.

    Thanks for the easy instructions!
  • Leandro
    I had an include with two blank lines after the ?> in that include... I deleted those blank lines and It works perfectly!

    Thanks!
  • Make sure there is no white space outside of the php start and end tags

    This is really a culprit.
    Thanks for help.
  • Emmanuel Afonrinwo
    Thanks a lot, after reading and carefully looking through the codes paying attention to your advice theproblem was resolved.
  • Charlies
    I am not getting this error on my local PC, but when I upload the scripts to the hosting provide I get this error. How can I set my local machine to display the same error

    Cheers
  • aneesniittech
    hi,

    you can solve the problem of "Header already sent" by removing all print and echo statements.
    If its still does not work add ob_start() at the start of your file.It will work
  • Alla
    I love you.
    I had white spaces in my include files.
    Hours upon hours of frustration and headaches.
    Thank you. <3333333333
  • Thank you very much for your blog post. I was putting together a header redirect script that was more complicated that simply redirecting to one site. When it started erroring out, I thought what I wanted to do was not possible. I read another persons forum post about white space and it was unclear what he was exactly talking about. After reading your post I understood that the problem was with whitespace *outside* the php tages (whitespace on the html page). Thanks a lot for your help :)
  • <? php
    header("location: zodiac.php");
    ?>
    above one is my index.php
    and i m trying to redired to zodia.php
    here what could be the problem
    say i m just redirecting and nothing else
  • Ah....!
    I got the problem,.. anyway thanks for all
  • Ah....!
    I got the problem,.. anyway thanks for all
  • Ivan
    Thank You!!!! :)
  • I owe you a kiss !!! ;)
    Thanks for the post
  • jayecifer
    This article helped me bunches. Thanks.
  • Thanks, I just had this problem, and your post solved it! I am a php newb, I almost had to reinstall my whole site.
  • jitenepolion
    call ob_start(); function at the start of function,It will turn output buffering on, n no output will sent from script.
blog comments powered by Disqus