I need to write a function for a project i\'m working on for fun, where we\'re making a site only accessible to students, staff, and alumni at an institution.
Let\'s
You could always do something like this:
$good_domains = array('school.edu'); //in the future, just add to this array for more schools
$email = "user@school.edu"; //your user's email
$matches = array();
preg_match("/^(.+)@([^\(\);:,<>]+\.[a-zA-Z]+)/", $email, &$matches); //validates the email and gathers information about it simultaneously
//should return ['user@mail.com', 'user', 'mail.com']
$domain = $matches[3];
if(in_array($domain, $goood_domains))
{
//success! your user is from school.edu!
}
else
{
//oh no! an imposter!
}
If you are using Laravel:
Str::endsWith($email, '@foo.bar.edu'); // bool
I'd just do this:
$acceptedDomains = array('site1.edu', 'site2.edu');
if(in_array(substr($email, strrpos($email, '@') + 1), $acceptedDomains))
{
// Email is from a domain in $acceptedDomains
}
The 'whatever.edu' portion will always be after the @
. So, all you need to do is:
@
in the string. (In a normal email, there will only be one, but that doesn't matter here.)@
. This will be the domain name.in_array()
to compare the domain name against a list of accepted domains in $acceptedDomains
.Note that if you want to also accept emails from email@any.subdomain.site1.edu
, you'd have to do just a little more, but that may or may not be applicable here. I'm also assuming you've validated that the email addresses are well formed before doing this.
There's a few ways to accomplish this, here's one:
// Make sure we have input
// Remove extra white space if we do
$email = isset($_POST['email']) ? trim($_POST['email']) : null;
// List of allowed domains
$allowed = [
'school.edu',
'school2.edu',
'school3.edu'
];
// Make sure the address is valid
if (filter_var($email, FILTER_VALIDATE_EMAIL))
{
// Separate string by @ characters (there should be only one)
$parts = explode('@', $email);
// Remove and return the last part, which should be the domain
$domain = array_pop($parts);
// Check if the domain is in our list
if ( ! in_array($domain, $allowed))
{
// Not allowed
}
}
Simple and Single line:
list($name, $domain) = explode('@', $email);
You can use regex:
if(preg_match('/^\w+@school\.edu$/i', $source_string) > 0)
//valid
Now proceed to tear me apart in the comments because there's some crazy email address feature I didn't account for :)