How To Build Login And Registration System In Php Mysql is Changing the World

How To Build Login And Registration System In Php Mysql is Changing the World

Introduction

A login and registration system is the backbone of any web application that requires user‑specific data or personalized experiences. In the PHP‑MySQL ecosystem, this system handles user authentication, account creation, and session management while safeguarding credentials against common attacks. Building a robust solution not only protects your users but also boosts trust, conversion rates, and SEO rankings—search engines favor sites that provide secure, reliable user interactions.


Core Concepts

Concept Why It Matters Key PHP/MySQL Implementation
Authentication Verifies a user’s identity before granting access. password_verify() against a hashed password stored in MySQL.
Password Hashing Prevents plain‑text password leaks. password_hash($pwd, PASSWORD_BCRYPT) with a cost factor.
Sessions Maintains a logged‑in state across pages. session_start(); $_SESSION['user_id'] = $id;
Prepared Statements Defends against SQL injection. $stmt = $pdo->prepare('SELECT * FROM users WHERE email = ?');
Input Validation & Sanitization Stops malformed data from entering the database. filter_var($email, FILTER_VALIDATE_EMAIL);
CSRF Protection Stops unauthorized form submissions. Hidden token <input type="hidden" name="csrf" value="<?= $token ?>">.
Account Verification Confirms ownership of the email address. Send a unique token link via mail() and store it in a verification_tokens table.
Password Reset Allows users to recover access securely. Generate a time‑limited token, store it, and validate on reset.

Real‑World Use Cases

  • E‑commerce platforms – Store customer profiles, order histories, and loyalty points.
  • SaaS dashboards – Restrict premium features to subscribed accounts.
  • Community forums – Enable posting, private messaging, and reputation systems.
  • Admin panels – Protect configuration pages and analytics with role‑based access.
  • Mobile API back‑ends – Provide token‑based authentication for native apps (often extended with JWT after the basic login).

Each scenario demands the same core security pillars but may add role management, multi‑factor authentication, or third‑party OAuth integrations.


Getting Started Guide

1. Prerequisites

  • PHP 8.0+ with PDO extension enabled.
  • MySQL 5.7+ (or MariaDB).
  • A web server (Apache/Nginx) with HTTPS configured.

2. Database Schema

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

CREATE TABLE verification_tokens (
    user_id INT UNSIGNED,
    token CHAR(64) NOT NULL,
    expires_at DATETIME NOT NULL,
    PRIMARY KEY (user_id, token),
    FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
);

3. Configuration (config.php)

<?php
declare(strict_types=1);
session_start();

define('DB_HOST', 'localhost');
define('DB_NAME', 'auth_demo');
define('DB_USER', 'root');
define('DB_PASS', '');

try {
    $pdo = new PDO(
        "mysql:host=" . DB_HOST . ";dbname=" . DB_NAME,
        DB_USER,
        DB_PASS,
        [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]
    );
} catch (PDOException $e) {
    die('Database connection failed: ' . $e->getMessage());
}
?>

4. Registration Script (register.php)

<?php
require 'config.php';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // 1️⃣ Sanitize & validate input
    $username = trim($_POST['username']);
    $email    = filter_var($_POST['email'], FILTER_VALIDATE_EMAIL);
    $pwd      = $_POST['password'];
    $pwd2     = $_POST['confirm_password'];

    if (!$email || $pwd !== $pwd2) {
        $error = 'Invalid input.';
    } else {
        // 2️⃣ Check for existing user
        $stmt = $pdo->prepare('SELECT id FROM users WHERE email = ? OR username = ?');
        $stmt->execute([$email, $username]);
        if ($stmt->fetch()) {
            $error = 'User already exists.';
        } else {
            // 3️⃣ Hash password
            $hash = password_hash($pwd, PASSWORD_BCRYPT);

            // 4️⃣ Insert user (unverified)
            $stmt = $pdo->prepare('INSERT INTO users (username,email,password) VALUES (?,?,?)');
            $stmt->execute([$username, $email, $hash]);
            $userId = $pdo->lastInsertId();

            // 5️⃣ Generate verification token
            $token = bin2hex(random_bytes(32));
            $expires = date('Y-m-d H:i:s', strtotime('+24 hours'));

            $stmt = $pdo->prepare('INSERT INTO verification_tokens (user_id, token, expires_at) VALUES (?,?,?)');
            $stmt->execute([$userId, $token, $expires]);

            // 6️⃣ Send verification email (simplified)
            $link = "https://yourdomain.com/verify.php?token=$token&uid=$userId";
            mail($email, 'Verify your account', "Click: $link");

            $success = 'Registration successful! Check your email to verify the account.';
        }
    }
}
?>
<!-- HTML form omitted for brevity -->

