What are the differences between using get_headers() and gethostbyname() to check the existence of an external domain in PHP?

When checking the existence of an external domain in PHP, using get_headers() is a more reliable method compared to gethostbyname(). get_headers() returns an array containing the response headers of a URL, allowing you to check the HTTP status code for a successful connection. On the other hand, gethostbyname() simply returns the IP address of a domain without verifying its existence.

function check_domain_existence($domain) {
    $headers = @get_headers($domain);
    
    if ($headers && strpos($headers[0], '200') !== false) {
        return true; // Domain exists
    } else {
        return false; // Domain does not exist
    }
}

$domain = 'example.com';
if (check_domain_existence($domain)) {
    echo "Domain $domain exists.";
} else {
    echo "Domain $domain does not exist.";
}