Skip to content

Instantly share code, notes, and snippets.

@neo22s
Last active October 18, 2020 02:25
Show Gist options
  • Save neo22s/8b55ee8f869b49fe8d2f to your computer and use it in GitHub Desktop.
Save neo22s/8b55ee8f869b49fe8d2f to your computer and use it in GitHub Desktop.
validate domain name in PHP
<?
/**
* checks if a domain name is valid
* @param string $domain_name
* @return bool
*/
public static function domain_name($domain_name)
{
//FILTER_VALIDATE_URL checks length but..why not? so we dont move forward with more expensive operations
$domain_len = strlen($domain_name);
if ($domain_len < 3 OR $domain_len > 253)
return FALSE;
//getting rid of HTTP/S just in case was passed.
if(stripos($domain_name, 'http://') === 0)
$domain_name = substr($domain_name, 7);
elseif(stripos($domain_name, 'https://') === 0)
$domain_name = substr($domain_name, 8);
//we dont need the www either
if(stripos($domain_name, 'www.') === 0)
$domain_name = substr($domain_name, 4);
//Checking for a '.' at least, not in the beginning nor end, since http://.abcd. is reported valid
if(strpos($domain_name, '.') === FALSE OR $domain_name[strlen($domain_name)-1]=='.' OR $domain_name[0]=='.')
return FALSE;
//now we use the FILTER_VALIDATE_URL, concatenating http so we can use it, and return BOOL
return (filter_var ('http://' . $domain_name, FILTER_VALIDATE_URL)===FALSE)? FALSE:TRUE;
}
@jeorlie
Copy link

jeorlie commented Oct 18, 2020

I came across this and copied to save a few minutes.
I added this block though
$dot_position = strpos($domain_name, '.');
$ext = substr($domain_name, ($dot_position) + 1);
if(strlen($ext) < 2) return false; // no single character tld yet known.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment