PHP Email Verification Script using PDO Extension

PHP Email Verification Script using PDO Extension

Here is a step-by-step guide for creating a PHP email verification system using the PDO extension for secure database interactions.

1. Database Setup

Create a table to store user information, including a field for email verification.

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

2. Registration Script

Create a script (register.php) to handle user registration and send a verification email.

register.php:

<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $username = trim($_POST['username']);
    $email = trim($_POST['email']);
    $password = trim($_POST['password']);

    if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
        echo "Invalid email format.";
        exit;
    }

    // Generate a hashed password and verification code
    $hashedPassword = password_hash($password, PASSWORD_BCRYPT);
    $verificationCode = bin2hex(random_bytes(16)); // Unique verification code

    // Database connection
    $host = 'localhost';
    $db = 'your_database_name';
    $user = 'your_username';
    $pass = 'your_password';

    try {
        $pdo = new PDO("mysql:host=$host;dbname=$db", $user, $pass);
        $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

        // Insert user data into the database
        $stmt = $pdo->prepare("INSERT INTO users (username, email, password, verification_code) VALUES (:username, :email, :password, :verification_code)");
        $stmt->execute([
            ':username' => $username,
            ':email' => $email,
            ':password' => $hashedPassword,
            ':verification_code' => $verificationCode
        ]);

        // Send verification email
        $subject = "Verify Your Email";
        $message = "Click the link below to verify your email:\n\n";
        $message .= "http://yourdomain.com/verify.php?code=$verificationCode";
        $headers = "From: no-reply@yourdomain.com";

        if (mail($email, $subject, $message, $headers)) {
            echo "Registration successful. Check your email for verification.";
        } else {
            echo "Failed to send verification email.";
        }
    } catch (PDOException $e) {
        echo "Error: " . $e->getMessage();
    }
}
?>
PHP

3. Verification Script

Create a script (verify.php) to handle email verification.

verify.php:

<?php
if (isset($_GET['code'])) {
    $verificationCode = $_GET['code'];

    // Database connection
    $host = 'localhost';
    $db = 'your_database_name';
    $user = 'your_username';
    $pass = 'your_password';

    try {
        $pdo = new PDO("mysql:host=$host;dbname=$db", $user, $pass);
        $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

        // Verify the user
        $stmt = $pdo->prepare("SELECT id FROM users WHERE verification_code = :code AND is_verified = 0");
        $stmt->execute([':code' => $verificationCode]);

        if ($stmt->rowCount() > 0) {
            // Update user status to verified
            $updateStmt = $pdo->prepare("UPDATE users SET is_verified = 1 WHERE verification_code = :code");
            $updateStmt->execute([':code' => $verificationCode]);
            echo "Your email has been successfully verified.";
        } else {
            echo "Invalid or already verified code.";
        }
    } catch (PDOException $e) {
        echo "Error: " . $e->getMessage();
    }
} else {
    echo "No verification code provided.";
}
?>
PHP

4. Frontend for Registration

Create a simple form for user registration.

index.html:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Registration</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha1/dist/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
    <div class="container mt-5">
        <h1>User Registration</h1>
        <form action="register.php" method="POST">
            <div class="mb-3">
                <label for="username" class="form-label">Username</label>
                <input type="text" name="username" id="username" class="form-control" required>
            </div>
            <div class="mb-3">
                <label for="email" class="form-label">Email</label>
                <input type="email" name="email" id="email" class="form-control" required>
            </div>
            <div class="mb-3">
                <label for="password" class="form-label">Password</label>
                <input type="password" name="password" id="password" class="form-control" required>
            </div>
            <button type="submit" class="btn btn-primary">Register</button>
        </form>
    </div>
</body>
</html>
PHP

5. How It Works

  1. Registration:
    • Users submit their username, email, and password via the form.
    • The server hashes the password and generates a unique verification code.
    • User data is saved in the database, and a verification email is sent.
  2. Verification:
    • Users click the verification link in their email.
    • The verify.php script checks the verification_code and updates is_verified if valid.

6. Additional Features

  • Secure Emails: Use PHPMailer or similar libraries for more reliable email sending with SMTP.
  • Error Handling: Add error messages for duplicate emails, invalid input, and other edge cases.
  • Password Reset: Extend the system with password reset functionality using similar verification logic.
  • Session Management: Integrate user authentication and session management after successful verification.

This system provides a basic and secure email verification setup using PDO. Let me know if you need enhancements or additional features!

Leave a Reply

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