Secure Login System
This Secure Login System example is a practical and reliable web-based application built with PHP and MySQL that demonstrates how real-world websites manage user authentication securely. Instead of storing plain-text passwords, this system uses password hashing (encryption) to protect user credentials. Users can register with a unique username and password, log in securely using hashed credentials, access a protected dashboard, and log out safelyFolder Structure
login-system/ │ ├── db.php ← Database connection ├── register.php ← Registration form & logic ├── login.php ← Login form & logic ├── dashboard.php ← Protected page ├── logout.php ← Logout logic ├── style.css ← Styling
Step-by-Step Files
db.php
<?php
$conn = new mysqli("localhost", "root", "", "login_demo");
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
?>
🔍 What's happening here?
You're creating a new connection to your MySQL database using PHP.
- ☆ "localhost" → This tells PHP that the MySQL server is on the same machine (local server).
- ☆ "root" → The MySQL username. On XAMPP, the default is usually
root. - ☆
""→ The password. XAMPP’s root user usually has no password by default. - ☆ "login_demo" → The name of the database you want to use.
- ☆ $conn->connect_error → This will contain a message if the connection fails.
- ☆ die("Connection failed: ...") → If there's a problem, this stops the script and prints the error message.
register.php
<?php
require 'db.php';
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$username = $_POST["username"];
$password = password_hash($_POST["password"], PASSWORD_DEFAULT);
$stmt = $conn->prepare("INSERT INTO users (username, password) VALUES (?, ?)");
$stmt->bind_param("ss", $username, $password);
try{
$stmt->execute();
echo "Registered successfully!";
} catch (mysqli_sql_exception $e) {
echo "Username already taken.";
}
}
?>
<link rel="stylesheet" href="style.css">
<form method="post">
<h2>Register</h2>
Username: <input name="username" required><br>
Password: <input type="password" name="password" required><br>
<button type="submit">Register</button>
</form>
🔍 What’s happening in the registration logic?
This PHP code runs when a user submits the registration form. Let’s break it down step by step:
- ☆ require 'db.php'; → Includes the file that connects to the MySQL database.
- ☆ $password = password_hash($_POST["password"], PASSWORD_DEFAULT); → Encrypts the password using a secure hashing algorithm so we never store plain text passwords in the database.
- ♣ PASSWORD_DEFAULT tells PHP to use the current strongest default algorithm. As of PHP 7 and 8, this means bcrypt (very secure).
- ♣ Example:
$plaintext = "mypassword"; $hashed = password_hash($plaintext, PASSWORD_DEFAULT); echo $hashed;
? for safely inserting user data."ss" means:
- ♣ First s → string for $username
- ♣ Second s → string for $password
- ♣ If successful, the user is registered and sees "Registered successfully!"
- ♣ If the username already exists (e.g., duplicate entry), it shows "Username is already taken."
- ♣try-catch is used to catch and handle exceptions. Without the try-catch, a duplicate username would cause a Fatal Error
login.php
<?php
session_start();
require 'db.php';
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$username = $_POST["username"];
$password = $_POST["password"];
$stmt = $conn->prepare("SELECT id, password FROM users WHERE username = ?");
$stmt->bind_param("s", $username);
$stmt->execute();
$stmt->store_result();
if ($stmt->num_rows === 1) {
$stmt->bind_result($id, $hashed_password);
$stmt->fetch();
if (password_verify($password, $hashed_password)) {
$_SESSION["user_id"] = $id;
header("Location: dashboard.php");
exit;
}
}
echo "Invalid username or password.";
}
?>
<link rel="stylesheet" href="style.css">
<form method="post">
<h2>Login</h2>
Username: <input name="username" required><br>
Password: <input type="password" name="password" required><br>
<button type="submit">Login</button>
</form>
🔍 What’s happening in the login logic?
This PHP code runs when a user submits the login form. Let’s break it down step by step:
- ☆ session_start(); → Starts a session so we can store user info after they log in. To ensure that multiple PHP pages can access the $_SESSION variables consistently.
- ☆ $stmt = $conn->prepare("SELECT id, password FROM users WHERE username = ?"); → Prepares a safe SQL statement to find the user with the given username. (Prevents SQL injection!)
- ☆ $stmt->bind_param("s", $username); →
Binds the actual username value to the SQL query. The
"s"means:- s → a string parameter for $username
- ☆ $stmt->execute(); and $stmt->store_result(); → Runs the query and stores the result so we can check how many rows it found.
- ☆ if ($stmt->num_rows === 1) →
Checks if one user was found with that username.
- ♣ $stmt->bind_result($id, $hashed_password); → gets the user's ID and stored hashed password from the database.
- ♣ $stmt->fetch(); → retrieves the data into those variables.
- ☆ password_verify($password, $hashed_password); →
Compares the typed password to the hashed password stored in the database.
- ♣ If correct → login success! ✅
- ♣ We set $_SESSION["user_id"] and redirect to
dashboard.php. - ♣ The header redirects the user to the protected page (like their dashboard).
- ♣ exit; is important—it stops the script immediately to make sure nothing else runs after the redirect.
- ☆ If the username is not found or the password doesn’t match, the user sees: "Invalid username or password."
dashboard.php
<link rel="stylesheet" href="style.css">
<?php
session_start();
if (!isset($_SESSION["user_id"])) {
header("Location: login.php");
exit;
}
echo "<h2>Welcome! You are logged in.</h2>";
echo "<a href='logout.php'>Logout</a>";
?>
🔍 What’s happening in the dashboard logic?
This PHP code makes sure only users who are logged in can access the dashboard. Let’s break it down step by step:
- ☆ session_start(); → This starts or resumes the session so we can access
$_SESSIONvariables. - ☆ if (!isset($_SESSION["user_id"])) →
Checks if the user is not logged in.
- ♣
$_SESSION["user_id"]is only set after a successful login. - ♣ If it’s missing, we redirect the user to the
login.phppage.
- ♣
- ☆ header("Location: login.php"); → This safely redirects the user to the login page if they're not authenticated.
- ☆ exit; → Stops the script immediately after redirection so no protected content is accidentally shown.
- ☆ echo "Welcome! You are logged in." → This is shown only if the user is authenticated.
- ☆ echo "<a href='logout.php'>Logout</a>" → Gives the user a link to log out and destroy the session.
✅ This protects your page from being accessed directly by someone who isn’t logged in. Without this check, anyone could visit dashboard.php even without logging in!
logout.php
<?php
session_start();
session_destroy();
header("Location: login.php");
exit;
?>
🔍 What's happening here?
This PHP script logs the user out by ending the session and redirecting them back to the login page.
- ☆ session_start() → Starts or resumes the current session. Required before using or destroying session data.
- ☆ session_destroy() → Destroys all session data, effectively logging the user out.
- ☆ header("Location: login.php") → Redirects the user to the login page after logout.
- ☆ exit → Stops the script to ensure no other code runs after the redirect.
style.css
body {
font-family: Arial, sans-serif;
background-color: #f7f7f7;
padding: 30px;
}
form {
background: #fff;
padding: 20px;
border-radius: 8px;
box-shadow: 0 0 10px #ccc;
}
input {
margin-bottom: 10px;
padding: 8px;
width: 200px;
}
button {
padding: 10px;
}
Setup Instructions
- ☆ Put all files into your XAMPP htdocs/login-system folder
- ☆ You need to create a database and a table using phpMyAdmin in XAMPP before running your PHP login system.
1. Create a database: login_demo 2. Run this SQL: CREATE TABLE users ( id INT AUTO_INCREMENT PRIMARY KEY, username VARCHAR(50) NOT NULL UNIQUE, password VARCHAR(255) NOT NULL ); 3. Open register.php to create a user 4. Open login.php to log in 5. dashboard.php is protected