Warning: headers already sent

When I was learning PHP their were few things that had stumped me, I would usually take it hours to solve them if not days. Now I have grown up, and I realize that those were the basic things that should have been mentioned in the PHP manual, but they were not.

Today I am going to write about one such annoying problem that almost always comes in the way of PHP developers at least once.

Warning: Cannot modify header information – headers already sent by (output started at C:wampwwwaktesterror.php:2) in C:wampwwwaktesterror.php on line 4

Warning: session_start() [function.session-start]: Cannot send session cookie – headers already sent by (output started at C:wampwwwaktesterror.php:2) in C:wampwwwaktesterror.php on line 3

This is “header already sent” warning message, that we get whenever we try to redirect a user to some other page or location, when we try to set a cookie or if we try to start a session. Once we get this warning we know that page won’t redirect, session won’t start or cookie’s sent to user, So we can’t even ignore them.

Before we see the solutions to resolve this warning let’s see the source code of the error.php file that I used to generate this error.


<?php
session_start();
header("location:http://localhost/");
?>

Please notice an empty line before “<?php”, this is the cause of errors in his page.

Why This Occurs

This is requirement of the http protocol that header related information must be sent by the server before it can sent the content. When we try to send a header information after we have already sent some output to client, PHP responds by giving this warning.

The most common reasons are

  1. An output is sent, either by normal HTML tags, blank lines in a file, or from PHP file itself(in my case this is the reason).
  2. We read a file using include()/require() function, and that file may have empty spaces or he lines at the end, that will be sent as output.

Important thing to note is that output is sent before header information that you wanted to sent, and hence the warning.

How To Resolve

This is really simple, just make sure their is no output sent before your call to header function. This might be a correct advice but this still does not help much.

What really needed is that we need to know where is the exact problem, that we can resolve.

So let’s take a look at the warning message again, now look at the part where in parenthesees it says “output started at <path of the file>: line number“, you see the source of our problem is already mentioned in this warning. This is where the problem lies.

Now we know from where output is coming we can depending on your situation we can remove the output that is being sent, or if we can’t do that we move the call to header function above that line.

Basically we have to make sure that no output is sent before call to any header related functions.

Some guideline that might help

  1. Always start “<?php” at the first line and first column, in you php file.
  2. Keep all you your session related function like session_start() at the start of file, just after “<?php”
  3. If all you are writing is a php file then do not use “?>”, this can prevent empty space or lines from being included in the other files.

It would be interesting to know what you did when you first saw this problem, what was your reactions.

If you have any doubts or you did not understand something leave a comment below, I will try to help you as time permits.

Comments

