重定向后如何从外部登录函数中回显$ _SESSION变量?

时间:2016-03-24 15:00:11

标签: php function login echo session-variables

我有一个重定向到管理员帐户的登录脚本,我想要回显一下在登录功能中创建的一些会话变量,但我一直在获取一个未定义的变量'通知。

这是我的登录脚本

$connect = mysqli_connect('localhost', 'root', '', 'cms1');

function login() {
    global $connect;
    $email = mysqli_real_escape_string($connect, $_POST['email']);
    $password = mysqli_real_escape_string($connect, $_POST['password']);
    $result = mysqli_query($connect, "SELECT * FROM users WHERE email='$email'");
    $row = mysqli_fetch_array($result, MYSQLI_BOTH);

    if (password_verify($password, $row['password'])) {
        session_start();
        $_SESSION["id"]             = $row['user_id'];
        $_SESSION["name"]       = $row['name'];
        $_SESSION["email"]      = $row['email'];
        $_SESSION["gender"]     = $row['gender'];
        $_SESSION["role"]       = $row['role'];

        header('Location: admin/index.php#/dashboard');

    } else {
        header('Location: index.php#/posts/WrongPassword');
    }
}

这是我的管理目录

中的index.php文件的片段
<div class="pcard">
    <img src="../images/T1.jpg" width="100%" alt="...">
    <div class="body">
        <h4><?php echo $_SESSION["name"]; ?></h4>
        <h5>Admin</h5>
    </div>
</div>

1 个答案:

答案 0 :(得分:0)

看起来你可能没有开始你的会话。你需要像这样开始:

session_start();

如果您未在每个页面上启动会话,则需要使用$_SESSION个变量,您将收到如下错误:

E_NOTICE : type 8 -- Undefined variable: _SESSION -- at line 3

如果您不确定如何使用它们,可能值得在PHP中查看the docs for sessions