Reputation: 671
When a user uses the login system on my website and the credentials submitted are correct, a session and session data is set. But the sesion data is not being carried over from page to page. At the login script I printed out the session array and it showed everything was being set. But when I went to a different page with the same code that prints the session, it shows there is nothing in the session. (Yes, I am inserting session_start()
at the beginning of every php page that needs it)
Login.php
<?php
require("config.php");
if(!empty($_POST))
{
// This query retreives the user's information from the database using
// their username.
$query = "
SELECT
id,
username,
password,
salt,
email
FROM users
WHERE
username = :username
";
// The parameter values
$query_params = array(
':username' => $_POST['username']
);
try
{
// Execute the query against the database
$stmt = $db->prepare($query);
$result = $stmt->execute($query_params);
}
catch(PDOException $ex)
{
die("Failed to run query: " . $ex->getMessage());
}
$login_ok = false;
$row = $stmt->fetch();
if($row)
{
$check_password = hash('sha256', $_POST['password'] . $row['salt']);
for($round = 0; $round < 65536; $round++)
{
$check_password = hash('sha256', $check_password . $row['salt']);
}
if($check_password === $row['password'])
{
// If they do, then we flip this to true
$login_ok = true;
}
}
// If the user logged in successfully, then we send them to the private members-only page
// Otherwise, we display a login failed message and show the login form again
if($login_ok)
{
unset($row['salt']);
unset($row['password']);
$_SESSION['USER'] = $row;
/* print_r($_SESSION); */
session_write_close();
header("Location: index.php");
// Redirect the user to the index page.
die("Redirecting to the home page.");
}
else
{
print("Login Failed.");
$submitted_username = htmlentities($_POST['username'], ENT_QUOTES, 'UTF-8');
header("Location: login.php");
exit;
}
}
echo $message;
?>
This next script checks to see if the session is set. If it isn't, it redirects the user to the login page.
<?php
/*** begin the session ***/
session_start();
if(!isset($_SESSION['USER']))
{
// If they are not, we redirect them to the login page.
header("Location: ../login.php");
exit;
}
?>
Upvotes: 0
Views: 103