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 say the schools website is: school.edu.
I'm having trouble writing a php filter that checks that the submitted email address has the domain of "school.edu"
I'll use an example. Dude #1 has an email of [email protected] and Dude #2 has an email at [email protected]. I want to make sure that Dude 1 gets an error message, and Dude #2 has a successful registration.
That's the gist of what I'm trying to do. In the near future the site will allow registration by another two locale schools: school2.edu and school3.edu. I will then need the checker to check the email against a small list (maybe an array?) of domains to verify that the email is of a domain name on the list.
PHP - Validate E-mail The easiest and safest way to check whether an email address is well-formed is to use PHP's filter_var() function.
An email domain is the part of an email address that comes after the @ symbol. For personal emails, it is most often gmail.com, outlook.com or yahoo.com. However, in a business context, companies are almost certain to have their own email domain.
To put it simply, the part of your email address behind the @ symbol – in other words, @mail.com, @email.com, @usa.com – is called a domain. It functions like a virtual street name that lets your email get delivered to the right address. Each email domain is associated with a specific mail server or servers.
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 } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With