无法发送会话cookie - 已发送的标头(当session_start()时)

时间:2014-11-22 12:39:53

标签: php cookies

我尝试使用登录加载页面,但有两个错误:

Warning: session_start() [function.session-start]: Cannot send session cookie - headers already sent by (output started at Z:\home\lab4\www\login.php:18) in Z:\home\lab4\www\login.php on line 19

Warning: session_start() [function.session-start]: Cannot send session cache limiter - headers already sent (output started at Z:\home\lab4\www\login.php:18) in Z:\home\lab4\www\login.php on line 19

第19行是session_start();。我试图在浏览器中删除所有我的cookie,但它没有帮助。有什么想法吗?

<body>
    <?php
        session_start();
        if(isset($_POST["enter"]))
        {                
            $login = $_POST["login"];
            $password = $_POST["password"];
            $query = mysql_query("SELECT * FROM users WHERE password = '$password' AND login = '$login'") or die(mysql_error());
            $user_data = mysql_fetch_array($query);
            if($user_data)
            {                                                       
                $_SESSION["login"] = $user_data["login"];
                $_SESSION["loggedin"] = true;
            }
            else print('<script>alert("Incorrect login or password!")</script>');
        }

2 个答案:

答案 0 :(得分:0)

session_start()必须在所有输出之前,在此之前移动PHP代码。

<?php

session_start();

if (isset($_POST["enter"])) {                
    $login = $_POST["login"];
    $password = $_POST["password"];
    $query = mysql_query("SELECT * FROM users WHERE password = '$password' AND login = '$login'") or die(mysql_error());
    $user_data = mysql_fetch_array($query);

    if ($user_data) {
        $_SESSION["login"] = $user_data["login"];
        $_SESSION["loggedin"] = true;
    }
    else print('<script>alert("Incorrect login or password!")</script>');
}

// another PHP code

?>

<body>
    ...

答案 1 :(得分:0)

我认为该代码将起作用

<?php

session_start();

if (isset($_POST["enter"])) {                
    $login = $_POST["login"];
    $password = $_POST["password"];
    $query = mysql_query("SELECT * FROM users WHERE password = '$password' AND login = '$login'") or die(mysql_error());
    $user_data = mysql_fetch_array($query);

    if ($user_data) {
        $_SESSION["login"] = $user_data["login"];
        $_SESSION["loggedin"] = true;
        $tpl_body='You are in';


    }
    else $tpl_body='<script>alert("Incorrect login or password!")</script>';
}

// another PHP code

?>

<body>


<?php

echo $tpl_body;

?>

</body>