jproux
jproux

Reputation: 265

PHP Email Sanitization Filter

I'm trying to figure out why my sanitize filter don't work. When entering an email with incorrect characters, it displays the email with incorrect characters. I would have thought it will strip out incorrect characters and only display the correct email address. Below is my code. What am I doing wrong?

<?php       

if(filter_has_var(INPUT_POST, 'data')){

$email = $_POST['data'];

//Now remove illegal characters
$email = filter_var($email, FILTER_SANITIZE_EMAIL);
echo $email;

}
?>  

<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<input type="text" name="data">
<button type="submit">Submit</button>
</form>

Upvotes: 1

Views: 2489

Answers (4)

Yecodeo
Yecodeo

Reputation: 371

this may help, after sanitizing we need to check if it is a valid mail

<?php       
  if(filter_has_var(INPUT_POST, 'data')){
    $regex = '/^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$/'; 

    $email = $_POST['data'];
    $email = filter_var($email, FILTER_SANITIZE_EMAIL);

    if (preg_match($regex, $email)) {
      echo $email;
    } else {
      echo "invalid email";
    }
  }
?>  

Upvotes: 0

jproux
jproux

Reputation: 265

It seems like only certain types of characters can get sanitized. For instance here are examples of wrong emails that will get sanitized:

(comment)[email protected] - After sanitization: [email protected] "much.more unusual"@example.com - After sanitization: [email protected]

But these for instance will not get sanitized:

sarah{[@gmail}{[.com - After sanitization: sarah{[@gmail}{[.com jp*&@gmail**&.com - After sanitization: jp*&@gmail**&.com

Upvotes: 0

Fom
Fom

Reputation: 515

To me it seems to be working. I would however not want to store a different email than the exact input. If the incoming email adress is incorrect I would return an error message asking the user for a real email adress:

if(filter_has_var(INPUT_POST, 'data')){
  $email = trim($_POST['data']);
  $sanitized = filter_var($email, FILTER_SANITIZE_EMAIL);
  if($email === $sanitized && filter_var($email, FILTER_VALIDATE_EMAIL)) {
    echo "This is a valid email: " . $email;
  } else {
    echo "This is an invalid email: " . $email;
  }
}

Upvotes: 4

AraByte
AraByte

Reputation: 154

I don't know if this is exactly what's you're looking for but just give it a try.

<?php
function filter_mail($string) {
   return preg_replace('/[^A-Za-z0-9.@\-]/', '', $string); // We remove special chars and accept only Alphs&Nums&.&@
}
$mail="jp)(*&@gmail)**&.com";
echo filter_mail($mail); //This will output the desired email
echo "<br>";
echo $mail; //This is how it was !
?>

Upvotes: 0

Related Questions