Created
April 2, 2024 22:37
-
-
Save joeyboli/3246bc7ce44b15bfbd85f62e745a51ce to your computer and use it in GitHub Desktop.
Domain Validation in php
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function checkDomain(string $url, string $remark = 'Domain Offline/invalid', int $timeout = 10): mixed | |
{ | |
// Parse the URL to extract the host, port, and scheme | |
$parsedUrl = parse_url($url); | |
$host = $parsedUrl['host'] ?? $url; | |
$port = $parsedUrl['port'] ?? -1; // Use -1 if port is not specified | |
$scheme = $parsedUrl['scheme'] ?? 'http'; // Default to HTTP if scheme is not specified | |
// Check if the input is an IP address | |
$isIp = filter_var($host, FILTER_VALIDATE_IP); | |
if ($isIp) { | |
// If it's an IP address, skip DNS resolution | |
$ips = [$host]; | |
} else { | |
// Check if the domain has a valid DNS A record | |
$dnsRecords = dns_get_record($host, DNS_A); | |
if (empty($dnsRecords)) { | |
return $remark; | |
} | |
$ips = array_column($dnsRecords, 'ip'); | |
} | |
// Use the default port if it's not specified in the URL | |
if ($port === -1) { | |
$port = $scheme === 'https' ? 443 : 80; | |
} | |
// Try to establish a connection | |
$fp = fsockopen($isIp ? $host : $ips[0], $port, $errno, $errstr, $timeout); | |
if ($fp) { | |
fclose($fp); | |
return $url; | |
} | |
return $remark; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment