How to Validate and Sanitize Email in PHP Easily
In PHP, you can validate an email using
filter_var with FILTER_VALIDATE_EMAIL to check if the email format is correct. To sanitize an email, use filter_var with FILTER_SANITIZE_EMAIL which removes unwanted characters.Syntax
Use filter_var function with two main filters for emails:
FILTER_VALIDATE_EMAIL: Checks if the email is valid.FILTER_SANITIZE_EMAIL: Removes illegal characters from the email.
php
$sanitizedEmail = filter_var($email, FILTER_SANITIZE_EMAIL); $isValid = filter_var($sanitizedEmail, FILTER_VALIDATE_EMAIL);
Example
This example shows how to sanitize and then validate an email address in PHP. It prints if the email is valid or not after cleaning it.
php
<?php $email = "john..doe@@example..com "; // Sanitize the email $sanitizedEmail = filter_var($email, FILTER_SANITIZE_EMAIL); // Validate the sanitized email if (filter_var($sanitizedEmail, FILTER_VALIDATE_EMAIL)) { echo "Valid email: " . $sanitizedEmail; } else { echo "Invalid email."; } ?>
Output
Invalid email.
Common Pitfalls
Common mistakes include validating the raw input without sanitizing, which can cause false negatives, or sanitizing but not validating, which may allow invalid emails. Also, relying only on regex can be error-prone compared to filter_var.
php
<?php // Wrong: Validate without sanitizing $email = "john..doe@@example..com "; if (filter_var($email, FILTER_VALIDATE_EMAIL)) { echo "Valid email."; } else { echo "Invalid email."; } // Right: Sanitize first, then validate $sanitizedEmail = filter_var($email, FILTER_SANITIZE_EMAIL); if (filter_var($sanitizedEmail, FILTER_VALIDATE_EMAIL)) { echo "Valid email after sanitizing."; } else { echo "Invalid email after sanitizing."; } ?>
Output
Invalid email.Invalid email after sanitizing.
Quick Reference
Summary tips for email validation and sanitization in PHP:
- Always sanitize input before validating.
- Use
FILTER_SANITIZE_EMAILto clean the email. - Use
FILTER_VALIDATE_EMAILto check format correctness. - Do not rely solely on regex for email validation.
Key Takeaways
Always sanitize email input with FILTER_SANITIZE_EMAIL before validation.
Use FILTER_VALIDATE_EMAIL with filter_var to check if an email is valid.
Avoid validating raw user input without sanitizing first.
Do not rely only on regular expressions for email validation in PHP.
filter_var provides a simple and reliable way to handle email validation and sanitization.