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

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

                        Can you upload the script somewhere that we can download it and examine the file directly? (I would suggest attaching it to your next post, but I don't believe you have that ability yet since you're a new user.)

                          I uploaded the script to another server so you can see the result..

                          http://mywebproof.com/test/home.php

                          is it weird that when you goto the actual 'login.php' file it doesn't show the error, but when other pages pull it in, it does?

                            NOTE: my link above didn't copy in the www. and i can't edit...i guess no privledges for that yet either =/

                            any help or suggestions appreciated

                              Two things:

                              1. I asked if you could provide the file for download so that we can look at the actual PHP code. There's no way we can do that by just viewing the rendered output of that file.

                              2. Providing that link actually did provide insight. Read the error message again - the problem is not on line 1 of login.php. In fact, the real source of the error isn't even in login.php at all - it's inside home.php.

                                You can't output any data before you attempt to modify the HTTP headers (which is what [man]session_start/man tries to do when you propagate the session ID via a cookie).

                                Do you see anything within the home.php page that would cause that? the only line of code in the actual page is this:

                                <?php include('login.php'); ?>

                                Line 1 of that page is the DOCTYPE declaration. Sorry, I'm not a programmer, so the answer may be really basic. Appreciate you looking at this though!

                                bradgrafelman;11014337 wrote:

                                Two things:

                                1. I asked if you could provide the file for download so that we can look at the actual PHP code. There's no way we can do that by just viewing the rendered output of that file.

                                2. Providing that link actually did provide insight. Read the error message again - the problem is not on line 1 of login.php. In fact, the real source of the error isn't even in login.php at all - it's inside home.php.

                                  You can't output any data before you attempt to modify the HTTP headers (which is what [man]session_start/man tries to do when you propagate the session ID via a cookie).

                                  jschnyderite;11014339 wrote:

                                  Do you see anything within the home.php page that would cause that?

                                  I don't know, because you haven't shown us what the "home.php" file contains.

                                  jschnyderite;11014339 wrote:

                                  Line 1 of that page is the DOCTYPE declaration.

                                  ...which is data that PHP sends as output. Thus, you can't use session_start() after line 1 of home.php if that's the case.

                                  Either restructure your code such that you can modify the HTTP headers if desired (e.g. any call to session_start(), header(), setcookie(), etc.), or do what I still consider to be a cheap workaround and enable output buffering (and set the limit high enough such that the buffer can contain all of the output you generate before trying to go back in time and output data that's to precede that output).

                                  jschnyderite;11014339 wrote:

                                  Sorry, I'm not a programmer

                                  Which begs the question: Why are you trying to program, then? 😉

                                    Something is funny here..
                                    I was just experimenting to see if I could figure out a fix.

                                    This login was converted to another site a month or two ago and works fine...i copied a page from that which displays and works great on another server, and when I move it to the server where I'm having an issue - the same exact file displays the error.

                                    I moved the <?php include('login.php'); ?> to the top of the document just for testing, and no errors...unfortunately, I need to align it in another spot on the page.

                                    bradgrafelman;11014341 wrote:

                                    I don't know, because you haven't shown us what the "home.php" file contains.
                                    What is the best way to show you the raw files? zip it and put it on my server? email?

                                    ...which is data that PHP sends as output. Thus, you can't use session_start() after line 1 of home.php if that's the case.

                                    Either restructure your code such that you can modify the HTTP headers if desired (e.g. any call to session_start(), header(), setcookie(), etc.), or do what I still consider to be a cheap workaround and enable output buffering (and set the limit high enough such that the buffer can contain all of the output you generate before trying to go back in time and output data that's to precede that output).

                                    GULP This stuff is greek to me..

                                    Which begs the question: Why are you trying to program, then? 😉

                                    im really just trying to fix something i inherited...believe me, i'd rather leave it to the pros =p

                                      jschnyderite;11014343 wrote:

                                      i copied a page from that which displays and works great on another server, and when I move it to the server where I'm having an issue - the same exact file displays the error.

                                      Sounds like the "[other] server" has output buffering enabled (see the PHP manual section [man]outcontrol[/man] for info; the PHP directive of interest would be output_buffering), whereas the server you're currently using does not.

                                      jschnyderite;11014343 wrote:

                                      I moved the <?php include('login.php'); ?> to the top of the document just for testing, and no errors...unfortunately, I need to align it in another spot on the page.

                                      Restructuring your code is likely going to be more than just moving an include() statement around, since it sounds like the code was poorly written (e.g. design/layout is so heavily dominant that it supersedes the actual logic).