Every website needs user authentication, whether itβs for a dashboard, admin panel, or member-only content. In this guide, youβll learn how to build a secure login system in PHP using MySQL, sessions, and password hashing.
π― What Youβll Learn:
β
How to create a user registration system
β
How to store passwords securely (using password_hash()
)
β
How to handle user login & logout
β
How to use sessions to keep users logged in
Letβs get started! π
1οΈβ£ Setting Up the Database
Before we start coding, letβs create the database and users
table.
Run this SQL command:
CREATE DATABASE zeroexp_dev;
USE zeroexp_dev;
CREATE TABLE users (
id INT AUTO_INCREMENT PRIMARY KEY,
username VARCHAR(50) UNIQUE NOT NULL,
email VARCHAR(100) UNIQUE NOT NULL,
password VARCHAR(255) NOT NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
π₯ What happens?
- The
users
table stores username, email, and hashed password. - The
password
column isVARCHAR(255)
because hashed passwords are long.
2οΈβ£ Database Connection File (db.php)
Weβll use PDO to connect PHP to MySQL.
db.php
<?php
$host = "localhost";
$dbname = "zeroexp_dev";
$username = "root";
$password = "";
try {
$pdo = new PDO("mysql:host=$host;dbname=$dbname;charset=utf8", $username, $password);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
die("Database connection failed: " . $e->getMessage());
}
?>
π₯ Why use PDO?
β
More secure than mysqli_connect()
β
Supports prepared statements (prevents SQL injection)
3οΈβ£ User Registration (Signup)
Users need to register first before logging in.
register.php
<?php
require "db.php";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$username = trim($_POST["username"]);
$email = trim($_POST["email"]);
$password = password_hash($_POST["password"], PASSWORD_BCRYPT); // Hash password
$stmt = $pdo->prepare("INSERT INTO users (username, email, password) VALUES (?, ?, ?)");
if ($stmt->execute([$username, $email, $password])) {
echo "Registration successful! <a href='login.php'>Login here</a>";
} else {
echo "Error registering user!";
}
}
?>
<form method="post">
Username: <input type="text" name="username" required><br>
Email: <input type="email" name="email" required><br>
Password: <input type="password" name="password" required><br>
<input type="submit" value="Register">
</form>
π₯ Why use password_hash()
?
- Stores passwords securely instead of plain text.
- Uses bcrypt encryption, making it almost impossible to crack.
4οΈβ£ User Login (Authentication)
Once users register, they can log in.
login.php
<?php
session_start();
require "db.php";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$username = trim($_POST["username"]);
$password = trim($_POST["password"]);
$stmt = $pdo->prepare("SELECT * FROM users WHERE username = ?");
$stmt->execute([$username]);
$user = $stmt->fetch(PDO::FETCH_ASSOC);
if ($user && password_verify($password, $user["password"])) {
$_SESSION["username"] = $username; // Store user session
header("Location: dashboard.php");
} else {
echo "Invalid credentials!";
}
}
?>
<form method="post">
Username: <input type="text" name="username" required><br>
Password: <input type="password" name="password" required><br>
<input type="submit" value="Login">
</form>
π₯ What happens?
β
password_verify()
compares the hashed password from the database.
β
If login is successful, we store the username in a session.
β
If login fails, the user sees an error message.
5οΈβ£ Creating a Dashboard (Protected Page)
Now, letβs create a dashboard that only logged-in users can access.
dashboard.php
<?php
session_start();
if (!isset($_SESSION["username"])) {
echo "Access denied! <a href='login.php'>Login here</a>";
exit;
}
echo "Welcome, " . $_SESSION["username"] . "! <a href='logout.php'>Logout</a>";
?>
π₯ What happens?
β
If no session exists, access is denied.
β
Logged-in users see a welcome message.
6οΈβ£ Logout System
Users should be able to log out safely.
logout.php
<?php
session_start();
session_unset();
session_destroy();
header("Location: login.php");
?>
π₯ What happens?
β
session_unset()
removes all session data.
β
session_destroy()
ends the session.
β
The user is redirected to the login page.
π― Mini Project: User Authentication System
Now, letβs combine everything into a fully functional login system.
File | Purpose |
---|---|
db.php |
Connects PHP to MySQL |
register.php |
Handles user registration |
login.php |
Processes login requests |
dashboard.php |
Displays user dashboard (requires login) |
logout.php |
Logs users out |
β What Youβve Built
βοΈ Users can register with a secure password
βοΈ Users can log in with hashed passwords
βοΈ Logged-in users can access a private dashboard
βοΈ Users can securely log out
π Boom! You now have a secure login system in PHP!
π Final Thoughts
Now you know how to:
β
Store passwords securely with password_hash()
β
Authenticate users safely
β
Use sessions to manage logins
β
Build a simple login system in PHP
π Next: Pagination in PHP
Happy coding! ππ