How to validate a domain in PHP

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:

  1. get the IP address of the domain
  2. 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:

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:

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.


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 =)

Leave a comment

Find the Best SEO in Fort Lauderdale, Florida (Plantation SEO) | Drupal & Worpress Develpment