How to add user access level in PHP login function
P粉680000555
2023-09-05 20:51:43
<p>I developed a PHP login/registration script that when a user logs in, it starts a session and creates a cookie, then redirects the user to dashboard.php using: </p>
<pre class="brush:php;toolbar:false;">//get data in variables
$emailAddress = mysqli_real_escape_string($conn,$_POST['emailAddress']);
$password = mysqli_real_escape_string($conn,$_POST['password']);
$remember = isset($_POST['rememberMe']);
if(!filter_var($emailAddress, FILTER_VALIDATE_EMAIL)) {
$error = 'Please enter a valid email address.';
}
elseif(email_exists($emailAddress,$conn)) { // if email address exists
$result = mysqli_query($conn,"SELECT password FROM users WHERE email = '$emailAddress'");
$retrievePassword = mysqli_fetch_assoc($result);
if(!password_verify($password,$retrievePassword['password'])) // if password does not match
{
$error = 'Password is incorrect.';
} else { // if password correct, log user in
$_SESSION['email'] = $emailAddress;
if($remember == 'on') { // if "keep user logged in" was ticked
setcookie("email",$emailAddress,time() 7200); // keep user logged in for 2 hours
}
header("location: dashboard.php");
}
} else { // if email does not exist
$error = 'Email address not registered.';
}</pre>
<p>At the top of all my restricted pages (e.g. dashboard.php) I have: </p>
<pre class="brush:php;toolbar:false;">if(logged_in()) { // if user logged in, show page</pre>
<p>logged_in() function is: </p>
<pre class="brush:php;toolbar:false;">function logged_in(){
if(isset($_SESSION['email']) || isset($_COOKIE['email'])) {
return true;
} else {
return false;
}
}</pre>
<p>In the database I have a column titled <code>usrUserTypeNo</code> which has "1" for admin and "3" for regular users.
How do I incorporate this user type into the session so I can determine what content is shown to the user based on their role? </p>
not completely.
If you want to perform one of three different actions (not logged in, normal user, admin user), then you must test these states and write logic for each state.
You can store the access level in the session instead of requesting it from the database every time.