5. Email Verification (verify.php)

<?php
require 'config.php';

$uid   = (int)$_GET['uid'] ?? 0;
$token = $_GET['token'] ?? '';

$stmt = $pdo->prepare('SELECT expires_at FROM verification_tokens WHERE user_id = ? AND token = ?');
$stmt->execute([$uid, $token]);
$row = $stmt->fetch();

if ($row && strtotime($row['expires_at']) > time()) {
    // Activate account
    $pdo->prepare('UPDATE users SET is_verified = 1 WHERE id = ?')->execute([$uid]);
    $pdo->prepare('DELETE FROM verification_tokens WHERE user_id = ?')->execute([$uid]);
    echo 'Account verified! You may now log in.';
} else {
    echo 'Invalid or expired token.';
}
?>

6. Login Script (login.php)


<?php
require 'config.php';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $email = filter_var($_POST['email'], FILTER_VALIDATE_EMAIL);
    $pwd   = $_POST['password'];

    $stmt = $pdo->prepare('SELECT id, password, is_verified FROM users WHERE email = ?');
    $stmt->execute([$email]);
    $user = $stmt->fetch(PDO::FETCH_ASSOC);

    if ($user && password_verify($pwd, $user['password'])) {
        if (!$user['is_verified']) {
            $error = 'Please verify your email first.';
        } else {
            // Regenerate session ID to prevent fixation
            session_regenerate_id(true);
            $_SESSION['

Other Recent Posts

Step By Step Guide To Learn Full Stack Development Explained for Beginners

Explore our complete guide to step by step guide to learn full stack development. Learn what it is, how it works, and its real-world applications in technology, AI, and IT.

Read More about Step By Step Guide To Learn Full Stack Development Explained for Beginners

The Ultimate Guide to Understanding How To Build Ai Chatbot With Python

Explore our complete guide to how to build ai chatbot with python. Learn what it is, how it works, and its real-world applications in technology, AI, and IT.

Read More about The Ultimate Guide to Understanding How To Build Ai Chatbot With Python

How To Use Huggingface Transformers In Python: Key Concepts and Applications

A beginner-friendly explanation of how to use huggingface transformers in python. Understand the key principles and see examples of how this technology is used today.

Read More about How To Use Huggingface Transformers In Python: Key Concepts and Applications

How Simple Api Projects For Beginners is Changing the World

Unlock the power of simple api projects for beginners. Our comprehensive article provides expert insights, practical use-cases, and the latest trends.

Read More about How Simple Api Projects For Beginners is Changing the World

Ai Vs Machine Learning Vs Deep Learning Explained: A Complete Guide for 2025

A beginner-friendly explanation of ai vs machine learning vs deep learning explained. Understand the key principles and see examples of how this technology is used today.

Read More about Ai Vs Machine Learning Vs Deep Learning Explained: A Complete Guide for 2025

How Python Mini Projects For Beginners With Source Code is Changing the World

Explore our complete guide to python mini projects for beginners with source code. Learn what it is, how it works, and its real-world applications in technology, AI, and IT.

Read More about How Python Mini Projects For Beginners With Source Code is Changing the World