【问题标题】:PHP Session Variables Not Working After RedirectPHP 会话变量在重定向后不起作用
【发布时间】:2020-10-09 06:34:52
【问题描述】:

我对以下代码有疑问。它可以在重定向之前回显变量,没问题。但是重定向之后就不行了。它似乎在重定向过程中丢失了会话变量。有什么想法吗?

原始页面:

if (password_verify($rawpassword,$row["passwordHash"])) {
    session_start();
    $_SESSION["email"] = $email;
    $_SESSION["fname"] = $row["firstName"];
    echo $_SESSION["email"];
    echo $_SESSION["fname"];
    header("Location: https://www.mywebsite.com/home.php");
} else {
    header("Location: https://www.mywebsite.com/signin.php?addlComment=3True");
    die();
}

以下页面:

<?php
    echo $_SESSION["email"];
    echo $_SESSION["fname"];
?>

【问题讨论】:

  • 您需要为该特定页面启动会话,请参阅有关它的一些文档session

标签: php variables session redirect session-variables


【解决方案1】:

您应该了解有关会话的更多信息,以避免出错并且不会让您的代码易受攻击!

知道要使用会话,您必须在每个脚本的开头开始它们

另外,创建会话后,您不需要使用“echo”命令,并且在重定向到成功页面后,实际上,您应该在成功页面上使用“echo”命令,并创建一些变量来存储这些会话的值,使其更易于使用,并使代码更简洁!

请试一试:

登录

<?php
    session_start();
    //Start the session in the top of the script
      

    if (password_verify($rawpassword, $row["passwordHash"])) {
        $_SESSION["email"] = $email;
        $_SESSION["fname"] = $row["firstName"];
        header("Location: home.php");
        exit();
    } else {
        header("Location: signin.php?addlComment=3True");
        exit();
    }

首页

<?php

    session_start();
    
    session_regenerate_id(true); //It can help you to protect against attacks, try to learn it!
    
    
    
    $email =  $_SESSION['email'];
    $first_name = $_SESSION['fname'];
    
    
    //If the user try to access the page without make login, then redirect to the signin page
    if(!email || !first_name)
    {
        header("Location: signin.php");
        exit();
    }
    
    
    
    //Test the sessions variables
    
    
    echo "Welcome, you're logged in! I know your first name is: {$first_name}";
    
    
    
      

【讨论】:

    猜你喜欢
    • 2014-02-16
    • 2016-12-01
    • 2012-11-17
    • 2017-09-02
    • 2014-08-14
    • 2012-07-14
    • 2018-11-19
    相关资源
    最近更新 更多