5

I am trying to start a session in PHP in order to store data about a user ID (which will be used in mySQL DB).

However when I start the session I get the following errors:

Warning: session_start(): Cannot send session cookie - headers already sent by (output started at /Applications/MAMP/blah) in /Applications/MAMP/blah on line 38

Warning: session_start(): Cannot send session cache limiter - headers already sent (output started at /Applications/MAMP/blah) in /Applications/MAMP/blah on line 38

I understand that the error is saying it cannot start the session as the page is already submitted, or "header already sent" however I am very confused because the line it is referencing, line 38, IS the line that starts the session:

Line 38: session_start();

So how can it say the headers are already sent by this line and that's the error?

Here is a shortened down section of my code. To note, there is portion of the HTML that is loaded in via AJAX using jQuery, could that be it?

<!DOCTYPE html>
<html>
<head>
<title>Title</title>
</head>
<body>
        <div class="wrapper">
          <div id="quiz-section">
             // This part is where the HTML content loads via AJAX
          </div>
        </div>
<!-- Below PHP looks at the referral i.e how the user landed on this page -->
<?php
session_start();
require 'connect.php';
if (!mysqli_query($con,"INSERT INTO entries (referral) VALUES ('$ref')")){
        echo("Error description: " . mysqli_error($con));
        return false;
}

$_SESSION["sessionID"] = mysqli_insert_id($con);
mysqli_close($con);

?>
</body>

<script>
// some jQuery here to load in the HTML content to the AJAX pane   
</script>
</html>
Francesca
  • 26,842
  • 28
  • 90
  • 153

1 Answers1

26

You're outputting HTML before the session_start(). Put your PHP code above the HTML code.

  • Thanks for this. even I know but I almost forgot this one because I have no coding in PHP like 1 year ago – Snowbases Nov 21 '19 at 17:50