'How to validate a school email domain with php

I am trying to validate a school email ending in .ac.uk in php. I want to be able to check if the email submitted in the form has ended in .ac.uk in PHP

My PHP code:

if (empty ($_POST["uni_email"])) {
$emailErr2 = "University email is required";
} else {
  $uemail = $_POST["uni_email"];
  if ( !filter_var($uemail, FILTER_VALIDATE_EMAIL)) {
   $emailErr3 = "Invalid email format";
   echo $emailErr3;
    
}
if (!preg_match('/ac.uk$/', $email)) {

  $emailErr3 = "Invalid university email format";
  echo $emailErr3;

}

I've seen ways using the checkdnsrr() function to check the domain but I'm not sure if that's the correct way as .ac.uk is not a domain and I want to ensure that it checks out for the .ac.uk after the domain. So a valid email would be [email protected].



Solution 1:[1]

Instead of that last preg_match, you can do it in non-regex way:

if(!endsWith($email, '.ac.uk'))
{
   // here handle your error, email doesn't end with .ac.uk.
   $emailErr3 = "Invalid university email format";
   echo $emailErr3;
}

function endsWith( $haystack, $needle ) {
    $length = strlen( $needle );
    if( !$length ) {
        return true;
    }
    return substr( $haystack, -$length ) === $needle;
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 LambdaTheDev