Sometimes we need to validate the domain name, and we can easily do it by using a regular expression or by using some of the inbuilt functions in PHP. But it does not mean that the domain name is actually registered and working.
To solve this problem, I have created a function to validate the domain name.
It's a complete validation of the domain name.
Features
- Adding HTTP if already not in the domain.
- Validates only HTTP and https in a scheme.
- Validates URL.
- Checks A record of the domain name.
- Validates server header response.
- Validates the host.
- Removes www. if you don't want it.
Function:
function is_valid_domain($url){
$validation = FALSE;
/*Parse URL*/
$urlparts = parse_url(filter_var($url, FILTER_SANITIZE_URL));
/*Check host exist else path assign to host*/
if(!isset($urlparts['host'])){
$urlparts['host'] = $urlparts['path'];
}
if($urlparts['host']!=''){
/*Add scheme if not found*/
if (!isset($urlparts['scheme'])){
$urlparts['scheme'] = 'http';
}
/*Validation*/
if(checkdnsrr($urlparts['host'], 'A') && in_array($urlparts['scheme'],array('http','https')) && ip2long($urlparts['host']) === FALSE){
$urlparts['host'] = preg_replace('/^www\./', '', $urlparts['host']);
$url = $urlparts['scheme'].'://'.$urlparts['host']. "/";
if (filter_var($url, FILTER_VALIDATE_URL) !== false && @get_headers($url)) {
$validation = TRUE;
}
}
}
if(!$validation){
echo "Its Invalid Domain Name.";
}else{
echo " $url is a Valid Domain Name.";
}
}
//Function Call
is_valid_domain('//www.w3schools.in');