phpformsemail

Accept Only GMail Emails In Forms


I have form here and I would like to accept only GMail Email address.

This is the part of the form.

function is_email($email){
   $x = '\d\w!\#\$%&\'*+\-/=?\^_`{|}~';    //just for clarity

   return count($email = explode('@', $email, 3)) == 2
       && strlen($email[0]) < 65
       && strlen($email[1]) < 256
       && preg_match("#^[$x]+(\.?([$x]+\.)*[$x]+)?$#", $email[0])
       && preg_match('#^(([a-z0-9]+-*)?[a-z0-9]+\.)+[a-z]{2,6}.?$#', $email[1]);
}


    elseif (!is_email($Email)) {
        $resultado = "Please, use a valid email address. (Required for account activation)<br><br> <a href=javascript:history.go(-1)>Go back!</a>";
    }

I already tried "explode ('@gmail.com', $email, 3)) == 2" but get me some error instead.


Solution

  • You just need to check if the string ends with "@gmail.com":

    /**
     * Check if an email is a Gmail address
     * @param string $email The email address to check
     * @return boolean
     */
    function isGmail($email) {
        $email = trim($email); // in case there's any whitespace
    
        return mb_substr($email, -10) === '@gmail.com';
    }
    

    I'm using mb_substr here but alternatively you can use substr.