I recently implemented a simple PHP login system that has the following logic:
- User Submits Form with E-mail & Password
- jQuery post request to external PHP file.
- PHP file checks username and password,
- A.) If login is OK, sets session variable, returns SUCCESS code, which reloads the page (after setting the new session). B.) If login is bad, returns error code.
The problem (not browser specific) is that sometimes (randomly, roughly 1 out of every 2 or 3 times), after a success code has been sent back & the page reloads, the session has NOT been set or changed.
jQuery post request:
function tryLogin() {
$.post( "/assets/lib/lib_actions.php?action=login", {email: $(".login-email").val(), passwor$
if (data == "success") {
window.location.replace("url to homepage - don't wish to reveal website");
} else {
$(".login-alert").css("display", "block");
$(".login-alert").html(data);
}
});
}
PHP Login check:
I've tried to fix the problem by inserting the while loop around where the session is set, but still no luck.
public function login($email, $password) { //will update to prepared statements when done
$row = self::$db->query("SELECT * FROM members WHERE email='".$email."'");
if (mysqli_num_rows($row) == 1) {
$row = self::$db->fetchArray($row);
$savedPassword = $row['password'];
$salt = $row['salt'];
$hash = crypt($password, $salt);
if ($savedPassword == $hash) {
while (!isset($_SESSION['uid']) || $_SESSION['uid'] == "Guest") {
session_regenerate_id();
$_SESSION['uid'] = $row['UID'];
session_write_close();
self::$db->query("UPDATE members SET lastActive=now() WHERE UID='".$row['UID$
}
return "success";
}
}
return "Incorrect E-mail or Password";
}
Does this check on every new page load:
if (isset($_SESSION['uid']) && $_SESSION['uid'] != "Guest") {
I appreciate any help or insights to the problem. I can also post any additional code if requested.