Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should I use filter_var to validate email?

Tags:

I have a class that validates every input before I send it to the database layer. Note that my problem is not about escaping or anything. My database layer will handle the SQL Injection problem. All I want to do is validate if the email is valid or not because later that email might be used as a 'send to'. For instance, the user will recover access to his account through a link sent to the e-mail. I read a lot about filter_var and there are a bunch of people being against it and other bunch being in favor. Keeping the focus on 'I just want to validate email and not filter it for database or for html or XSS or whatever', is there a problem in using filter_var?

like image 396
Marco Aurélio Deleu Avatar asked Oct 22 '13 15:10

Marco Aurélio Deleu


People also ask

Which function is used to validate email?

The easiest and safest way to check whether an email address is well-formed is to use PHP's filter_var() function.

What does filter_ validate_ email do?

Definition and Usage The FILTER_VALIDATE_EMAIL filter validates an e-mail address.

What is Filter_var?

The filter_var() function filters a variable with the specified filter.

How can I check email is valid in laravel?

All you need to do is change the validate method as follows: public function save(Request $request) { $validated = $request->validate([ email=> 'email:rfc,dns' ]); //If email passes validation, method will continue here. } This allows us to apply both DNS and RFC validation to our email addresses.


2 Answers

Yes, you should.

Using the standard library validation instead of a home brew one has multiple benefits:

  1. Many eyeballs already seen the code (well, at least two) you will be using, hopefully with experience in email validation even before it's merged into a release.
  2. It's unit tested.
  3. Other people will use the same check and report bugs and you get these fixes for free on php updates.

However checking the format of an email address is only the first line of defense, if you really want to know that it's real or not, you will have to send a message to it.

like image 155
complex857 Avatar answered Sep 28 '22 19:09

complex857


Yes, you should use filter_var and this is how you can incorporate it :

if( filter_var( $email ,FILTER_VALIDATE_EMAIL ) ) {     /*      * Rest of your code      */ } 
like image 26
absfrm Avatar answered Sep 28 '22 18:09

absfrm