Using PHP $_SESSION, users not staying logged in.
I'm using $_SESSION to keep my users logged in after they have logged in.
When they return to the homepage, they at first appear to be logged in,
but after refreshing the page once, they are no longer logged in.
NOTE: I'm still learning PHP programming so please don't mind that most of
my code is rather, noobish.
Index.php Code:
<?php
session_start();
if (empty($_SESSION['username'])) {
$UserOnline = "Guest";
} else {
$UserOnline = $_SESSION['username'];
}
echo $UserOnline
//Using echo to test what user is logged in (Either Guest or a User)
?>
Login.php Code:
<?php
session_start();
$username = $_POST['username'];
$password = $_POST['password'];
if (empty($username)) {
header ('Location: http://localhost/practice/loginAttempt.php?try=empty');
} elseif (empty($password)) {
header ('Location: http://localhost/practice/loginAttempt.php?try=empty');
}
require 'required/connect.php';
$result = mysqli_query($con, "SELECT * FROM users WHERE
username='$username'");
$row = mysqli_fetch_array($result);
$DBPassword = $row['password'];
if ($password != $DBPassword) {
header ('Location: http://localhost/practice/loginAttempt.php?try=failed');
} else {
$_SESSION['username'] = $username;
header ('Location: http://localhost/practice/');
}
?>
I have tested on the login.php page if the user is in a session there, and
I always get the correct return value. The issue is that after I refresh
once on the Index.php page, the user is no longer in a session.
Is there something I'm forgetting or am I not using the $_SESSION
correctly or is another error that I simply do not know about?
Thanks, Justin
No comments:
Post a Comment