session_start错误,因为';标头已发送';通过相同的session_start操作


session_start errors because 'headers already sent' by the same session_start action?

我正在尝试用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

我知道错误是说它不能启动会话,因为页面已经提交,或者"标题已经发送",但我很困惑,因为它引用的行,第38行,是启动会话的行:

Line 38: session_start();

那么,它怎么能说这行已经发送了标题,这就是错误呢?

这是我代码的缩短部分。需要注意的是,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>

您在session_start()之前输出HTML。将PHP代码置于HTML代码之上。