session_start错误,因为'标头已经发送'通过相同的session_start动作?

时间:2015-02-06 13:29:04

标签: php session session-variables

我正在尝试在PHP中启动会话以存储有关用户ID的数据(将在mySQL数据库中使用)。

然而,当我开始会话时,我收到以下错误:

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

我理解错误是说它无法启动会话,因为页面已经提交,或者#34;标头已经发送"但我很困惑,因为它引用的行,第38行,是启动会话的行:

Line 38: session_start();

那么如何说这个标题已经被这一行发送了,那是错误的呢?

这是我的代码的缩短部分。需要注意的是,有一部分HTML是通过AJAX使用jQuery加载的,可能就是这样吗?

<!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>

1 个答案:

答案 0 :(得分:4)

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