Search code examples
phppreg-matchemail-validation

Validate an email address in the URL


I will validate this URL with an email address inside.

These two domains are allowed:

All names before the @ in the email address allowed.

When the user inserts another domain after the @, like this:

https://www.example.com/secure/[email protected]

they will get an error. How can I do this?


Solution

  • Try this:

    $email = $_GET['ID']; // remember to filter this!
    $regex = '#\w+@(?<domain>\w+\-?\w+\.\w+)#';
    
    preg_match($regex, $email, $matches);
    $domain = $matches['domain'];
    
    if ($domain !== 'example-test.com') {
        // Unauthorised
    }
    

    See a working example here https://3v4l.org/SorhQ See the regex and tweak if required here https://regex101.com/r/uDzOzm/1/