问题描述
我的以下代码有问题。它可以在重定向之前回显变量,没问题。但是重定向之后就不能了。似乎在重定向过程中丢失了会话变量。有什么想法吗?
原始页面:
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}";