26 responses to “Warning: headers already sent”

  1. […] tagged phpOwn a WordPress blog? Make monetization easier with the WP Affiliate Pro plugin. Warning: headers already sent saved by 3 others     Luisguitarrista bookmarked on 06/01/08 | […]

  2. Paul Houle Avatar

    I like tip #3 — although many people find it counterintuitive (they think they should always finish what they start,) it’s a great way to avoid the problem you’re describing.

  3. BTM Avatar

    Dig the manual for ob_start()

  4. Amit Kumar Singh Avatar
    Amit Kumar Singh

    @BTM thanks for completting this post.

    i was hoping somebody would raise that point when i skipped ob_start() in favor of keeping this post simple.

    now it is complete. 🙂

  5. BlaM Avatar

    In addition to BTM:

    I even prefer to enable output buffering in my php.ini – on one hand because it solves all those “headers already sent” problems and on the other because it has performance benefits.

  6. […] Reading/Parsing Excel Spreadsheet using PHP May 31st, 2008 | Save to del.icio.us now(0) function displayURL(data) { var urlinfo = data[0]; if (!urlinfo.total_posts) return; document.getElementById(‘a98’).innerHTML = urlinfo.total_posts; } This is second article in the series of common PHP problems that a beginner faces. You can check the first article Warning: header data already sent. […]

  7. […] This is second article in the series of common PHP problems that a beginner faces. You can check the first article Warning: header data already sent. […]

  8. Nilesh T Avatar
    Nilesh T

    If all you are writing is a php file then do not use “?>”, this can prevent empty space or lines from being included in the other files.

    I not understand this guidline.
    So, explain it further

  9. […] = urlinfo.total_posts; } A month back I had written about why your session might not be setting, even though you had set every thing as per the book. This time I am writing about a new problem […]

  10. ruta Avatar
    ruta

    thank you sir…its really amazine think

  11. gakusha Avatar

    I am on the lesson about cookies and having problem with setting cookies.
    I have to say that using setcookie() worked fine when I placed it on the very 1st line, but how about in the following case? I am getting “Warning: Cannot modify header information – headers already sent by (output started at C:wampwwwphpbasednewreadingcookies.php:7) in C:wampwwwphpbasednewreadingcookies.php on line 14

    Please help!

    read cookies

  12. shriram Avatar

    i have a problem in my code as follows:

    error message is;

    Warning: Cannot modify header information – headers already sent by (output started at C:wampwwwmartixumartindex.php:8) in C:wampwwwmartixumartindex.php on line 33

  13. sindhura Avatar
    sindhura

    after implementing session_start(); and header(Content-type:image/jpg)
    output is
    http://localhost:81/upload/upload.php
    can u plz tell me how to display the image

  14. BlaM Avatar

    @sindhura: Umm, is that the error message or are you trying to give us a link to your page so that we can see ourselves?

    If it is the error message then it’s generated by the browser and means “Hey, I can’t display the image due to whatever reason.” Either the image data is missing completely or you may have some additional output in your file that corrupts the image file.

  15. sindhura Avatar
    sindhura

    @BlaM : Still my code displays same output.Here, is my code.

    loadImageFromObject($image);
    $cc->cropToDimensions($xpos1, $ypos1, $xpos2,$ypos2 );
    return $cc->getImageObject();
    }
    ?>

  16. sindhura Avatar
    sindhura

    can u plz tell me what’s wrong with the code
    $dir=”upload/”;
    $image=$_POST[‘image’];;
    $file=$dir.$image;
    $image_object =@imagecreatefromjpeg($file);

  17. BlaM Avatar

    It totally depends on your Class “$cc”. If it outputs an error message instead of the image, you get no image shown.

    – Try to call the image URL directly (no HTML page).
    – If nothing’s shown: Try to remove the “header” command. You might get the error message then.

  18. Mayel Avatar

    Account Manager

    #createaccform {
    border: 2px solid #600;
    background-color: #FFC;
    width: 200px

    }
    form {
    margin: 5px;
    }

    label {
    display: block;
    width: 90px;
    float: left;
    clear: both;
    }

    label, input {
    margin-bottom: 4px;
    }

    Welcome to the account manager!

    Username:

    Password:

    Re-type password:

    Email:

    Change Password

    Password and username cannot be the same and make sure to have their lenght from 4-10 characters.
    Go to main page…

  19. Mayel Avatar

    //
    //
    // Account Manager

    #createaccform {
    border: 2px solid #600;
    background-color: #FFC;
    width: 200px

    }
    form {
    margin: 5px;
    }

    label {
    display: block;
    width: 90px;
    // float: left;
    // clear: both;
    // }
    //
    // label, input {
    // margin-bottom: 4px;
    }
    //
    //
    //
    //Welcome to the account manager!
    //
    //
    // Username:
    //
    // Password:
    //
    // Re-type password:
    //
    // Email:
    //
    //
    // Change Password

    //
    //
    // Password and username cannot be the same and make sure to have their // lenght from 4-10 characters.
    // Go to main page…
    //
    //
    Whats the problem i get the (header-error error ;P)

  20. Mayel Avatar

    Why does it print my code instead of my program -.-

  21. Mayel Avatar

    I mean the opposite…

  22. Aris Avatar

    hi,
    i’m really thank’s cause you was posted this article

    it’s worked..
    all my problem was solved
    I’m very thank’s you
    🙂

  23. ammr Avatar
    ammr

    use meta redirect….

    echo ”;
    exit;

  24. ammr Avatar
    ammr

    echo ;
    exit;

  25. anamika Avatar
    anamika

    hi,
    i am anamika.I have same problem in my website.I have checked, there is not any blank space and empty line in any files but still getting this error can you plz help me to solve this problem.I thought i am getting this problem because I have used session_start(); inside if condition..
    so give me any solution for it