Kevin Aartsen Kevin Aartsen - 6 months ago 25
PHP Question

Email validation not working accordingly

i made a form where people can enter their email.
The problem is they can now add everything they want inside the field, I want them to only be able to enter a valid email. i found this piece of code on the internet.

if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$emailErr = "Invalid email format";
}


And implemented it in my PHP mail sending code:

<?php

$email = $_POST['subscribefield'];

if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$emailErr = "Invalid email format";
}


$to = "test@hotmail.com";
$subject = "Abonee voor de nieuwsbrief";
$body = "$email \n Heeft zich aangemeld voor de nieuwsbrief";

mail($to, $subject, $body);

echo "your mail was sent";
?>


Still doesn't work. What did i do wrong?

Thanks in advance,

Kevin

Answer

You don't have if statement anywhere that would check $emailErr. Such as:

if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
  $emailErr = "Invalid email format"; 
}

if( isset($emailErr) === FALSE )
{
    $to = "test@hotmail.com";
    $subject = "Abonee voor de nieuwsbrief";
    $body = "$email \n Heeft zich aangemeld voor de nieuwsbrief";

    mail($to, $subject, $body);

    echo "your mail was sent";
}

Or simply

if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
  echo "Invalid email format";
  die();
}