CodexBloom - Programming Q&A Platform

advanced patterns when using PHP's filter_var with FILTER_VALIDATE_EMAIL for custom domain validation

👀 Views: 144 đŸ’Ŧ Answers: 1 📅 Created: 2025-06-12
php validation filter_var

After trying multiple solutions online, I still can't figure this out. I'm collaborating on a project where I'm working with an scenario when trying to validate email addresses that are supposed to belong to a specific set of custom domains using PHP's `filter_var` function with `FILTER_VALIDATE_EMAIL`... The question arises when I combine the `filter_var` function with a custom validation for domain names. My goal is to only allow emails from the domains 'example.com' and 'test.com'. When I use the following code: ```php $email = 'user@example.com'; $validDomains = ['example.com', 'test.com']; if (filter_var($email, FILTER_VALIDATE_EMAIL) && in_array(substr(strrchr($email, '@'), 1), $validDomains)) { echo 'Valid email'; } else { echo 'Invalid email'; } ``` It works perfectly fine for 'user@example.com', but when I test with 'user@invalid.com', I expect it to output 'Invalid email'. However, I am getting 'Valid email' instead. The same happens when I test with 'user@test.com'; it returns 'Valid email' as expected, but 'user@foo.com' still returns 'Valid email', which is incorrect. I've tried debugging by printing the intermediate steps and confirming that `filter_var` is indeed validating the email format correctly, but the domain check seems to unexpected result in certain cases. I'm using PHP 8.1.0, and I'm not sure if there's something I'm missing in how string manipulation or validation is being handled here. Any suggestions on how to correctly enforce domain validation alongside the email format validation? The project is a web app built with Php. Any ideas how to fix this? This is my first time working with Php 3.11. Thanks, I really appreciate it!