r/PHPhelp • u/uuuuunacceptable • May 05 '25
Solved Partial match from array, rather than in_array
Context:
Retrofitting a signup check against a list of allowed domain names. `$emailDomain` is the user's email address with the name and @ symbol stripped, leaving only the domain name behind.
However, it's become apparent that in the users signing up for the service, a lot use subdomains of domain names already in the allowlist.
So I created a second version of the approved domains array, but all entries prefixed with `.` - so I want to check, secondarily, if `$emailDomain` contains any of the entries from that array, and that's where I'm stuck.
(There's a second aspect where they could be on a list of individually allowed email addresses - just to explain the second part of the check below).
My current code (which is a negative check, i.e. don't let them proceed if this is true), is:
if(!in_array($emailDomain, $allowedDomains) && !in_array($email, $allowedEmails)) $errors[] = "Nope, halt here".For the sake of a simplified example: given the $emailDomain `foo.google.com` and the array `['.google.com','.microsoft.com','.yahoo.au']` - how do I check if any of the items in the array are contained within the $emailDomain?
Thanks
1
u/uuuuunacceptable May 05 '25
My solution has ended up being, based on https://www.reddit.com/r/PHP/comments/7dn4yp/php_code_golf_detect_if_string_contains_an/ :
Thanks all for your input!
1
u/colshrapnel May 05 '25
I don't get it. Where did you see a email address like user@foo.google.com?
1
u/allen_jb May 05 '25
One problem you'll want to avoid here is partial matches.
eg. If
example.comis in your allow list, you wantsubdomain.example.comto match, but you don't wantnotreallyexample.comto match.Another potential issue to watch out for is TLDs of more than one level - eg
.co.uk. There's no simple way to deal with these. If you really care about them you have to use the public suffix listA simple solution (that ignores the TLDs with multiple levels) would be to split the email domain on
.and create a list of (sub)domains to check against the whitelist: https://3v4l.org/qqLet(Obviously you could combine these 2 loops - I've left them separate here for demonstration purposes. Plus I would probably have the list to check generated by a separate method / function)
1
u/stonedlogic May 05 '25
you could use str_contains function depending on your PHP version.
1
u/colshrapnel May 05 '25 edited May 05 '25
using some new 8.4 function