Validate an Email Address in PHP
Learn how to validate email addresses using built-in functions like
filter_var()
and regular expressions in PHP.
๐ง Why Validate Emails?
Email validation is crucial in web development to ensure that the data submitted by users is accurate, correctly formatted, and usable. PHP provides both simple and advanced methods for validating email addresses.
โ
Using filter_var()
(Recommended)
The easiest and safest way to validate an email in PHP is with
filter_var()
.
<?php
$email = "[email protected]";
if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
echo "Valid email.";
} else {
echo "Invalid email.";
}
?>
Pros: Fast, reliable, and built into PHP.
๐ Using Regular Expressions (Regex)
For custom validations or specific formatting rules, you may use a regex pattern.
<?php
$email = "[email protected]";
$pattern = "/^[\w.-]+@[\w.-]+\.\w+$/";
if (preg_match($pattern, $email)) {
echo "Valid email (via regex).";
} else {
echo "Invalid email.";
}
?>
Note: Regex can be overly strict or lenient. Use carefully.
๐งผ Sanitize Before Validating
Always sanitize email input before validation to remove illegal characters:
<?php
$raw_email = " [email protected] ";
$sanitized = filter_var(trim($raw_email), FILTER_SANITIZE_EMAIL);
?>
๐ Example: Validating Email from a Form
<form method="post">
<input type="email" name="email" required>
<button type="submit">Submit</button>
</form>
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$email = filter_var(trim($_POST["email"]), FILTER_SANITIZE_EMAIL);
if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
echo "Thank you, valid email: $email";
} else {
echo "Please enter a valid email address.";
}
}
?>
โ Best Practices
- Always sanitize user input before validating
- Use
filter_var()
over regex when possible - Validate both client-side (HTML5) and server-side (PHP)
- Don't rely only on JavaScript for validation