PHP is by far our favorite programming language here at The Barton Organization. As a search engine optimization company in Florida, we use technologies like Laravel, WordPress & Drupal quite frequently.
In this little tutorial, we’re going to talk about how to validate a domain in PHP.
In order to validate a domain, the easiest way is to validate based on whether or not the domain is attached to an IP address or not. You can do regex to match the domain to a pattern, but then you need to keep a list of valid domain patterns. You can check against a database, but then you gotta add more complexity. We’re going to show you a way to validate a domain name by using builtin PHP functions.
We have to do 2 things:
- get the IP address of the domain
- check to make sure the IP is valid
How do I get a domain’s IP address in PHP?
The simplest way to do it is like this:
$domain = 'thebarton.org'; $ip = gethostbyname($domain);
This will return the ipv4 address. At this point in time, it’s safe to use ipv4 instead of ipv6. But we still need to validate the IP to make sure the domain is a valid domain, and not just one that’s sitting out there somewhere pulling in bad data.
How do I validate an IP address?
In PHP, you can do the following:
$ip = '127.0.0.1'; $ip = filter_var($ip, FILTER_VALIDATE_IP); if($ip) { // we have a valid ip } else { // fail }
The code users PHP’s filter_var function to validate the IP address. It will return the IP address on success, or false if it fails.
Conclusion
You have just learned a nifty way of validating a domain name using PHP. You can use this in your code to check if domains are valid, or not, the choice is yours =)