I am having an issue with the follow code. It can echo the variables before it redirects, no problem. But after it redirects, it cannot. It seems to be losing the session variables in the redirect process. Any thoughts?
Original Page:
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();
}
The Following Page:
<?php
echo $_SESSION["email"];
echo $_SESSION["fname"];
?>
You should learn more about sessions to avoid making mistakes and not leaving your codes vulnerable!
Know that to work with sessions, you must start them right at the beginning of each script
Also, after you create your session, you don't need to use the 'echo' command and right after redirecting to the success page, in fact, it is on the success page that you should work with the 'echo' command, and create some variables to store the value of those sessions, to make it easier to work with, and to make the code cleaner!
Please try it:
Signin
<?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();
}
Home
<?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}";