Guides
Last updated
July 25, 2025

5 Ways to Implement Email Exists Validation in PHP

Nicolas Rios
Nicolas Rios
Table of Contents:
ON THIS PAGE
Get your free
email validation
 API key now
stars rating
4.8 from 1,863 votes
See why the best developers build on Abstract
START FOR FREE
Thank you! Your submission has been received!
Oops! Something went wrong while submitting the form.
No credit card required

Preventing duplicate accounts by checking if an email already exists is a fundamental part of user registration. We'll explore five ways to handle this in PHP, complete with code snippets. We will also cover the pitfalls of traditional methods and show how Abstract API addresses these issues.

How to Implement Email Exists Validation in PHP

Here are four common methods to check for duplicate emails in your PHP application. Each approach uses a different strategy to query the database or an in-memory store.

Pre-flight SELECT with a Prepared Statement

This method involves a pre-flight query to check if an email exists before an INSERT operation. The code prepares a statement that looks for a match in the users table. It uses fetchColumn() to get a single column, and if a record is found, the function returns a value that indicates a duplicate.

$stmt = $pdo->prepare('SELECT 1 FROM users WHERE email = ? LIMIT 1');
$stmt->execute([$email]);
if ($stmt->fetchColumn()) { 
    // duplicate 
}

Unique Constraint and Exception Handling

This approach relies on the database to enforce uniqueness. First, you apply a UNIQUE constraint to the email column. The application then attempts to insert a new user record without a prior check. If the email exists, the database rejects the INSERT and generates a duplicate-key error.

The code, inside a try...catch block, catches this PDOException. It then inspects the error information to confirm it is a duplicate entry error, like MySQL's error code 1062, a common topic on PHP forums and in other developer communities.

try {
    $stmt = $pdo->prepare('INSERT INTO users(email, pwd) VALUES(?, ?)');
    $stmt->execute([$email, $hash]);
} catch (PDOException $ex) {
    if ($ex->errorInfo[1] == 1062) { 
        // duplicate email 
    }
    else { throw $ex; }
}

Atomic UPSERT Operation

An UPSERT operation combines an INSERT and an UPDATE into a single, atomic command. The database attempts to insert a new row. If this action violates a unique constraint, it performs an UPDATE instead.

The specific syntax varies between database systems. For MySQL, the INSERT ... ON DUPLICATE KEY UPDATE statement is used. After execution, you check the number of affected rows. A rowCount() of 2 in MySQL signals a duplicate.

$stmt = $pdo->prepare('INSERT INTO users(email,pwd) VALUES(?,?) ON DUPLICATE KEY UPDATE id=id');
$stmt->execute([$email, $hash]);
$duplicate = ($stmt->rowCount() == 2);

In-Memory Reservation with Redis

This technique uses an in-memory data store like Redis to manage email reservations. Before any database interaction, the application calls the SETNX command in Redis.

This command attempts to set a key, for example "email:user@example.com", and only succeeds if the key does not already exist. If SETNX returns 0, the email is already reserved.

If it succeeds, the application can proceed with the database write. The key should have a short Time-To-Live (TTL). After a successful commit, the application should delete the key.

Challenges of Traditional Email Validation

These traditional methods introduce significant drawbacks that can compromise data integrity and user experience. The approaches often overlook critical nuances in how email addresses function in the real world.

  • A pre-flight SELECT query creates a race condition. Under load, two requests can see an email as available and then attempt to insert it simultaneously. This makes application-side checks inherently brittle without a database-level unique constraint.
  • Email standards and mail systems handle case sensitivity differently. A simple string comparison or forced lower-case conversion can miss duplicates or create false collisions. This affects database query methods which use simple string comparison, like pre-flight SELECT.
  • Simple string comparisons fail to account for provider-specific alias rules. For example, Gmail ignores dots and plus-labels in addresses. This oversight, common in all database-centric methods, allows users to create multiple accounts that point to the same actual mailbox.
  • Live SMTP checks to verify an address are unreliable. Many mail servers disable verification commands or use catch-all addresses. These probes also vary in response, face interference from greylisting, and can damage your sender reputation.

