17
1
0
How To Validate an Email Address in PHP

How To Validate an Email Address in PHP

Published on July 3, 2025 by OBSCountdown Editorial

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
Comments (0)

No comments yet. Be the first to comment!

Leave a Comment
Replying to someone's comment. Cancel
17
1
0
Join Our OBS Community

Loading...

Join Now