0

My code:

    <?php
    session_start();
    
    $_SESSION["favcolor"] = "green";
    ?>

<html>
    

    
  <head>

    <link rel="stylesheet" href="style.css">
    <meta charset="utf-8">
    <title>Login | NeonBLOX</title>
    
   charset stuff

  </head>

  <body>
    
    <?php
    
       $_SESSION["favcolor"] = "green";
    
    ?>
    
    <div class="ib2">
       top stuff
    </div>
    
    <div class="ib">
        form stuff
    </div>
    


  </body>
</html>

Why does it error Warning: session_start(): Cannot start session when headers already sent in (...) on line 2? I'm trying to test session stuff with my current site, so I can make it so I send information that is preset to another web page, but it gives me this error before I even log in.

Neon BLOX
  • 9
  • 1
  • 1
  • 2

2 Answers2

0

Your PHP code prints whitespace before session_start();. As a rule of thumb, don't make any output before calling session_start();.


Fix for this will be removing the whitespace before <?php as that will be output too.

<?php
    session_start();
    
    $_SESSION["favcolor"] = "green";
    ?>

<html>
    

    
  <head>

    <link rel="stylesheet" href="style.css">
    <meta charset="utf-8">
    <title>Login | NeonBLOX</title>
    
   charset stuff

  </head>

  <body>
    
    <?php
    
       $_SESSION["favcolor"] = "green";
    
    ?>
    
    <div class="ib2">
       top stuff
    </div>
    
    <div class="ib">
        form stuff
    </div>
    


  </body>
</html>
Ammar Faizi
  • 1,393
  • 2
  • 11
  • 26
0

This usually means that some output from your PHP script has already been prepared (or sent) to the client for the current request.

Headers are used in a lot of programmatic communications and they are a way to prepare the receiver for whatever is about to happen. They usually contain stuff like content type, how many bytes the incoming data is and other meta data.

In PHP they can also contain session data - the session key and anything else you have packed in there. Headers are sent once and all at once for each response. So if you have already sent out headers that say "there is no session for this response", you can't subsequently say "hold on, there is!" As the headers have already gone out.

When you start a session in PHP it attempts to hook into the pending headers in order to pack the session data in there but if the headers have already gone out you will get the error Cannot start session when headers already sent.

So the solution is to figure out where your php stack is sending out headers before you call that session_start() function. Be aware that any printed white space counts! That little factoid lets us look at your code again and see that there is a tab before your opening <?php tag. That's whitespace, which initiates the data send which means your headers are already on their way to the client by the time you run any php at all!

Abraham Brookes
  • 1,720
  • 1
  • 17
  • 32