Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to validate domain name in PHP?

Is it possible without using regular expression?

For example, I want to check that a string is a valid domain:

domain-name abcd example 

Are valid domains. These are invalid of course:

domaia@name ab$%cd 

And so on. So basically it should start with an alphanumeric character, then there may be more alnum characters plus also a hyphen. And it must end with an alnum character, too.

If it's not possible, could you suggest me a regexp pattern to do this?

EDIT:

Why doesn't this work? Am I using preg_match incorrectly?

$domain = '@djkal'; $regexp = '/^[a-zA-Z0-9][a-zA-Z0-9\-\_]+[a-zA-Z0-9]$/'; if (false === preg_match($regexp, $domain)) {     throw new Exception('Domain invalid'); } 
like image 635
Richard Knop Avatar asked Nov 18 '09 10:11

Richard Knop


People also ask

How to check valid domain name in PHP?

php function is_valid_domain_name($domain_name) { return (preg_match("/^([a-z\d](-*[a-z\d])*)(\. ([a-z\d](-*[a-z\d])*))*$/i", $domain_name) //valid chars check && preg_match("/^. {1,253}$/", $domain_name) //overall length check && preg_match("/^[^\.]{ 1,63}(\.

How do I check if a domain name is valid?

The valid domain name must satisfy the following conditions: The domain name should be a-z or A-Z or 0-9 and hyphen (-). The domain name should be between 1 and 63 characters long. The domain name should not start or end with a hyphen(-) (e.g. -geeksforgeeks.org or geeksforgeeks.org-).


1 Answers

<?php function is_valid_domain_name($domain_name) {     return (preg_match("/^([a-z\d](-*[a-z\d])*)(\.([a-z\d](-*[a-z\d])*))*$/i", $domain_name) //valid chars check             && preg_match("/^.{1,253}$/", $domain_name) //overall length check             && preg_match("/^[^\.]{1,63}(\.[^\.]{1,63})*$/", $domain_name)   ); //length of each label } ?> 

Test cases:

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? [<script]                 N is_valid_domain_name? [alert(]                  N is_valid_domain_name? [.]                       N is_valid_domain_name? [..]                      N is_valid_domain_name? [ ]                       N is_valid_domain_name? [-]                       N is_valid_domain_name? []                        N 
like image 63
velcrow Avatar answered Sep 18 '22 09:09

velcrow