Sometimes it is necessary to check if a mail is valid when a user is trying to register a new account on your website to avoid abuse. In addition to the format check, one more safety measure to take is to check if the email domain is a commonly used one to avoid some abuse. In this article I will illustrate how to do it using PHP.
Firstly, implement a utility class for mail addresses check.
<?php class Check { // public static function isEmailLegal($email) { return filter_var($email, FILTER_VALIDATE_EMAIL) && strlen($email) <= 32; } public static function isEmailMaiDomainCommon($email) { list($userName, $mailDomain) = explode("@", $email); $commonDomainList = array("gmail.com", "qq.com", "163.com", "yahoo.com", "hotmail.com", "outlook.com", "yeah.net", "live.com", "foxmail.com"); return in_array($mailDomain, $commonDomainList); } }
Then when checking if a mail is legal
// check email format if (!Check::isEmailLegal($email)) { $res['ret'] = 0; $res['msg'] = 'Illegal Mail'; return $response->getBody()->write(json_encode($res)); } // check mail domain if(!Check::isEmailMaiDomainCommon($email)) { $res['ret'] = 0; $res['msg'] = 'The mail domain is too unique!'; return $response->getBody()->write(json_encode($res)); }
Basically, it checks if a mail domain is inside a safe list, one like the commonDomainList in the above example.