PHP:传递会话变量失败

时间:2017-05-19 10:47:00

标签: php session login

我想将会话变量从login.php页面传递给test-start.php

我的PHP登录页面:

<?php session_start();?>
<html>
<body>
<?php 
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if ($_POST["username"] == "suren" && $_POST["password"] == "passwd")
{
$_SESSION['login'] = true;
$_SESSION["var"]="true";
var_dump($_SESSION['login']);
header("location: /login/test-start.php");
#session_write_close()
#I've tried session_write_close option as well!!!
exit();
}
else 
{
echo "<h2>Try Again !!!</h2>";
}
}
?>
<form method = "POST" action = "<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<input type = "text" name="username">
<input type = "text" name = "password">
<input type="submit" value = "login">
</form>
</body>
</html>

我的第二页:

<?php session_start();?>
<html>
<body>
<?php
var_dump($_SESSION['login']);
echo $_SESSION['login'];
if (!$_SESSION['login']){
echo "<h2>Login first!!!<h2>";
#header("location:/login/newlogin.php");
#die;
}
#echo "<h2>Successfully Logged in <h2>";
?>
</body>
</html>

在这里我得到以下输出:我使用var_dump()作为会话变量......

/opt/monitor/web/login/test-start.php:6:null

先登录!!!

1 个答案:

答案 0 :(得分:0)

我无法重现您的代码。它在这里工作正常。第二个脚本报告登录成功。但是,在使用header命令重定向之前有输出,这可能会导致一些问题。我稍微调整了您的代码,但保留了您的实现:

newlogin.php

<?php 
session_start();
$try_again = false;
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    if ($_POST["username"] == "suren" && $_POST["password"] == "passwd") {
        $_SESSION['login'] = true;
        $_SESSION["var"]="true";
        header("location: loggedin.php");
        exit();
    }
    else {
        $try_again = true;
    }
}
?>
<html>
<body>
<?php
if ($try_again) { 
    echo "<h2>Try Again !!!</h2>";
}
?>
<form method = "POST" action = "<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<input type = "text" name="username">
<input type = "text" name = "password">
<input type="submit" value = "login">
</form>
</body>
</html>

loggedin.php

<?php 
session_start();
var_dump($_SESSION);

输出

array(2) { ["login"]=> bool(true) ["var"]=> string(4) "true" }

编辑:您可能已将文件编码为带有BOM的UTF8。这会在每个文件的开头插入一个不可见的字符。这会导致session_start失败。如果您已关闭所有错误输出,则可能看不到此错误。如果您还没有这样做,请尝试将文件编码为UTF8而不使用BOM。