🔐 Build a Login System with PHP and MySQL

php-mysql-login-system-tutorial

Introduction

User authentication is one of the most common features in web applications — from blogs to dashboards, login systems are everywhere. In this beginner-friendly tutorial, you’ll learn how to build a simple login system using PHP and MySQL.

We’ll go step-by-step in small snippets, explaining each part clearly so you can learn by building. By the end, you’ll understand how sessions, form handling, and database queries work together to secure user access.


🛠️ Tools You’ll Need

  • PHP (local server with XAMPP, MAMP, or similar)
  • MySQL (via phpMyAdmin or CLI)
  • A basic code editor (VS Code, Sublime Text)

🧱 Step 1: Create a MySQL Database & Users Table

Let’s start by setting up a database and a users table to store login credentials.

📄 Snippet 1: SQL to Create Database and Table

CREATE DATABASE user_auth;

USE user_auth;

CREATE TABLE users (
    id INT AUTO_INCREMENT PRIMARY KEY,
    username VARCHAR(50) NOT NULL UNIQUE,
    password VARCHAR(255) NOT NULL
);

💡 Explanation:

  • user_auth is the database where we’ll store user data.
  • users table includes username and a hashed password.
  • VARCHAR(255) for password is to store hashed strings (we’ll hash passwords later using password_hash()).

🧾 Step 2: HTML Login Form

Now let’s create the frontend form that users will interact with.

📄 Snippet 2: Basic Login Form (login.html)

<form action="login.php" method="POST">
    <h2>Login</h2>
    <input type="text" name="username" placeholder="Username" required />
    <input type="password" name="password" placeholder="Password" required />
    <button type="submit">Login</button>
</form>

💡 Explanation:

  • The form uses POST method to keep credentials private.
  • It sends data to login.php, which we’ll create next to handle the logic.

🔒 Step 3: Handle Login in PHP

Let’s now write the server-side script to verify credentials.

📄 Snippet 3: Login Logic (login.php)

<?php
session_start();
$conn = new mysqli('localhost', 'root', '', 'user_auth');

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $username = $_POST['username'];
    $password = $_POST['password'];

    // Prepare and execute SQL
    $stmt = $conn->prepare("SELECT * FROM users WHERE username = ?");
    $stmt->bind_param('s', $username);
    $stmt->execute();

    $result = $stmt->get_result();
    $user = $result->fetch_assoc();

    // Verify password
    if ($user && password_verify($password, $user['password'])) {
        $_SESSION['username'] = $user['username'];
        header("Location: dashboard.php");
    } else {
        echo "Invalid username or password.";
    }
}
?>

💡 Explanation:

  • We start a session to track the logged-in user.
  • Use prepared statements (preparebind_param) to prevent SQL injection.
  • password_verify() compares the entered password with the hashed one stored in the database.
  • If login is successful, we redirect to dashboard.php.

📥 Step 4: Optional – User Registration Page

You can’t log in without users! Let’s add a simple registration handler.

📄 Snippet 4: Register Script (register.php)

<?php
$conn = new mysqli('localhost', 'root', '', 'user_auth');

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);

    if ($stmt->execute()) {
        echo "User registered successfully!";
    } else {
        echo "Error: Username may already exist.";
    }
}
?>

💡 Explanation:

  • We use password_hash() to securely store the password.
  • This script can be paired with a similar HTML form like the login one.

📄 Step 5: Dashboard (Protected Page)

Let’s create a simple page users will see only if logged in.

📄 Snippet 5: Dashboard Page (dashboard.php)

<?php
session_start();

if (!isset($_SESSION['username'])) {
    header("Location: login.html");
    exit();
}
?>

<h1>Welcome, <?php echo $_SESSION['username']; ?>!</h1>
<a href="logout.php">Logout</a>

💡 Explanation:

  • This page checks if a user is logged in via session.
  • If not, it redirects them back to login.
  • We also add a logout link.

🚪 Step 6: Logout Script

📄 Snippet 6: Logout Script (logout.php)

<?php
session_start();
session_destroy();
header("Location: login.html");
?>

💡 Explanation:

  • Destroys the session and redirects user to login.
  • Simple but crucial for managing user access.

📌 Combine It All

Once you’ve gone through all the snippets:

✨ Combine these code pieces into your project folder to see the full working login system in action!

Try registering a user, logging in, viewing the dashboard, and logging out to test the full flow.


🧠 Best Practices & Tips

  • Always use password_hash() and password_verify() — never store plain text passwords.
  • Protect routes by checking session variables.
  • Use HTTPS in production to secure data transmission.
  • Consider rate limiting or CAPTCHA to prevent brute force attacks.

🔎 SEO & Performance Tie-In

A secure and functional login system improves user experience and site credibility — both of which contribute to better SEO. Plus, search engines favor well-structured, fast, and secure sites.


✅ Conclusion

You’ve just built a working login system using PHP and MySQL — a foundational backend skill every developer should know! 🎉

Want to level up? Try adding features like:

  • “Remember Me” checkbox
  • Forgot Password reset flow
  • User roles and admin panel

👉 Got questions or stuck on something? Drop a comment below — or explore our other tutorials in the backend-apis section to keep learning!

Post a Comment

0 Comments