Admin and User Login in PHP with MySQL Source Code
This article will guide you through creating a simple yet effective admin and user login system using PHP and MySQL. This system will allow users to register, login, and access different functionalities based on their roles.
Project Setup
-
Database Setup:
- Create a new database (e.g.,
login_system
). - Create a table named
users
with the following columns:id
(INT, PRIMARY KEY, AUTO_INCREMENT)username
(VARCHAR(255), UNIQUE)password
(VARCHAR(255))role
(ENUM('user', 'admin'))
- Create a new database (e.g.,
-
PHP Files:
- Create three PHP files:
index.php
(for registration and login)admin.php
(for admin-specific content)user.php
(for user-specific content)
- Create three PHP files:
Registration Form (index.php)
alert('Registration successful!');";
} else {
echo "";
}
}
?>
Login/Registration
Registration
Login
Login Authentication (index.php)
0) {
$row = mysqli_fetch_assoc($result);
// Verify password
if (password_verify($password, $row['password'])) {
// Start session
session_start();
$_SESSION['username'] = $username;
$_SESSION['role'] = $row['role'];
// Redirect based on user role
if ($row['role'] == 'admin') {
header('Location: admin.php');
} else {
header('Location: user.php');
}
} else {
echo "";
}
} else {
echo "";
}
}
// ... (other code)
?>
Admin Page (admin.php)
Welcome, Admin";
// Display admin-specific content here
} else {
header('Location: index.php');
}
?>
User Page (user.php)
Welcome, " . $_SESSION['username'] . "";
// Display user-specific content here
} else {
header('Location: index.php');
}
?>
Explanation
- Database Connection: The
config.php
file contains the database connection details. - Registration: The registration form collects username and password. The password is hashed using
password_hash()
for security. - Login: The login form checks if the user exists in the database. If found, the password is verified using
password_verify()
. - Session Management: Session variables are used to store user information after successful login.
- Role-Based Access: The code redirects the user to either
admin.php
oruser.php
based on their assigned role.
Security Considerations
- Password Hashing: Always use strong password hashing algorithms like
PASSWORD_DEFAULT
for security. - Input Validation: Sanitize and escape all user input to prevent SQL injection attacks.
- Session Handling: Use secure session handling methods to prevent session hijacking.
- Error Handling: Implement proper error handling to prevent vulnerabilities and provide informative messages.
Conclusion
This guide provides a basic framework for creating a login system with admin and user roles using PHP and MySQL. You can further expand this system by adding features like user profile management, password reset functionality, and more robust security measures. Remember to prioritize security best practices throughout the development process.