session_start错误,因为同一session_start操作已“发送标题”?

Fra*_*sca -5 php session session-variables

我试图在PHP中启动一个会话,以便存储有关用户ID的数据(将在mySQL DB中使用)。

但是,当我开始会话时,出现以下错误:

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
Run Code Online (Sandbox Code Playgroud)

我了解错误是因为页面已提交或“标题已发送”而无法启动会话,但是我非常困惑,因为它所引用的行38行是启动会话的行:

Line 38: session_start();
Run Code Online (Sandbox Code Playgroud)

因此,如何说标头已经通过此行发送,这就是错误?

这是我的代码的简化部分。注意,HTML的一部分是通过jQuery使用AJAX加载的,是否可以?

<!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>
Run Code Online (Sandbox Code Playgroud)

小智 5

您要在之前输出HTML session_start()。将您的PHP代码放在HTML代码之上。