PHP Validate Email

PHP Validate Email

Last Updated on Feb 15, 2023

Introduction

In a lot of projects you need to validate the emails given by the user. You should make sure the email address has a correct format.

For example user shouldn’t give you fakeemail.com  because this is not an email.

Validate Emails in PHP

There are 2 ways to validate the emails in php:

1- using regular expression

To review how to use regular expressions in php check PHP Regular Expressions.

2- using filters

The second solution is much easier and is the preferred way

Php has a lot of filters that you can validate and sanitize data with. In order to use them we need to use the function filter_var

It takes the value as the first argument and the filter as the second argument

The filter for validating emails is FILTER_VALIDATE_EMAIL

So let’s do it

$email = "test@example.com";
if (!filter_var($email,FILTER_VALIDATE_EMAIL)) {
   echo 'invalid email';
} else {
   echo 'email is correct';
}
// email is correct

And with invalid emails:

$email = "testexample.com";
if (!filter_var($email,FILTER_VALIDATE_EMAIL)) {
   echo 'invalid email';
} else {
   echo 'email is correct';
}
// invalid email

Conclusion

Now you know about validating emails in PHP.

I recommend you to open a PHP files and try to validate different types of emails. see which one is correct and which one is not.

If you have any suggestions, questions, or opinions, please contact me. I’m looking forward to hearing from you!

Key takeaways

  • validate email in php
  • filters in php
  • FILTER_VALIDATE_EMAIL

Category: programming

Tags: #php

Join the Newsletter

Subscribe to get my latest content by email.

I won't send you spam. Unsubscribe at any time.

Related Posts

Courses