2026-07-15

How to validate email id and password & confirm password in php

Stefan Bogdanescu

Stefan Bogdanescu

Founder & Senior Architect

How to validate email id and password & confirm password in php

Mastering Form Validation in PHP: Securely Handling Emails and Passwords

As a senior developer, I often encounter beginners who are eager to build applications but get stuck on the fundamental aspects of security and data validation. Dealing with user input—especially sensitive data like emails and passwords—is arguably the most critical step in building any application. If you skip proper validation, you open yourself up to serious vulnerabilities.

This post will walk you through exactly how to properly validate email uniqueness and password confirmation in PHP, moving beyond simple checks to implement secure, industry-standard practices. We will address the issues present in your provided code and guide you towards building robust registration flows.

The Philosophy of Input Validation: Client vs. Server

Before diving into the code, it is crucial to understand that validation must happen in two places:

  1. Client-Side Validation (UX): This involves using HTML5 attributes (type="email", required) and JavaScript to give immediate feedback to the user. This improves the user experience by catching obvious errors instantly.
  2. Server-Side Validation (Security): This is the most important step. Never trust the client-side input. All validation logic must be repeated on the server side using PHP to ensure data integrity and security, regardless of what the client tries to submit.

Server-Side Logic for Email and Password Checks

Your request involves two primary checks: ensuring the email is unique and confirming that the password matches the confirmation field. These checks happen after the form data has been submitted via the POST method.

1. Validating Email Uniqueness

To check if an email already exists, you must query your database before attempting to insert a new record.

The Flaw in Using Legacy Functions: Your provided code uses the deprecated mysql_* functions. These functions are highly insecure and have been removed from modern PHP versions. For security and maintainability, we must use PDO (PHP Data Objects) with prepared statements instead. This prevents SQL Injection attacks, a massive security risk.

Here is the conceptual flow using secure practices:

// Assume you have established a PDO connection ($pdo)
$email = $_POST['email'];

// Step 1: Check if the email exists in the database
$stmt = $pdo->prepare("SELECT COUNT(*) FROM register WHERE email = ?");
$stmt->execute([$email]);
$count = $stmt->fetchColumn();

if ($count > 0) {
    // Error: Email already registered
    $error_message = "This email address is already in use.";
} else {
    // Proceed to insertion if unique
    // ... insert logic here ...
}

2. Validating Password Confirmation

Checking if the password and confirm password fields match is a simple but essential string comparison. This must be done immediately upon form submission.

$password = $_POST['password'];
$cpassword = $_POST['confirmpassword'];

if ($password !== $cpassword) {
    // Error: Passwords do not match
    $error_message = "Passwords do not match. Please try again.";
} else {
    // Passwords match, proceed with insertion
}

Implementing Secure Password Storage (Crucial Step!)

A major oversight in the code you provided is the handling of passwords. Never store passwords in plain text. If a hacker gains access to your database, they will immediately have all user passwords.

You must use PHP’s built-in password_hash() function for storing passwords securely and password_verify() for checking them during login. This is fundamental security practice that any modern application, including those following principles found in frameworks like Laravel, demands.

Refactored Example using Modern PHP (PDO)

Here is how you would structure the validation logic securely, avoiding deprecated functions and ensuring data integrity:

<?php
// 1. Setup Database Connection (Using PDO for security!)
// $pdo = new PDO('mysql:host=localhost;dbname=yourdb', 'user', 'password');

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $email = trim($_POST['email']);
    $password = $_POST['password'];
    $cpassword = $_POST['confirmpassword'];
    $errors = [];

    // --- Validation Check 1: Email Uniqueness ---
    if (empty($email)) {
        $errors[] = "Email is required.";
    } else {
        // Securely check for existing email using prepared statements
        $stmt = $pdo->prepare("SELECT COUNT(*) FROM register WHERE email = ?");
        $stmt->execute([$email]);
        if ($stmt->fetchColumn() > 0) {
            $errors[] = "This email is already registered.";
        }
    }

    // --- Validation Check 2: Password Match ---
    if ($password !== $cpassword) {
        $errors[] = "Passwords do not match. Please ensure they are identical.";
    }

    // If no errors were found, proceed with insertion (and hash the password!)
    if (empty($errors)) {
        // Hash the password securely before saving it!
        $hashed_password = password_hash($password, PASSWORD_DEFAULT); 
        
        // Prepare and execute INSERT statement here using PDO prepared statements...
        // ... success message ...
    } else {
        // Display all collected errors to the user
        echo "There were errors in your submission: " . implode("<br>", $errors);
    }
}
?>

Conclusion

Validating user input is not an optional step; it is the foundation of application security. By moving away from outdated methods like mysql_* and embracing modern techniques like PDO prepared statements, you protect your application from SQL injection. Furthermore, by implementing strict server-side checks for uniqueness and matching passwords, you ensure data integrity. Always prioritize security—remember that handling sensitive information like passwords correctly is the hallmark of a professional developer. For comprehensive architectural guidance on building secure systems, exploring resources like those offered by Laravel can provide invaluable insights into these best practices.

Note: Blog content is currently available in English.

Tags:

Enhance your marketing setup with your own email marketing platform.

Join the growing number of SaaS platforms using Laravel Mail to offer email marketing solutions to their customers.