Basic Login System with PHP and MySQL

Basic Login System with PHP and MySQL

👋 Hey there, PHP developer! In this blog post, you’ll learn how to create a basic login system with PHP and MySQL, even if you’re just starting out with web development. Login systems are a core part of nearly every website that requires authentication. Whether you’re building a personal blog or a custom admin panel, knowing how to create a secure login is essential.

Let’s walk through everything you need to get started — with full explanations, code blocks, and helpful tips.

Why You Need a Login System

A login system allows users to securely access parts of your website that are not meant for the public — like a dashboard, profile page, or admin panel.

Without login functionality, there’s no way to identify or restrict user access, making your application vulnerable and unscalable.

Tools and Technologies Used

To build our login system with PHP and MySQL, we’ll use the following:

  • PHP: Server-side scripting language
  • MySQL: Database to store user credentials
  • HTML/CSS: For form design
  • XAMPP or Localhost: To run PHP locally

Setting Up the Database

Let’s start by creating a database and a users table.

Step 1: Create a Database

PHP
CREATE DATABASE demo;

Step 2: Create a users Table

PHP
USE demo;

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

We store passwords using hashed values, not plain text (we’ll see how in PHP later).

Creating the Registration Form (Optional)

Although this post focuses on the login system, let’s quickly create a registration page to insert a user.

register.php

PHP
<?php
$conn = new mysqli("localhost", "root", "", "demo");

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $username = $_POST['username'];
    $password = password_hash($_POST['password'], PASSWORD_DEFAULT); // secure hash

    $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: " . $stmt->error;
    }
}
?>

<form method="POST">
    Username: <input type="text" name="username" required><br><br>
    Password: <input type="password" name="password" required><br><br>
    <input type="submit" value="Register">
</form>

This allows you to create a few users for testing.

Creating the Login Form

Now let’s design a simple login form using HTML.

login.php

PHP
<form method="POST" action="login_process.php">
    <h2>Login</h2>
    <label>Username:</label>
    <input type="text" name="username" required><br><br>
    
    <label>Password:</label>
    <input type="password" name="password" required><br><br>
    
    <input type="submit" value="Login">
</form>

Keep it minimal and user-friendly.

Login Script in PHP

Here’s where the magic happens: validating the user and setting up sessions.

login_process.php

PHP
<?php
session_start();
$conn = new mysqli("localhost", "root", "", "demo");

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;
            $_SESSION['username'] = $username;
            header("Location: dashboard.php");
            exit();
        } else {
            echo "Incorrect password.";
        }
    } else {
        echo "User not found.";
    }
}
?>

We use password_verify() to safely compare the input password with the stored hash.

Dashboard Page After Login

Only logged-in users should access this page. We’ll check if a session is set.

dashboard.php

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

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

Now, users who log in successfully are redirected here.

Logout Functionality

Logging out simply means destroying the session.

logout.php

PHP
<?php
session_start();
session_unset();
session_destroy();

header("Location: login.php");
exit();

Simple and clean.

Securing Your Login System

Security is critical when handling user data. Let’s improve your login system’s protection:

1. Use Prepared Statements

Already implemented above to prevent SQL injection.

2. Hash Passwords

We’re using password_hash() and password_verify() — modern and secure.

3. Session Security

Regenerate session ID after login:

PHP
session_regenerate_id();

4. Rate Limiting / CAPTCHA

Add limits on login attempts or Google reCAPTCHA for bots.

5. HTTPS

Always use HTTPS in production to encrypt data transmission.

🔐 Learn more from this OWASP Authentication Cheat Sheet.

Wrapping Up

That’s a complete and beginner-friendly walkthrough of creating a login system with PHP and MySQL.

You’ve learned how to:

  • Set up a secure database
  • Create a login form
  • Authenticate users with password hashing
  • Redirect and manage sessions
  • Logout and protect pages

This simple system can be extended with:

  • User roles (admin, editor, etc.)
  • Email verification
  • Password reset via email
  • Persistent login (remember me)

🎯 Final Thoughts

Building your own login system not only improves your understanding of PHP and MySQL but also gives you better control over how authentication works.

It’s important to build this foundation before moving on to more complex frameworks like Laravel or Symfony.

Have questions? Drop them in the comments or share your own version of the login system! 👇

Happy coding! 🔐💻


Comments

Leave a Reply

Your email address will not be published. Required fields are marked *