Build PHP Login, Logout, and Role‑Based Access Control in Minutes
This guide shows how to create a MySQL users table, implement PHP functions for user login and logout using sessions, and add a role‑based permission check to control access for administrators and regular users.
When developing a website, user authentication and role‑based authorization are essential. First, create a users table in MySQL to store id, username, hashed password, role, and created_at timestamps.
CREATE TABLE users (
id INT(11) AUTO_INCREMENT PRIMARY KEY,
username VARCHAR(100) NOT NULL,
password VARCHAR(100) NOT NULL,
role VARCHAR(50) NOT NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);Next, implement a login function that queries the table for the supplied username, verifies the password with password_verify, and stores the user’s id, username, and role in $_SESSION if authentication succeeds.
function login($username, $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'])) {
$_SESSION['user_id'] = $user['id'];
$_SESSION['username'] = $user['username'];
$_SESSION['role'] = $user['role'];
return true;
}
}
return false;
}For logout, simply destroy the session:
function logout() {
session_unset();
session_destroy();
}To enforce multi‑level permissions, add a checkPermission function that compares the required role with the role stored in the session and returns a boolean.
function checkPermission($requiredRole) {
if (isset($_SESSION['role']) && $_SESSION['role'] == $requiredRole) {
return true;
} else {
return false;
}
}Use the permission check to guard actions:
if (checkPermission('admin')) {
// admin operations
} elseif (checkPermission('user')) {
// regular user operations
} else {
// no permission
}These snippets provide a complete, lightweight solution for PHP login, logout, and role‑based access control, enabling flexible permission management and improving website security.
php Courses
php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
