1

I was playing around with filter_var to validate emails:

$email = "test@test.com"; 

if( filter_var( $email, FILTER_VALIDATE_EMAIL ) ){

    echo "{Valid Email";

}else{

    echo "Invalid Email";

}

That returns Valid Email.

But when I tried special characters like . $ # * ? & ! ^ ~ / ' - _ @ % {} | = + at the local part, Like :

$email = "te?st@test.com";
$email = "te/st@test.com";
$email = "te'st@test.com";
$email = "te}st@test.com";
$email = "te|st@test.com";
$email = "te=st@test.com";

That would return Valid Email too.

It's not accepting characters like <> [] ,.

But if I use $:

$email = "te$st@test.com";

That would return Valid Email, But also NOTICE Undefined variable: st

So should I use it to validate email addresses, Before inserting them to the DB?

Or I should use a custom Regular Expression?

John Conde
  • 217,595
  • 99
  • 455
  • 496
  • 1
    The official RFC for emails is quite complex, lengthy, and incredibly inclusive of many weird things. Check out https://en.wikipedia.org/wiki/Email_address#Examples for other valid emails. [In short, do not attempt this with regex because it's already been done and you probably don't know what you are doing.](https://stackoverflow.com/a/1903368/2191572) In your example `te$st@test.com` is interpolated as `te@test.com` because `$st` is undefined so a null (empty) is used in its place and you get a warning. – MonkeyZeus Aug 15 '18 at 12:46

1 Answers1

4

When using double quoted strings, the $ character is seen as the beginning of a variable name. So $stlooks like a variable and PHP tries to interpolate it. This is easily resolved by using single quotes which does not interpolate variables in strings.

$email = 'te$st@test.com';

See the PHP documentation for strings to learn more about this as it is an important part of PHP development.

John Conde
  • 217,595
  • 99
  • 455
  • 496
  • You are right, But what if I'm checking the `$_POST['email']`, Would I face that issue too? –  Aug 15 '18 at 14:19
  • 1
    No, because PHP would be looking at the literal value of that variable like it was in some quotes and would not try to interpolate variables within it – John Conde Aug 15 '18 at 15:15