Building a Simple Login System with PHP and MySQL πŸš€

Building a Simple Login System with PHP and MySQL πŸš€

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 is VARCHAR(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! πŸŽ‰πŸš€

Leave a Reply