What is the best practice for checking user type along with password verification in PHP?
When verifying a user's login credentials in PHP, it's important to not only check the password but also verify the user type to ensure they have the appropriate access level. One common approach is to store the user type in the database along with the username and password. When a user tries to log in, you can query the database to retrieve the user's type and then compare it to the expected type.
// Assuming you have already connected to the database
$username = $_POST['username'];
$password = $_POST['password'];
$query = "SELECT * FROM users WHERE username = '$username'";
$result = mysqli_query($conn, $query);
if(mysqli_num_rows($result) == 1) {
$user = mysqli_fetch_assoc($result);
if(password_verify($password, $user['password'])) {
$userType = $user['user_type'];
if($userType == 'admin') {
// User is an admin
} else if($userType == 'regular') {
// User is a regular user
} else {
// Handle other user types
}
} else {
// Incorrect password
}
} else {
// User not found
}
Related questions
-
imagecreatetruecolor ImageCreate image manipulation
-
GET requests length limitations form submission
-
preg_match delimiters patterns