PHP 会话变量在重定向后不起作用

PHP Session Variables Not Working After Redirect

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

原始页面:

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"];
?>

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

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

此外,在您创建会话后,您不需要使用 '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}";