• PHP Help PHP Coding
  • [RESOLVED] Warning: session_start(): Cannot send session cookie - headers already sent

The error message is specifically telling you that something on line 1 of the script generated output prior to the session_start() call. Either there is something before the opening <?php tag (a space, a newline, a unicode BOM character), or the only other thing I can think of would be if your PHP configuration has an auto_prepend_file specified and that file is generating output, although in that case I think the error message would point to that file instead (though I'm not 100% sure about that).

Therefore pending any further information, I suspect Weedpacket's suggestion is correct, that your editor is saving the file in UTF-8 with a BOM (byte order mark) at the start of the file. Either see if there is an option with your editor to save it as plain ASCII or as UTF-8 without the BOM, or else try another editor that can.

    Thimbletack wrote:

    I wrote this code I wrote it in notepad

    Yes, Notepad is one of those editors that does this (unless you save the file with an ANSI character set). Visual Studio also provides the option, but if I recall, for HTML files it defaults to Latin-1 and you have to tell it to use UTF-8 (with BOM).

      Ok so I saved a blank file and it put 3 bytes and said 1 kb so I do think you are right. So I don't think notepad does that so I am probably going to edit it in there. But is there some way to change the code to have nothing in front of it? because in notepad I see nothing so do you guys think the best way to do this would to open a new notepad file and copy the code down?

      Thanks for your help,

      Thimbletack

        Sorry for double posting but I just wanted to say thanks for helping me out. I rewrote the code in notepad and it worked! So I just gotta rewrite each page w/ php on it... But anyway thanks again.

        Thimbletack 😃

          a year later
          Weedpacket;10897309 wrote:

          Yes, Notepad is one of those editors that does this (unless you save the file with an ANSI character set). Visual Studio also provides the option, but if I recall, for HTML files it defaults to Latin-1 and you have to tell it to use UTF-8 (with BOM).

          Yes that's right. I had the same problem with few files created by Notepad and i was quite confuse.
          My problem came from the ANSI character set UTF-8 with BOM.
          After a lot of research i found this this information then i fixed the problem.

          I just recreated the file with different editor and everything works fine.
          I hope this information can save your time and nerves. 🙂


          Nothing is imposible imagination is everything!
          Benchmark Software
          [URL="ttp://stsdb.com"]World's fastest database[/URL]

            11 days later

            I had this problem. Went through and cleaned up all spaces and lines. It still didn't work. Then I changed from UTF-8 to ASCII. Bingo! So now I'll try to use ASCII for php and UTF-8 for HTML

              @: Your problem wasn't UTF-8 itself (I use it on several projects), but rather than your text editor probably included the BOM character at the beginning of the file. Since the BOM isn't part of "<?php", PHP assumes that you meant for it to be outputted to the user.

                If you just use Notepad to write your scripts then i would highly encourage you to download Notepad++. Quite easily the best text editor for web design available. And its free! :p

                  Great! That worked as well. I downloaded notepad++ and saved as UTF-8 without BOM.
                  Thanks

                    2 months later

                    After scratching my head with the same problem, i found that there was a new line after the closing ?> php tag in one of my include files. Like others have mentioned, this is a definite 'gotcha'

                      2 months later

                      I know this is an old thread but perhaps someone can help.

                      I have created a test file with ONLY this code:

                      <?php
                      $value = session_start();
                      echo "Session value = ".$value."<br>";
                      ?>

                      As suggested in this thread (or elsewhere):
                      1) There are no spaces, html, etc. preceding this.
                      2) The file is encoded in UTF-8 WITH BOM
                      3) I've modified my php.ini file to set: session.cache_limiter = public

                      And I get these errors:

                      Warning: session_start() [function.session-start]: Cannot send session cookie - headers already sent by (output started at C:\xampp\feralpots\eNorman\test.php:1) in C:\xampp\feralpots\eNorman\test.php on line 2

                      Warning: session_start() [function.session-start]: Cannot send session cache limiter - headers already sent (output started at C:\xampp\feralpots\eNorman\test.php:1) in C:\xampp\feralpots\eNorman\test.php on line 2
                      Session value = 1

                      I am baffled !

                      Does anyone know how to fix this ??

                      Thx !

                        while it shouldn't matter, does it still happen if you don't assign the session_start return value to a variable?

                          ... headers already sent by ...

                          means that there is something in front of the session_start

                          2) The file is encoded in UTF-8 WITH BOM

                          I believe that is suppose to be without BOM. But save yourself the hassle and get anyone of the hundreds of free IDE's out there. NotePad++ is a good one to start with.

                            Kirk,

                            You were right about UTF-8 WITH BOM !

                            I was already using notepad++.
                            When I converted to to UTF-8 WITHOUT BOM the warning disappeared !

                            Thanks immensely for your help !!!

                            Dagon -- thank you too for your quick reply !

                            🙂

                              6 months later

                              I'm using Notepad++ and had the PHP down in the body. Once I moved it to the very first line it was fine. Even the <html> tag caused it to break if it was first. This works:

                              <?php
                              session_start(); // initialise a session - commented out as it seems to auto start
                              $SESSION['counter']++; // increment a session counter
                              ?>
                              <html>
                              <head>
                              </head>
                              <body>
                              <?php echo "You have viewed this page ". $
                              SESSION['counter'] . " times"; ?>
                              </body>
                              </html>

                                Since [man]session_start/man modifies the outgoing HTTP response headers, it doesn't have to be the 'first' line of code - it just has to be called before any output (which causes the HTTP headers to be sent at that point).

                                  a year later

                                  I enclosed the start_session() command in php tags at the beginning of my script and then started a new php tag for the rest of the code. This is the only solution that worked for me, as follows:

                                  <?php session_start();?>
                                  <?php
                                  php code here......
                                  ?>

                                    sbrichman;11000174 wrote:

                                    This is the only solution that worked for me

                                    Then you were doing something very, very wrong, because the call to session_start() doesn't have to be surrounded by its own set of PHP tags, nor does it need to be the first statement in the script (or even at the "beginning").

                                      6 months later

                                      I'm getting the same error on line 1 of my code. my session starts on top and I tried saving in notepad++ in UTF without BOM. STILL no luck. this script was working, and hasn't moved servers or anything so I'm not sure what happened...could the way the file is uploaded affect it working?

                                      here is my code:

                                      <?php session_start(); ?>
                                      
                                      
                                      <script src="js/jquery.validate.min.js" type="text/javascript" charset="utf-8"></script>
                                      <script type="text/javascript" charset="utf-8">
                                      //<![CDATA[
                                      			$(document).ready(function() {
                                      
                                      			$("#loginform").validate({
                                      				rules: {
                                      					email: {
                                      						required: true,
                                      						email:true
                                      					},
                                      					password: {
                                      						required: true,
                                      					},
                                      				},
                                      				messages: {
                                      					password: "Please enter your password",
                                      					email: "Please enter a valid email address"
                                      				}
                                      			});
                                      		});
                                      
                                      		function OnLogin(){
                                      			var email = $('#email').val();
                                      			var password = $('#password').val();
                                      
                                      			if ( email != "" && password != "" ){ 
                                      
                                      					$.ajax({
                                      							url:'lib/login.php',
                                      							type:'POST',
                                      							data:"email=" + email + "&password=" + password,
                                      							async:false,
                                      							success: function(str){
                                      
                                      								if ( str.indexOf("SUCCESS") != -1 )
                                      								{
                                      									if ( $("#redirect").length > 0 && $("#redirect").val() != ""  ) 
                                      										location.href = $("#redirect").val() + ".php";
                                      									else
                                      										location.reload();
                                      									return;
                                      								}
                                      								else
                                      								{
                                      									if ( str.indexOf("PWD") != -1 )
                                      									{
                                      										alert("Please input the correct password.");
                                      										$("#password").focus(); 
                                      									}
                                      									else if ( str.indexOf("UID") != -1 )
                                      									{
                                      										alert("Please input the correct email.");
                                      										$("#email").focus();
                                      									}
                                      								}
                                      							}
                                      						});
                                      				}
                                      
                                      			}
                                      
                                      		function OnRegister(){
                                      			location.href = "register.php";
                                      		}
                                      
                                      		function OnLogOut(){
                                      			$.ajax({
                                      					url:'lib/logout.php',
                                      					type:'POST',
                                      					data:"logout=1",
                                      					async:false,
                                      					success: function(str){
                                      
                                      						if ( str.indexOf("SUCCESS") != -1 )
                                      						{
                                      							location.reload();
                                      							return;
                                      						}
                                      					}	
                                      				});				
                                      		}
                                      //]]>
                                      </script>
                                      <?php if( !isset($_SESSION['PHP_AUTH_USER']) ): ?>
                                      <h1>User Login</h1>
                                      <div id="login-form">
                                      
                                      <form id="loginform" name="loginform" method="post" onsubmit="OnLogin();return false;">
                                      	<h3>Email</h3>
                                      	<input type="text" name="email" id="email" />
                                      	<h3>Password</h3>
                                      	<input type="password" name="password" id="password" />
                                      	<br />
                                      
                                      	<input type="image" class="login button" src="images/login.jpg"   />
                                      	<input type="image" class="register button" src="images/register.jpg" onclick="OnRegister()" />
                                      </form>
                                      </div>
                                      <?php else: ?>
                                      	<p>Thanks <strong><?=$user_name?></strong>, You are now logged in.</p>
                                      	<p style="text-align:center"><input type="button" class="button" onclick="OnLogOut()" value="logout" /></p>
                                      <?php endif; ?>
                                      
                                        9 days later