Email Verification in PHP: Step-by-Step Guide

by Lovepreet 3 minute read 8 views

Implementing email verification in PHP enhances security, reduces fake signups, and ensures user authenticity by validating their email before granting full access to your platform.

Key Points

  • 91% of users trust websites more when email verification is part of the sign-up process.
  • Email verification can reduce fake registrations by up to 80%, improving data integrity significantly.
  • Verified users are 75% more likely to engage and complete their profile post-signup process.

Introduction

Implementing email verification is a crucial part of securing user registration on your web application. This guide walks you through creating a secure email verification system in PHP using PHPMailer and a MySQL database. The flow includes user registration, token generation, email sending, and email verification. If you’re planning custom website development, adding email verification enhances security and user trust.

Folder Structure

Manage your project with the following structure for clarity and maintainability. Whether you're working on a small project or enterprise-level website development services, this structure ensures clean code management.

  • Users.sql: SQL file to create the users table

  • Config.php: DB and mail configuration

  • Register.php: Handles user registration and sends a verification email

  • Mail.php: Send email using PHPMailer

  • Verify.php: Verifies the user's email using a token

Database: users table

Before anything else, you need to create a database table to store user registration details along with a verification token.

                                        CREATE TABLE users (
    id INT AUTO_INCREMENT PRIMARY KEY,
    name VARCHAR(100),
    email VARCHAR(150) UNIQUE,
    password VARCHAR(255),
    is_verified TINYINT(1) DEFAULT 0,
    token VARCHAR(255),
    created_at DATETIME DEFAULT CURRENT_TIMESTAMP
);
                                    

This table stores user credentials, a unique verification token, and an is_verified flag to indicate whether the email has been verified. When you hire PHP developers, ensure they understand the importance of structured and normalized database design like this.

config.php – DB and Email Config

This file contains database connection logic using PDO for secure and efficient interactions with MySQL.

                                        <?php
$host = 'localhost';
$db   = 'your_database';
$user = 'root';
$pass = '';
$charset = 'utf8mb4';

$dsn = "mysql:host=$host;dbname=$db;charset=$charset";
$options = [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION];

try {
    $pdo = new PDO($dsn, $user, $pass, $options);
} catch (\PDOException $e) {
    die("Database connection failed: " . $e->getMessage());
}
?>
                                    

Update these variables with your database credentials. The try-catch block ensures graceful handling of connection errors. If you are partnering with a development company that offers website development services, make sure they use PDO or other secure connection methods.

register.php – Handle Registration

This script handles the registration form submission. It hashes the password, generates a unique token, stores the user in the database, and sends a verification email.

                                        <?php
require 'config.php';
require 'mail.php';

$name = $_POST['name'];
$email = $_POST['email'];
$password = password_hash($_POST['password'], PASSWORD_DEFAULT);
$token = bin2hex(random_bytes(32));

$sql = "INSERT INTO users (name, email, password, token) VALUES (?, ?, ?, ?)";
$stmt = $pdo->prepare($sql);
$stmt->execute([$name, $email, $password, $token]);

// Send email
$verify_link = "http://yourdomain.com/verify.php?token=" . $token;
$message = "Click to verify your email: <a href='$verify_link'>Verify Email</a>";
sendMail($email, "Verify Your Email", $message);

echo "Registration successful. Check your email to verify.";
?>
                                    

The bin2hex(random_bytes(32)) ensures a secure token is generated for each user. When working with teams that offer custom website development, this security layer is often a standard recommendation.

mail.php – Send Email (Using PHPMailer)

This script uses PHPMailer to send emails. It should be installed via Composer:

                                        <?php
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

require 'vendor/autoload.php'; // After `composer require phpmailer/phpmailer`

function sendMail($to, $subject, $body) {
    $mail = new PHPMailer(true);

    try {
        $mail->isSMTP();
        $mail->Host = 'smtp.example.com';
        $mail->SMTPAuth = true;
        $mail->Username = 'your@email.com';
        $mail->Password = 'yourpassword';
        $mail->SMTPSecure = 'tls';
        $mail->Port = 587;

        $mail->setFrom('your@email.com', 'Your App');
        $mail->addAddress($to);
        $mail->isHTML(true);
        $mail->Subject = $subject;
        $mail->Body = $body;

        $mail->send();
        return true;
    } catch (Exception $e) {
        echo "Mail error: {$mail->ErrorInfo}";
        return false;
    }
}
?>
                                    

If you hire PHP developer for your project, ensure they are experienced with PHPMailer for reliable email delivery and configuration.

verify.php – Email Verification

This script handles email verification. It validates the token from the URL, checks the database and updates the user’s verification status if valid.

                                        <?php
require 'config.php';

$token = $_GET['token'] ?? '';

if ($token) {
    $stmt = $pdo->prepare("SELECT * FROM users WHERE token = ?");
    $stmt->execute([$token]);
    $user = $stmt->fetch();

    if ($user && !$user['is_verified']) {
        $pdo->prepare("UPDATE users SET is_verified = 1, token = NULL WHERE id = ?")->execute([$user['id']]);
        echo "Email verified successfully. You can now login.";
    } else {
        echo "Invalid or expired token.";
    }
} else {
    echo "No token provided.";
}
?>
                                    

This script ensures tokens are one-time use by setting them to NULL after successful verification. Many website development companies implement this as a standard feature for secure user onboarding.

Key Benefits:

  • Prevents spam and fake signups

  • Secures your login system

  • Ideal for SaaS, eCommerce, and member-only platforms

  • Essential features when you hire PHP developer teams or freelancers

Need help implementing this? Consider working with experienced developers who offer reliable website development services to ensure scalability, security, and performance.

Final Words

Email verification in PHP adds a powerful layer of security to your user registration process. By verifying users’ email addresses, you ensure that each user is legitimate, reduce the risk of bots, and improve user trust. Whether you're building your project or working with an agency that offers custom website development, this guide gives you everything you need to get started.

Tech Stack & Version

Frontend

  • HTML
  • CSS
  • JavaScript

Backend

  • PHP
  • MySQL
  • PHPMailer

Deployment

  • DigitalOcean
  • Linode
img

©2025Digittrix Infotech Private Limited , All rights reserved.