fix: Update RFC1123 Hostname Check (#7572)

* Update RFC1123 Hostname Check

The regex was wrong. It failed to match devices like `cisco-3750x` even though it is a valid hostname. 
I picked this regex from the RFC1123 documentation, and updated it.

* Update CommonFunctionsTest.php

Update tests

* Updated to allow domains ending with a dot
This commit is contained in:
Parth Laxmikant Kolekar
2017-10-29 15:42:32 +05:30
committed by Daniel Preussker
parent 6fab5166c5
commit ebcfa45a93
2 changed files with 7 additions and 2 deletions

View File

@ -629,9 +629,9 @@ function is_valid_hostname($hostname)
// maximum length is 253 characters, maximum segment size is 63
return (
preg_match("/^([a-z\d](-*[a-z\d])*)(\.([a-z\d](-*[a-z\d])*))*\.?$/i", $hostname) //valid chars check
preg_match("/^(([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\-]*[a-zA-Z0-9])\.)*([A-Za-z0-9]|[A-Za-z0-9][A-Za-z0-9\-]*[A-Za-z0-9])\.?$/", $hostname) //valid chars check
&& preg_match("/^.{1,253}$/", $hostname) //overall length check
&& preg_match("/^[^\.]{1,63}(\.[^\.]{1,63})*\.?$/", $hostname)
&& preg_match("/^[^\.]{1,63}(\.[^\.]{1,63})*\.?$/", $hostname) //segment length check
);
}

View File

@ -129,11 +129,16 @@ class CommonFunctionsTest extends \PHPUnit_Framework_TestCase
$this->assertTrue(is_valid_hostname('google.com'), 'google.com');
$this->assertTrue(is_valid_hostname('news.google.co.uk'), 'news.google.co.uk');
$this->assertTrue(is_valid_hostname('xn--fsqu00a.xn--0zwm56d'), 'xn--fsqu00a.xn--0zwm56d');
$this->assertTrue(is_valid_hostname('www.averylargedomainthatdoesnotreallyexist.com'), 'www.averylargedomainthatdoesnotreallyexist.com');
$this->assertTrue(is_valid_hostname('cont-ains.h-yph-en-s.com'), 'cont-ains.h-yph-en-s.com');
$this->assertTrue(is_valid_hostname('cisco-3750x'), 'cisco-3750x');
$this->assertFalse(is_valid_hostname('cisco_3750x'), 'cisco_3750x');
$this->assertFalse(is_valid_hostname('goo gle.com'), 'goo gle.com');
$this->assertFalse(is_valid_hostname('google..com'), 'google..com');
$this->assertFalse(is_valid_hostname('google.com '), 'google.com ');
$this->assertFalse(is_valid_hostname('google-.com'), 'google-.com');
$this->assertFalse(is_valid_hostname('.google.com'), '.google.com');
$this->assertFalse(is_valid_hostname('..google.com'), '..google.com');
$this->assertFalse(is_valid_hostname('<script'), '<script');
$this->assertFalse(is_valid_hostname('alert('), 'alert(');
$this->assertFalse(is_valid_hostname('.'), '.');