Skip to content

Commit

Permalink
Use PHP methods to validate domain and hostname
Browse files Browse the repository at this point in the history
  • Loading branch information
vermakhushboo committed Jan 29, 2024
1 parent b401650 commit eae1a61
Show file tree
Hide file tree
Showing 2 changed files with 4 additions and 15 deletions.
13 changes: 1 addition & 12 deletions src/Domains/Domain.php
Original file line number Diff line number Diff line change
Expand Up @@ -65,21 +65,10 @@ class Domain
*/
public function __construct(string $domain)
{
if ((strpos($domain, 'http://') === 0) || (strpos($domain, 'https://') === 0)) {
if ((strpos($domain, 'http://') === 0) || (strpos($domain, 'https://') === 0 || !filter_var($domain, FILTER_VALIDATE_DOMAIN, FILTER_FLAG_HOSTNAME))) {
throw new Exception("'{$domain}' must be a valid domain or hostname");
}

if (strpos($domain, ' ') !== false || strpos($domain, ';') !== false || strpos($domain, '|') !== false || strpos($domain, '&') !== false || strpos($domain, '>') !== false || strpos($domain, '<') !== false) {
throw new Exception("Spaces and shell metacharacters not allowed in {$domain} domain");
}

$labels = explode('.', $domain);
foreach ($labels as $label) {
if (strpos($label, '-') === 0 || strpos($label, '-') === strlen($label) - 1) {
throw new Exception("Hyphens not allowed at label edges in domain {$domain}");
}
}

$this->domain = \mb_strtolower($domain);
$this->parts = \explode('.', $this->domain);

Expand Down
6 changes: 3 additions & 3 deletions tests/DomainTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -216,21 +216,21 @@ public function testHTTPSException2(): void
public function testDomainWithSpaces(): void
{
$this->expectException('Exception');
$this->expectExceptionMessage("Spaces and shell metacharacters not allowed in rm -f -r * domain");
$this->expectExceptionMessage("'rm -f -r *' must be a valid domain or hostname");
$domain = new Domain('rm -f -r *');
}

public function testDomainWithShellMetaCharacters(): void
{
$this->expectException('Exception');
$this->expectExceptionMessage("Spaces and shell metacharacters not allowed in ls; cat /etc/passwd domain");
$this->expectExceptionMessage("'ls; cat /etc/passwd' must be a valid domain or hostname");
$domain = new Domain('ls; cat /etc/passwd');
}

public function testDomainWithHypens(): void
{
$this->expectException('Exception');
$this->expectExceptionMessage("Hyphens not allowed at label edges in domain -my--domain.com");
$this->expectExceptionMessage("'-my--domain.com' must be a valid domain or hostname");
$domain = new Domain('-my--domain.com');
}

Expand Down

0 comments on commit eae1a61

Please sign in to comment.