goforphp

Introduction

Every time a user signs up, fills out a contact form, or subscribes to a newsletter, they usually share their email address. But not all email addresses are valid—some are mistyped, some are fake, and some belong to temporary domains. Accepting these invalid emails can create problems like failed deliveries, bounce backs, or spam.

If you’re building any kind of form in PHP, PHP email validation is essential. It ensures you’re collecting real, properly formatted, and useful email addresses.

What Is Email Validation?

Email validation is the process of confirming that an email address:

  • Follows a correct structure (like user@example.com)

  • Is not empty or filled with junk

  • Belongs to a real and working domain

  • (Optional) Isn’t from a disposable or spam domain

PHP gives you several tools to validate emails—some are easy to implement, and others offer more control depending on your needs.


Why PHP Email Validation Matters

Whether you’re a beginner or a pro, email validation should never be skipped. Here’s why:

  • Improves Data Accuracy: Ensures only correctly formatted emails are saved.

  • Reduces Spam & Abuse: Filters out fake or temporary addresses.

  • Enhances Deliverability: Fewer invalid emails means fewer bounce backs.

  • Boosts UX: Provides users with instant feedback if they mistype.

  • Protects Your Brand: Helps keep your sender reputation strong.


Method 1: Using filter_var() (Best for Beginners)

The easiest and most reliable way to validate an email in PHP is by using the built-in filter_var() function.

Example:

php
$email = "user@example.com";

if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
echo "Valid email address.";
} else {
echo "Invalid email address.";
}

Why It Works:

  • ✅ Quick and clean

  • ✅ Checks format accurately

  • ✅ Works in PHP 5.2+

  • ✅ No custom regex needed

If you’re new to PHP or looking for a plug-and-play solution, this is the best way to start.


Method 2: Sanitize Then Validate

Before validating, you should sanitize the email to remove unwanted characters like spaces or HTML tags.

Example:

php
$email = trim($_POST['email']);
$email = filter_var($email, FILTER_SANITIZE_EMAIL);

if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
echo "Clean and valid email.";
} else {
echo "Invalid email input.";
}

Good Practice: Always sanitize user input before validation to avoid injection, formatting errors, or bad data entries.


Method 3: Regex-Based Email Validation (For Custom Rules)

Sometimes you need more control than filter_var() offers. That’s when regular expressions (regex) are helpful.

Example:

php
$email = "user@domain.com";
$pattern = "/^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-z]{2,}$/";

if (preg_match($pattern, $email)) {
echo "Email format is correct.";
} else {
echo "Email format is incorrect.";
}

When to Use:

  • You want to enforce specific rules (e.g., limit to certain domains)

  • You need full control over structure

  • filter_var() is too lenient for your use case

Caution: Regex can block valid emails if not written carefully. Don’t reinvent the wheel—use tested patterns.


Method 4: Check Domain Validity with checkdnsrr()

Valid format doesn’t mean a real domain. To verify that the domain exists and can receive emails, use checkdnsrr().

Example:

php
$email = "info@example.com";
$domain = substr(strrchr($email, "@"), 1);

if (checkdnsrr($domain, "MX")) {
echo "Domain exists.";
} else {
echo "Invalid or inactive domain.";
}

You can combine this with filter_var() for a complete validation check.

Full Example:

php
$email = trim($_POST['email']);
$email = filter_var($email, FILTER_SANITIZE_EMAIL);
$domain = substr(strrchr($email, "@"), 1);

if (filter_var($email, FILTER_VALIDATE_EMAIL) && checkdnsrr($domain, "MX")) {
echo "Email and domain are valid.";
} else {
echo "Please enter a valid email address.";
}


Method 5: Block Disposable Email Providers

Some users use temporary emails from services like mailinator.com or tempmail.com. You can block these to improve the quality of your users.

Example:

php
$disposable_domains = ["mailinator.com", "10minutemail.com", "tempmail.com"];
$domain = substr(strrchr($email, "@"), 1);

if (in_array($domain, $disposable_domains)) {
echo "Disposable email detected.";
}

You can maintain a list of disposable domains and update it regularly to block them effectively.


Building a Full PHP Email Validation Form

Let’s put everything together in a complete form setup.

HTML Form:

html
<form method="POST">
<label>Email:</label>
<input type="email" name="email" required>
<input type="submit" value="Submit">
</form>

PHP Script:

php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$email = trim($_POST['email']);
$email = filter_var($email, FILTER_SANITIZE_EMAIL);
$domain = substr(strrchr($email, "@"), 1);
$disposable_domains = ["mailinator.com", "tempmail.com"];

if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
echo "Invalid email format.";
} elseif (!checkdnsrr($domain, "MX")) {
echo "Email domain doesn't exist.";
} elseif (in_array($domain, $disposable_domains)) {
echo "Please use a personal or business email.";
} else {
echo "Success! Email is valid.";
}
}

This example checks for format, domain existence, and filters out disposable providers—all in one flow.


Bonus Tip: Email Confirmation Links

For important actions (e.g., account signup), don’t just validate the email—confirm it by sending a link or code the user must click. This ensures:

  • The email exists

  • The user owns the email

  • They want to receive your emails

Workflow:

  1. User enters email and submits form

  2. Server stores email + a unique token

  3. Sends an email with confirmation link (https://yourdomain.com/verify?token=abc123)

  4. User clicks link → you mark email as “verified”


Common Mistakes to Avoid

  • ❌ Skipping server-side validation (client-side alone isn’t safe)

  • ❌ Forgetting to sanitize input before checking

  • ❌ Relying only on regex or only on format

  • ❌ Not checking if the domain exists

  • ❌ Not offering helpful error messages


Conclusion

Email validation in PHP is more than just a formality—it’s a crucial step in building trust, delivering reliable service, and maintaining clean data. By combining filter_var(), sanitization, regex, domain checks, and disposable email filtering, you ensure your application collects high-quality information.

Whether you’re a beginner writing your first contact form or a pro building user systems, mastering PHP email validation is a must.

Leave a Reply

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