I have used a hash encryption of the password for the user so in the login i check with password_verify if the passwords match and that part of the code seems to be working. And everything inside of the if statment besides something with the sessions. The header Location works but i just get sent back and in the errorlog it says; Undefined index: authorized in C:\xampp\htdocs\portfolio\admin.php on line 22. And authorized is the session im trying to create for checking if the user is logged in.
So my question is partly what I'm doing wrong and partly how a good way to work with sessions in an loginfunction is? My admin.php is supposed to only be accessed if the user is logged in. I will paste the important parts of the code below.
My login.php page:
In the top of the document:
// Error log
ini_set('log_errors', 1);
ini_set('error_log', 'logs/error_log.txt');
//Session
session_start();
session_regenerate_id();
// Includes
include_once 'actions/login_action.php';
?>
In the body:
<div id="login">
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" autocomplete="off">
<p><input type="text" name="user" placeholder="Username" maxlength="30" required/></p>
<p><input type="password" name="pass" placeholder="Password" maxlength="30" required /></p>
<input class="green" name="login" type="submit" value="Log In >>" />
</form>
</div>
<?php
}else{
echo "You are already logged in.";
}
?>
My login_action.php page:
The loop that fetch the result and checks the password:
// Fetch the result
while($stmt->fetch()) {
$pass_crypt = $password;
// Checking password & making sessions
if (password_verify($pass, $pass_crypt) == $pass_crypt) {
$_SESSION['authorized'] = true;
$_SESSION['username'] = htmlspecialchars($user);
// Successful signin logs in logs/success_signin_log.txt
$successLog = fopen("logs/success_signin_log.txt", "ab");
$txt = 'Successful login preformed ' . $date . ' by ' . $user . "\r\n";
fwrite($successLog, $txt);
fclose($successLog);
// Sends to myplace.php
header("Location: admin.php");
}else {
$user = "";
$_SESSION['authorized'] = false;
$errlogin = "Invalid login";
$error = "Login failed, please try again.";
}
}
My admin.php page:
In the top of the document:
// Error log
ini_set('log_errors', 1);
ini_set('error_log', 'logs/error_log.txt');
// Session
session_start();
session_regenerate_id();
// If the session is not set your not logged in or empty user will be sent back to the login page.
if (!isset($_SESSION['authorized']) || $_SESSION['authorized'] == false) {
header ("Location: login.php");
}
?>
!isset($_SESSION['authorized']) && $_SESSION['authorized'] == false, which will / can never be true. Did you probably mean!isset($_SESSION['authorized']) || $_SESSION['authorized'] == false?