I am making a login modal that will allow users to have access to a specific page once logged in. I have a login.php, a functions.php, and a index.php. The problem I am having is the user is not being logged in after entering the correct credentials, it just refreshes the login. I have the database connected to my site.
My login.php looks like this:
<?php require_once("../includes/db_connection.php"); ?>
<?php require_once("../includes/functions.php"); ?>
<?php require_once("../includes/session.php"); ?>
<?php
$username = $_POST['username'];
$password = $_POST['password'];
// try to log in assuming user and password are correct
function attempt_login($username, $password) {
$user = find_user_by_username($username);
if($user) {
// found user, now check password
if(password_check($password, $user['password'])) {
// Remove password field from array
unset($user['password']);
// password matches, now get return the user
return $user;
} else {
// password does not match
return false;
}
} else {
// user not found
return false;
}
}
// was user successfully logged in?
if(attempt_login($username, $password)) {
// user successfully logged in
// Mark user as logged in using session value
// This is where the session variable needs to be placed
$placeholder = true;
redirect_to('graves.php');
} else {
// Failure to log in given user (username or password incorrect)
setLoginMessage("Username/password not found.");
redirect_to('index.php#openModal');
}
?>
My functions.php:
<?php
function logged_in() {
return isset($_SESSION['loggedIn']);
}
// part 2
// check if user is logged in and make an error message if not
function confirm_logged_in() {
if(!logged_in()) {
setLoginMessage("Please log in");
redirect_to('index.php#openModal');
}
}
// check if password given from the login form matches the current user's password hash from the database
function password_check($password, $existing_hash) {
// existing hash contains format and salt at start
$hash = crypt($password, $existing_hash);
if ($hash === $existing_hash) {
return true;
} else {
return false;
}
}
// get the current user from the database using their username
function find_user_by_username($username) {
global $connection;
/* Prepared statement, stage 1: prepare */
if (!($stmt = mysqli_prepare($connection, "Select * FROM users WHERE username = ? LIMIT 1"))) {
echo "Prepare failed: (" . mysqli_errno($connection) . ") " . mysqli_error($connection);
}
/* Prepared statement, stage 2: bind parameters */
$stmt->bind_param( 's', $username );
/* Prepared statement, stage 3: execute statement*/
if(!$result = $stmt->execute()){
return null;
} else {
//get result from previously executed statement - old $result variable no longer needed
$result = mysqli_fetch_assoc($stmt->get_result());
return $result;
}
}
?>
I hope this isn't too broad of a question. I have a session.php connected as well.