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

Hi,

I am getting these errors :

Warning: session_start(): Cannot send session cookie - headers already sent by (output started at /home/box/public_html/im/launch.php:29) in /home/box/public_html/im/launch.php on line 40

Warning: session_start(): Cannot send session cache limiter - headers already sent (output started at /home/box/public_html/im/launch.php:29) in /home/box/public_html/im/launch.php on line 40

Warning: Cannot modify header information - headers already sent by (output started at /home/box/public_html/im/launch.php:29) in /home/box/public_html/im/launch.php on line 42

Warning: Cannot modify header information - headers already sent by (output started at /home/box/public_html/im/launch.php:29) in /home/box/public_html/im/launch.php on line 43

Here are lines 40 to 46 :

session_start();
$_SESSION['sid'] = "sid";
setcookie("sid", sid, time()+3600);
setcookie("sid", $_GET["uname"], time()+3600);
$CheckInTime = Time();
$query="INSERT INTO `NetImOn` (`U_Name`, `LoginTime`, `SessionId`) VALUES ('".$_GET["uname"]."', '".$CheckInTime."', '".session_id()."')"  or die(mysql_error()); 
mysql_query($query);

Can anyone please tell me what is wrong with the following error, thank you.

Jf3000

    Make sure you have nothing that outputs to the browser before those lines and delete any unessasary whitespace from that code up. That error means you outputted something to the browser before line 40 and then tried to use a header value that can't be sent because of course the header had already been sent before line 40.

      3 years later

      I know this is an old post, but I got the same problem:

      error:
      arning: session_start() [function.session-start]: Cannot send session cookie - headers already sent by (output started at /mnt/w0207/d23/s08/b02d7009/www/designisbs.ca/johnbursic/edit_profile_verification.php:21) in /mnt/w0207/d23/s08/b02d7009/www/designisbs.ca/johnbursic/edit_profile_verification.php on line 25

      Warning: session_start() [function.session-start]: Cannot send session cache limiter - headers already sent (output started at /mnt/w0207/d23/s08/b02d7009/www/designisbs.ca/johnbursic/edit_profile_verification.php:21) in /mnt/w0207/d23/s08/b02d7009/www/designisbs.ca/johnbursic/edit_profile_verification.php on line 25

      Code:

      <?php
      	$form_username = $_POST['username'];
      
      session_start();
      if(!empty($_POST['surname'])){
          foreach($_POST as $key => $value) {
              $_SESSION['profile'][$key] = mysql_real_escape_string($value);
          }
          $fields = array("surname", "givenName", "homeSuite", "mailSuite", "homeAddy", "mailAddy", "homeCity", "mailCity", "homeProv", "mailProv", "homeCount", "homePost", "mailPost", "busPhone", "celPhone", "homPhone", "fax", "busEmail", "perEmail");
          $sql .= "UPDATE users SET ";
              $length = count($fields);
              $n = 1;
              foreach($fields as $field) {
                  if($n < $length) {
                      $sql .= "{$field}='{$_SESSION['profile'][$field]}',";
                  } else {
                      $sql .= "{$field}='{$_SESSION['profile'][$field]}'";
                  }
                  $n++;
              }
          $sql .= " WHERE username = '{$username}'";
          if(mysql_query($sql, $link)){
              // Successfull  - Clear the Session
              $_SESSION['profile'] = NULL;
              echo("<p>{$form_username}'s Details have been saved.</p>\n");
          }else{
              $error = mysql_error();
              echo("<p>There was an Error saving {$form_username}'s Details.</p>\n<p>{$error}</p>\n");
          }
      }else{
          echo("<p>Please make sure all Required fields are Vaild</p>\n");
      }
      ?>
      

      Any ideas?

        The answer is exactly the same as was given before. Check edit_profile_verification.php line 21 and see what it is sending to the browser. Remove that, and it should fix it.

          22 days later

          It is not intuitive but ...

          if <?php is at line 2 of your script and a blank line is above it then that can cause problems such as the php header function not working.

          I had a HEADER session_regenerate error because a script called by require_once () or include () had 1 blank line below the closing php tag !!

          ?>
          BLANK LINE WAS HERE

          echo statements will also be a problem if they precede the header function call.
          I wonder if die() or any other statements which write to the screen would be just as bad as echo () in this situation.

            2 months later

            100% working solution

            Step one :- Search & Open PHI.INI

            Step Two:- Search session.cache_limiter

            Step three:- put " public " in front of session.cache_limiter

            Like

            session.cache_limiter =public

            Thats it .

            Regards
            Shahzad Arain 🙂

            [Do not post personal contact info here - MOD]

              a month later

              Hi, I used Dreamweavers "Log-in User" wizard to create the php code that binds to the database and upon execution, i get the following message:

              Warning: session_start() [function.session-start]: Cannot send session cookie - headers already sent in /Users/xxx/Sites/xxxx/login.php on line 10

              Warning: session_start() [function.session-start]: Cannot send session cache limiter - headers already sent (output started at /Users/xxx/Sites/xxxx/login.php:10) in /Users/xxx/Sites/xxxx/login.php on line 10

              Here is my code... what could be wrong?

              <?php virtual('/~xxx/xxxx/Connections/yyyy.php'); ?>
              <?php
              if (!function_exists("GetSQLValueString")) {
              function GetSQLValueString($theValue, $theType, $theDefinedValue = "", $theNotDefinedValue = "") 
              {
                $theValue = get_magic_quotes_gpc() ? stripslashes($theValue) : $theValue;
              
                $theValue = function_exists("mysql_real_escape_string") ? mysql_real_escape_string($theValue) : mysql_escape_string($theValue);
              
                switch ($theType) {
                  case "text":
                    $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL";
                    break;    
              case "long": case "int": $theValue = ($theValue != "") ? intval($theValue) : "NULL"; break; case "double": $theValue = ($theValue != "") ? "'" . doubleval($theValue) . "'" : "NULL"; break; case "date": $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL"; break; case "defined": $theValue = ($theValue != "") ? $theDefinedValue : $theNotDefinedValue; break; } return $theValue; } } ?> <?php // *** Validate request to login to this site. if (!isset($_SESSION)) { session_start(); } $loginFormAction = $_SERVER['PHP_SELF']; if (isset($_GET['accesscheck'])) { $_SESSION['PrevUrl'] = $_GET['accesscheck']; } if (isset($_POST['GroupID'])) { $loginUsername=$_POST['GroupID']; $password=$_POST['Password']; $MM_fldUserAuthorization = ""; $MM_redirectLoginSuccess = "/~xxx/xxxx/main.php"; $MM_redirectLoginFailed = "/~xxx/xxxx/authorizationfailed.php"; $MM_redirecttoReferrer = false; mysql_select_db($database_yyyy, $yyyy); $LoginRS__query=sprintf("SQL query", GetSQLValueString($loginUsername, "text"), GetSQLValueString($password, "text")); $LoginRS = mysql_query($LoginRS__query, $yyyy) or die(mysql_error()); $loginFoundUser = mysql_num_rows($LoginRS); if ($loginFoundUser) { $loginStrGroup = ""; //declare two session variables and assign them $_SESSION['MM_Username'] = $loginUsername; $_SESSION['MM_UserGroup'] = $loginStrGroup; if (isset($_SESSION['PrevUrl']) && false) { $MM_redirectLoginSuccess = $_SESSION['PrevUrl']; } header("Location: " . $MM_redirectLoginSuccess ); } else { header("Location: ". $MM_redirectLoginFailed ); } } ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/> <title>Untitled Document</title> </head> <body> <form id="form1" name="form1" method="POST" action="<?php echo $loginFormAction; ?>"> <table width="200" border="1"> <tr> <td>User Name</td> <td><input type="text" name="GroupID" id="GroupID" /></td> </tr> <tr> <td><p>Password</p> </td> <td><input type="text" name="Password" id="Password" /></td> </tr> <tr> <td>&nbsp;</td> <td><input type="submit" name="button" id="button" value="Submit" /></td> </tr> </table> </form> </body> </html>

              I appreciate the help.

                In at least a couple places before the session_start(), you have this sort of thing going on:

                <?php // some code ?>
                <?php
                // some more code . . .
                ?>
                

                The newline between the "?>" and the subsequent "<?php" is, in fact, output. Either get rid of those superfluous closing/opening php tags, or - probably better in the long run - move the session_start() to be in the very first <?php...?> section.

                  3 months later

                  I am also getting this error. I've looked around for a while and haven't figured out how to fix it, but my errors are for all of my PHP code. This is kind of weird. So here is my code.

                  <?php session_start();?><html><?php
                  if(isset($_SESSION['loggedinuser'])) 
                  echo "You're logged in! Click <a href='profile.php'>Here</a> to view your profile";
                  else {
                  echo "You're not logged in. Do you want to <a href='login.php'>log in</a> or <a href='register.html'>register</a>?";
                  }
                  ?>
                  <head>
                      <title>UrComics.com Your comics, Your votes!</title>
                      <link rel="stylesheet" type="text/css"
                      href="style.css" />
                  </head>
                  <body>
                  <table border="1" cellspacing="0" cellpadding="1" align="left">
                  <tbody>
                  <tr>
                  <td>
                  <img alt="" src="./Images/UrComicsLogo1.gif" />
                  <br />
                  <h5 align="center">
                  <a href="index.php">Home</a>
                  <br />
                  <a href="UrPaper.php">Ur Paper</a>
                  <br />
                  <a href="inThePaper.php">In The Paper</a>
                  <br />
                  <a href="Help.html">Help/FAQ</a>
                  <br />
                  <a href="uploadcomic.php">Submit A Comic</a>
                  </h5>
                  </td>
                  </tr>
                  </tbody>
                  </table>
                  <table border="1" cellspacing="2" cellpadding="2" align="center" width="75%">
                  <tbody>
                  <tr>
                  <td>
                  <h1 align="center">Welcome to UrComics.com</h1>
                  </td>
                  <td>
                  <h3>Hits</h3>
                  <hr align="left" width="100%" "noshade" size="2" />
                  <h3>
                  <?php
                  $filename = "counter.txt" ;
                  $fd = fopen ($filename , "r") or die ("Can't open $filename") ;
                  $fstring = fread ($fd , filesize ($filename)) ;
                  echo "$fstring" ;
                  fclose ($fd) ;
                  $fd = fopen ($filename , "w") or die ("Can't open $filename") ;
                  $fcounted = $fstring + 1 ;
                  $fout = fwrite ($fd , $fcounted) ;
                  fclose ($fd) ;
                  ?>
                  </h3>
                  <br />
                  </td>
                  </tr>
                  <tr>
                  <td width="50%" class="red">
                  <h3 align="center">Announcements</h3>
                  <hr align="left" width="100%" "noshade" class="red"  size="2" />
                  <br />
                  <p>Welcome to urcomics.com where you can post your own comics and see what others think of your idea.
                  Just create an account to get started!</p>
                  <a href="register.html">Click Here to Get Started!</a>
                  </td>
                  <td width="50%" class="blue">
                  <h3 align="center">Comics Of The Week</h3>
                  <hr align="left" width="100%" "noshade" class="blue" size="2" />
                  <br />
                  <p>Once I figure out the php i am gonna put the top rated comics of the week on here.</p>
                  </td>
                  </tr>
                  <tr>
                  <td class="green" align="left">
                  <h3 align="center">Login</h3>
                  <hr align="left" width="100%" "noshade" class="green" size="2" />
                  <br />
                  <?php
                  if(isset($_SESSION['loggedinuser'])) {
                  ?>
                  You're currently logged in, do you want to <a href="logout.php">Log out</a>?
                  <?php 
                  } else { 
                  ?>
                  <p>Put in your username and password to login.</p>
                  <br />
                  <form name="authenticate" method="post" action="authenticate.php">
                  Username:<input name="username" type="text" size="20">
                  <br />
                  Password:<input name="password" type="password" size="20" />
                  <br />
                  <input type="submit" name="submit" value="submit"/>
                  <input type="reset" name="clear" value="reset"/>
                  </form>
                  <?php
                  }
                  ?>
                  </td>
                  </tr>
                  </tbody>
                  </table>
                  </body>
                  </html>

                  So I am getting these errors at the top of my page.

                  Warning: session_start() [function.session-start]: Cannot send session cookie - headers already sent by (output started at C:\file\secret\index.php:1) in C:\anotherfile\file\index.php on line 1
                  
                  Warning: session_start() [function.session-start]: Cannot send session cache limiter - headers already sent (output started at C:\files\morefiles\index.php:1) in C:\morefiles\stuff\index.php on line 1
                  

                  NOTE:That is not really the file location.

                  But it is weird because the code was working then it just stopped working. and none of my php works so I don't know if this is a problem in my php.ini file or what. Anyone know how to fix this?

                    Some editors, when they save a file as UTF-8, stick extra characters into the file at the very beginning (the format doesn't require it, but they do it anyway). Then refuse to show you those characters when they display the file. To see if your editor is one of these, try saving an empty file and seeing how many bytes it takes up. If it's more then zero (probably three), then you'll have to tell your editor to stop messing around (and how you do that depends on the editor).

                      I don't think so... I am using Microsoft Visual web studio and it doesn't do that because when I wrote this code I wrote it in notepad so It shouldn't be that that is happening.

                      This is really strange

                      Thimbletack

                        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