Php is valid domain

Saved searches

Use saved searches to filter your results more quickly

You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window. Reload to refresh your session.

PHP Class to check if given name valid domain name or not

ewwink/php-domain-name-validation

This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Name already in use

A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?

Sign In Required

Please sign in to use Codespaces.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching Xcode

If nothing happens, download Xcode and try again.

Launching Visual Studio Code

Your codespace will open once ready.

There was a problem preparing your codespace, please try again.

Latest commit

Git stats

Files

Failed to load latest commit information.

README.md

PHP Domain Name Validation

This is PHP Class to check if given name valid domain name or not.

In the pass when Domain TLDs only .com .net .org .biz .info .us to extract domain name you can use Regular expression

now when more then 500 Domain TLDs registered that regex is not reliable even with if you modified like this one

for example with regex above name cintai.anu.mu will detected as valid domain not subdomain but its wrong valid domain tlds are .mu, ac.mu, .co.mu, .com.mu, .org.mu, .net.mu

require_once("is_domain.php"); ### Return True if domain valid domain, otherwise false checkName::is_domain("example.com"); // will return "true" ### Get or Parse domain from URL checkName::cleanURL("https://github.com/ewwink/php-domain-name-validation"); // will return "github.com" ### Get or Parse domain from URL and validate Domain name checkName::is_domain("https://github.com/ewwink/php-domain-name-validation", true); // will return "true" 

learning and doing is fun check pagerank

Источник

PHP Check the domain name is valid

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 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'); 

Источник

neo22s / validate.php

This file contains 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

/**
* 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 ;
>

Источник

regex — How to validate domain name in PHP?

Solution:

$/", $domain_name) //overall length check && preg_match("/^[^\.](\.[^\.])*$/", $domain_name) ); //length of each label > ?> 
is_valid_domain_name? [a] Y is_valid_domain_name? [0] Y is_valid_domain_name? [a.b] Y is_valid_domain_name? [localhost] Y is_valid_domain_name? [google.com] Y is_valid_domain_name? [news.google.co.uk] Y is_valid_domain_name? [xn--fsqu00a.xn--0zwm56d] Y is_valid_domain_name? [goo gle.com] N is_valid_domain_name? [google..com] N is_valid_domain_name? [google.com ] N is_valid_domain_name? [google-.com] N is_valid_domain_name? [.google.com] N is_valid_domain_name? [ 

Answer

Solution:

With this you will not only be checking if the domain has a valid format, but also if it is active / has an IP address assigned to it.

$domain = "stackoverflow.com"; if(filter_var(gethostbyname($domain), FILTER_VALIDATE_IP)) 

Note that this method requires the DNS entries to be active so if you require a domain string to be validated without being in the DNS use the regular expression method given by velcrow above.

Also this function is not intended to validate a URL string use FILTER_VALIDATE_URL for that. We do not use FILTER_VALIDATE_URL for a domain because a domain string is not a valid URL.

Answer

Solution:

// Validate a domain name var_dump(filter_var('mandrill._domainkey.mailchimp.com', FILTER_VALIDATE_DOMAIN)); # string(33) "mandrill._domainkey.mailchimp.com" // Validate an hostname (here, the underscore is invalid) var_dump(filter_var('mandrill._domainkey.mailchimp.com', FILTER_VALIDATE_DOMAIN, FILTER_FLAG_HOSTNAME)); # bool(false) 

Answer

Solution:

$domain = "stackoverflow.com"; checkdnsrr($domain , "A"); //returns true if has a dns A record, false otherwise 

Answer

Solution:

Firstly, you should clarify whether you mean:

  1. individual domain name labels
  2. entire domain names (i.e. multiple dot-separate labels)
  3. host names

The reason the distinction is necessary is that a label can technically include any characters, including the NUL, @ and ' . ' characters. DNS is 8-bit capable and it's perfectly possible to have a zone file containing an entry reading " an\0odd\[email protected] ". It's not recommended of course, not least because people would have difficulty telling a dot inside a label from those separating labels, but it is legal.

However, URLs require a host name in them, and those are governed by RFCs 952 and 1123. Valid host names are a subset of domain names. Specifically only letters, digits and hyphen are allowed. Furthermore the first and last characters cannot be a hyphen. RFC 952 didn't permit a number for the first character, but RFC 1123 subsequently relaxed that.

Off the top of my head I don't think it's possible to invalidate the a- example with a single simple regexp. The best I can come up with to check a single host label is:

if (preg_match('/^[a-z\d][a-z\d-]$/i', $label) && !preg_match('/-$/', $label)) 

To further complicate matters, some domain name entries (typically SRV records) use labels prefixed with an underscore, e.g. _sip._udp.example.com . These are not host names, but are legal domain names.

Answer

Solution:

Here is another way without regex.

$myUrl = "http://www.domain.com/link.php"; $myParsedURL = parse_url($myUrl); $myDomainName= $myParsedURL['host']; $ipAddress = gethostbyname($myDomainName); if($ipAddress == $myDomainName) < echo "There is no url"; >else 

Answer

Solution:

I think once you have isolated the domain name, say, using Erklan's idea:

$myUrl = "http://www.domain.com/link.php"; $myParsedURL = parse_url($myUrl); $myDomainName= $myParsedURL['host']; 
if( false === filter_var( $myDomainName, FILTER_VALIDATE_URL ) ) < // failed test >

PHP5s Filter functions are for just such a purpose I would have thought.

It does not strictly answer your question as it does not use Regex, I realise.

Answer

Solution:

Regular expression is the most effective way of checking for a domain validation. If you're dead set on not using a Regular Expression (which IMO is stupid), then you could split each part of a domain:

You would then have to check each character in some sort of a loop to see that it matches a valid domain.

Like I said, it's much more effective to use a regular expression.

Answer

Solution:

Your regular expression is fine, but you're not using preg_match right. It returns an int (0 or 1), not a boolean. Just write if(!preg_match($regex, $string))

Answer

Solution:

If you don't want to use regular expressions, you can try this:

$str = 'domain-name'; if (ctype_alnum(str_replace('-', '', $str)) && $str[0] != '-' && $str[strlen($str) - 1] != '-') < echo "Valid domain\n"; >else 

but as said regexp are the best tool for this.

Answer

Solution:

If you want to check whether a particular domain name or ip address exists or not, you can also use checkdnsrr
Here is the doc http://php.net/manual/en/function.checkdnsrr.php

Answer

Solution:

A valid domain is for me something I'm able to register or at least something that looks like I could register it. This is the reason why I like to separate this from "localhost"-names.

And finally I was interested in the main question if avoiding Regex would be faster and this is my result:

 253 // .example.org and localhost- are not allowed || $name[0] == '.' || $name[0] == '-' || $name[ $len - 1 ] == '.' || $name[ $len - 1 ] == '-' // a.de is the shortest possible domain name and needs one dot || ($domain_only && ($len < 4 || strpos($name, '.') === false)) // several combinations are not allowed || strpos($name, '..') !== false || strpos($name, '.-') !== false || strpos($name, '-.') !== false // only letters, numbers, dot and hypen are allowed /* // a little bit slower || !ctype_alnum(str_replace(array('-', '.'), '', $name)) */ || preg_match('/[^a-z\d.-]/i', $name) ) < return false; >// each label may contain up to 63 characters $offset = 0; while (($pos = strpos($name, '.', $offset)) !== false) < if ($pos - $offset >63) < return false; >$offset = $pos + 1; > return $name; > ?> 

