All Tutorials

Your One-Stop Destination for Learning and Growth

Checking a Domain Name with PHP Script

If you own a website or planning to create one, checking the availability of a domain name is an essential task. In this blog post, we will walk through a simple process of creating a PHP script that checks whether a given domain name is available or not. We'll be using a free WHOIS API service, like whois.porkbun.com, to accomplish this.

Prerequisites

  • A basic understanding of HTML, CSS, and PHP.
  • A web hosting account with PHP support.

Creating the PHP script

Let's call our PHP file check_domain.php. Create a new file using your favorite text editor or an Integrated Development Environment (IDE) like Visual Studio Code. Now copy and paste the following code into the file:

<?php
$domain = $_GET['domain'];
if(empty($domain)) {
    die("Please provide a domain name as a query parameter.");
}

$url = "http://api.whois.porkbun.com/whois/$domain";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);

if ($httpCode != 200) {
    die("Error: cURL returned HTTP code $httpCode.");
}

curl_close($ch);

// Parse the XML response and extract the registration date.
$xml = simplexml_load_string($response);
$registered_on = (string)$xml->registrar->registrantContact->registrantName->[0];
$registered_on .= " - " . (string)$xml->registrar->registrantContact->registrantStreet->[0];
$registered_on .= ", " . (string)$xml->registrar->registrantContact->registrantCity->[0] . ", " . (string)$xml->registrar->registrantContact->registrantCountry->[0];

if(empty($registered_on)) {
    echo "The domain name '{$domain}' is available.";
} else {
    echo "The domain name '{$domain}' is registered by: {$registered_on}";
}
?>

Replace whois.porkbun.com with the API URL of your preferred WHOIS service if needed.

This script uses the cURL library for making HTTP requests and SimpleXML for parsing the XML response. The PHP script accepts a domain name as a query parameter, fetches the WHOIS information using the provided API, and then checks whether the registration details are empty or not to determine availability.

Using the script

Save your file as check_domain.php in your web server's public directory (e.g., htdocs) and make sure your PHP installation is enabled on your web hosting account. To test it, open a new browser window, enter the following URL: http://yourwebsite.com/check_domain.php?domain=example.com (replace yourwebsite.com with your actual website address).

The script will return "The domain name 'example.com' is registered by:" if it's already taken or "The domain name 'example.com' is available." if it's free for registration.

In conclusion, this simple PHP script makes checking the availability of a domain name an easy and accessible process right from your website. Happy coding!

Published May, 2015