A login system is one of the most essential features of any website or web application. Whether it’s an e-commerce site, a blogging platform, or an internal company portal, user authentication ensures that only authorized users can access specific areas. In this article, we’ll walk through creating a simple login system in PHP using MySQL.
Prerequisites
Before you start, make sure you have:
A local server environment (XAMPP, WAMP, or MAMP).
Basic knowledge of PHP and MySQL.
A database created with a users table.
Step 1: Create the Database
First, create a database named login_system and a users table.
CREATE DATABASE login_system; USE login_system; CREATE TABLE users ( id INT AUTO_INCREMENT PRIMARY KEY, username VARCHAR(50) NOT NULL, email VARCHAR(100) NOT NULL, password VARCHAR(255) NOT NULL );
You can manually insert a user with an encrypted password:
INSERT INTO users (username, email, password)
VALUES ('testuser', 'test@example.com', MD5('12345'));
Step 2: Database Connection (db.php)
<?php
$host = "localhost";
$user = "root";
$pass = "";
$dbname = "login_system";
$conn = new mysqli($host, $user, $pass, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
?>
Step 3: Create Login Form (login.php)
<!DOCTYPE html> <html> <head> <title>Login System in PHP</title> </head> <body> <h2>Login</h2> <form action="login_process.php" method="POST"> <label>Username:</label><br> <input type="text" name="username" required><br><br> <label>Password:</label><br> <input type="password" name="password" required><br><br> <input type="submit" value="Login"> </form> </body> </html>
Step 4: Process Login (login_process.php)
<?php
session_start();
include 'db.php';
$username = $_POST['username'];
$password = md5($_POST['password']);
$sql = "SELECT * FROM users WHERE username='$username' AND password='$password'";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
$_SESSION['username'] = $username;
header("Location: dashboard.php");
exit();
} else {
echo "Invalid Username or Password!";
}
?>
Step 5: Create Dashboard (dashboard.php)
<?php
session_start();
if (!isset($_SESSION['username'])) {
header("Location: login.php");
exit();
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Dashboard</title>
</head>
<body>
<h2>Welcome, <?php echo $_SESSION['username']; ?>!</h2>
<a href="logout.php">Logout</a>
</body>
</html>
Step 6: Logout (logout.php)
<?php
session_start();
session_unset();
session_destroy();
header("Location: login.php");
exit();
?>
Step 7: Secure the System
Use password_hash() and password_verify() instead of MD5 for better security.
Validate and sanitize user input.
Implement CSRF protection for advanced security.