Benchmark results compared with velcrow 's function and 10000 iterations (complete results contains many code variants. It was interesting to find the fastest.):

filter_hostname($domain);// $domains: 0.43556308746338 $real_world: 0.33749794960022 is_valid_domain_name($domain);// $domains: 0.81832790374756 $real_world: 0.32248711585999 

$real_world did not contain extreme long domain names to produce better results. And now I can answer your question: With the usage of ctype_alnum() it would be possible to realize it without regex, but as preg_match() was faster I would prefer that.

If you don't like the fact that "local.host" is a valid domain name use this function instead that valids against a public tld list. Maybe someone finds the time to combine both.

Answer

Solution:

The correct answer is that you don't . you let a unit tested tool do the work for you:

// return '' if host invalid -- private function setHostname($host = '') < $ret = (!empty($host)) ? $host : ''; if(filter_var('http://'.$ret.'/', FILTER_VALIDATE_URL) === false) < $ret = ''; >return $ret; > 

Answer

Solution:

If you can run shell commands, following is the best way to determine if a domain is registered.

This function returns false, if domain name isn't registered else returns domain name.

function get_domain_name($domain) < //Step 1 - Return false if any shell sensitive chars or space/tab were found if(escapeshellcmd($domain)!=$domain || count(explode(".", $domain))//Step 2 - Get the root domain in-case of subdomain $domain = (count(explode(".", $domain))>2 ? strtolower(explode(".", $domain)[count(explode(".", $domain))-2].".".explode(".", $domain)[count(explode(".", $domain))-1]) : strtolower($domain)); //Step 3 - Run shell command 'dig' to get SOA servers for the domain extension $ns = shell_exec(escapeshellcmd("dig +short SOA ".escapeshellarg(explode(".", $domain)[count(explode(".", $domain))-1]))); //Step 4 - Return false if invalid extension (returns NULL), or take the first server address out of output if($ns===NULL) < return false; >$ns = (((preg_split('/\s+/', $ns)[0])[strlen(preg_split('/\s+/', $ns)[0])-1]==".") ? substr(preg_split('/\s+/', $ns)[0], 0, strlen(preg_split('/\s+/', $ns)[0])-1) : preg_split('/\s+/', $ns)[0]); //Step 5 - Run another dig using the obtained address for our domain, and return false if returned NULL else return the domain name. This assumes an authoritative NS is assigned when a domain is registered, can be improved to filter more accurately. $ans = shell_exec(escapeshellcmd("dig +noall +authority ".escapeshellarg("@".$ns)." ".escapeshellarg($domain))); return (($ans===NULL) ? false : ((strpos($ans, $ns)>-1) ? false : $domain)); > 
  1. Works on any domain, while php dns functions may fail on some domains. (my .pro domain failed on php dns)
  2. Works on fresh domains without any dns (like A) records
  3. Unicode friendly

Источник

Читайте также:  Модуль pathlib python 3
Оцените статью