I’m restricting my administrative panel, to only accept access when a session exist.
When the user login with sucess I store a session like this:
...
$result = $readUser->fetch(PDO::FETCH_ASSOC);
$_SESSION['result'] = $result;
And then in my dashboard.php I see if session exists:
if(!$_SESSION['result'])
{
header('Location: index.php?restricted=true');
}
If not exists I send user to index.php
that is where I havemy login form.
This simple code above its not enough??
But I read now that is important see if the session is valid and if the session exists, check also if the session is valid, and so we must read database to verify that the information of user session are the same as we have in the database.
But, I didnt understand, why and when a session, that exists, can be invalid and how the information of a user session cant be different in database, if he did login and was stored a session with his login?
And the code verifying database will be like this:
if(!$_SESSION['result'])
{
header('Location: index.php?restricted=true');
}
else{
$userId = $_SESSION['result']['id'];
$readUser = $pdo->prepare("SELECT * FROM admins where id = :userId");
$readUser->bindValue(":userId", $userId);
$readUser->execute();
if(!$readUser->rowCount() >=1){
unset($_SESSION['userlogin']);
header('Location: index.php?resctricted=true');
}
}