-3

I have a subscribe using the email button on my website. How do I restrict people subscribing using @gmail, @yahoo emails?

LIST EMAIL ADDRESS

$recipient = "test@test.com";

# SUBJECT (Subscribe/Remove)
$subject = "Subscribe";

# RESULT PAGE
$location = "https://test.com";

## FORM VALUES ##

# SENDER - WE ALSO USE THE RECIPIENT AS SENDER IN THIS SAMPLE
# DON'T INCLUDE UNFILTERED USER INPUT IN THE MAIL HEADER!
$sender = $recipient;
$email = $_POST[‘emailTextBox’];
if (!strpos($email, '@') || !strpos($email, '.')) {
      echo "Email is invalid";
} else {

}


# MAIL BODY
$body .= "Email: ".$_REQUEST['Email']." \n";
# add more fields here if required

## SEND MESSGAE ##

mail( $recipient, $subject, $body, "From: $sender" ) or die ("Mail could not be sent.");

## SHOW RESULT PAGE ##

header( "Location: $location" );
?>
Temani Afif
  • 245,468
  • 26
  • 309
  • 415

1 Answers1

0
// ...
$email = $_POST[‘emailTextBox’];

if (!filter_var($email, FILTER_VALIDATE_EMAIL) || preg_match('/\@(gmail|yahoo|hotmail)/', $email)) {
      // Email is invalid
} else {
    // Email is valid
}
  • filter_var, used with the FILTER_VALIDATE_EMAIL filter, will just checks if the email is actually a valid email
  • preg_match will check now if the email contains the domains you don't want.

If you rather want people to susbcribe ONLY with the specified email, you need to do:

// ...
$email = $_POST[‘emailTextBox’];

if (!filter_var($email, FILTER_VALIDATE_EMAIL) || !preg_match('/\@(gmail|yahoo|hotmail)/', $email)) {
      // Email is invalid
} else {
    // Email is valid
}

Notice the !preg_match()


Usingfilter_var, you may want to consider this question and its answers too.

Prince Dorcis
  • 955
  • 7
  • 7
  • Didn't work this way. Not sure what I did wrong here. $sender = $recipient; $email = $_POST[‘emailTextBox’]; if (!filter_var($email) || preg_match('/\@(gmail|yahoo|hotmail)/', $email)) { echo "Email is invalid"; } else { } if (!strpos($email, '@') || !strpos($email, '.')) { echo "Email is invalid"; } else { } – Kshitiz_hamal Aug 27 '20 at 01:04
  • Yes, sorry, I missed the filter (`FILTER_VALIDATE_EMAIL`) in the `filter_var` function. I've edited the answer, kindly check it. – Prince Dorcis Aug 27 '20 at 08:01
  • This didn't help either. Any other suggestions ? – Kshitiz_hamal Aug 28 '20 at 20:49
  • You want people to susbcribe ONLY with gmail, yahoo or hotmail ? Is it that? – Prince Dorcis Aug 28 '20 at 23:40
  • Exact opposite of that. I want to exclude emails including gmail.com, yahoo.com – Kshitiz_hamal Aug 30 '20 at 02:10
  • So the first answer should work. What response or error are you getting when you use it? – Prince Dorcis Aug 30 '20 at 02:49