Validate Emails with Abstract API
Add email already exists validation to your PHP project to prevent duplicate user sign-ups.
Get started for free

How Abstract API Handles Email Already Exists Validation in PHP

Abstract API addresses the core weaknesses of traditional methods through a comprehensive email quality check that runs before your application queries its database.

  • A single HTTPS request returns a complete verdict. This includes syntactic validity, typo suggestions, MX presence, SMTP handshake status, and flags for disposable, free, or role-based accounts.
  • You call the API before you check your user table. If the email deliverability is not “DELIVERABLE” or the quality score is low, you fail fast, so the “already-exists” check only runs on trusted addresses.
  • All logic remains in PHP. This removes the need for shell access, custom regular expressions, or cron jobs that update provider lists.
  • The API has low latency and provides explicit JSON error codes. This allows your application to safely fall back or queue requests when issues arise.
  • A Composer package abstracts cURL, response maps, and retry logic, which reduces integration from days to minutes.

How to Add Abstract API to Your Development Environment

Once you know Abstract’s capabilities, you can add its email validation API to your project with ease. The process involves a few simple steps to prepare your environment.

  • First, get a free API key from the Abstract API dashboard.
  • Next, add the official PHP package to your project with Composer. This command adds the necessary files:
composer require abstractapi/php-email-validation
  • Ensure your application includes the Composer autoloader, which is typically at vendor/autoload.php.
  • Finally, configure the client once with your API key. You can place this code in a bootstrap file or service provider.

Sample Email Validation Implementation with Abstract API

The PHP code below defines a function that uses Abstract API to check an email address. The function calls the verify method and inspects the deliverability and quality_score fields from the response. It only returns true for high-quality, deliverable addresses. This function then acts as a guard before you run your database check for an existent email.

<?php
use Abstractapi\EmailValidation\AbstractEmailValidation;

AbstractEmailValidation::configure(getenv('ABSTRACT_EMAIL_KEY'));

function isEmailAcceptable(string $email): bool
{
    $info = AbstractEmailValidation::verify($email);
    return $info->deliverability === 'DELIVERABLE'
        && (float)$info->quality_score >= 0.90;
}

if (!isEmailAcceptable($candidate)) {
    http_response_code(422);
    exit('Please enter a valid, deliverable email address.');
}
// proceed with unique-email check / insert here

A successful API call for a valid email like janedoe@gmail.com returns a detailed JSON object:

{
  "email": "janedoe@gmail.com",
  "auto_correct": "",
  "deliverability": "DELIVERABLE",
  "quality_score": "0.96",
  "is_valid_format": true,
  "is_free_email": true,
  "is_disposable_email": false,
  "is_role_email": false,
  "is_catchall_email": false,
  "is_mx_found": true,
  "is_smtp_valid": true
}

The response provides a clear verdict through a few key fields:

  • The deliverability and quality_score fields give an immediate go or no-go signal.
  • The auto_correct field suggests a fix for common typos, which allows for silent correction instead of outright failure.
  • The is_disposable_email flag lets you block temporary inboxes, even if they are technically deliverable.

These fields let you pre-filter bad or risky addresses before the uniqueness constraint executes on your database. This process eliminates duplicate-row contention and improves data quality.

Final Thoughts

Traditional email validation is often slow and unreliable, which leads to poor data quality and race conditions. Abstract API replaces these fragile scripts with a single, fast API call to pre-filter bad addresses before they reach your database. Consider an account on Abstract API to get your free API key and reliably validate user emails.

Validate Emails with Abstract API
Stop duplicate sign-ups and maintain a clean user database with our PHP validation guide.
Get started for free

Related Articles

Phone Validation
key now
Get your free
stars rating
4.8 from 1,863 votes
See why the best developers build on Abstract
Thank you! Your submission has been received!
Oops! Something went wrong while submitting the form.
No credit card required