...

View Full Version : IP Address Validation



MRushton
08-29-2010, 10:49 PM
To be used in versions of PHP that do not have the native function filter_var(). It should also be used in versions that do have the native function filter_var() simply because the in-built validation is faulty (http://bugs.php.net/bug.php?id=50830).


/*
* Copyright Michael Rushton 2010
* http://squiloople.com/
* Feel free to use and redistribute this code. But please keep this copyright notice.
*/

final class IPAddressValidator {

private $ip_address;

private $ipv4 = true;
private $ipv6 = true;
private $ipv6v4 = true;

private function __construct($ip_address, $strict) {

$this->ip_address = $ip_address;

if ($strict) {
$this->SetStrict();
}

}

public static function SetIPAddress($ip_address, $strict = false) {
return new self($ip_address, $strict);
}

public function SetStrict($strict = true) {

$this->SetIPv4();
$this->SetIPv6(!$strict);
$this->SetIPv6v4(!$strict);

return $this;

}

public function SetIPv4($allow = true) {

$this->ipv4 = $allow;

return $this;

}

public function SetIPv6($allow = true) {

$this->ipv6 = $allow;

return $this;

}

public function SetIPv6v4($allow = true) {

$this->ipv6v4 = $allow;

return $this;

}

public function Validate() {

$ipv6_full = '[a-f0-9]{1,4}(?::[a-f0-9]{1,4}){7}';

$ipv6_comp = '(?!(?:.*[a-f0-9](?::|$)){8,})(?:[a-f0-9]{1,4}(?::[a-f0-9]{1,4}){0,6})?::(?:[a-f0-9]{1,4}(?::[a-f0-9]{1,4}){0,6})?';

$ipv6 = '(?:' . $ipv6_full . ')|(?:' . $ipv6_comp . ')';

$ipv6v4_full = '[a-f0-9]{1,4}(?::[a-f0-9]{1,4}){5}:';

$ipv6v4_comp = '(?!(?:.*[a-f0-9]:){6,})(?:[a-f0-9]{1,4}(?::[a-f0-9]{1,4}){0,4})?::(?:[a-f0-9]{1,4}(?::[a-f0-9]{1,4}){0,4}:)?';

$ipv6v4 = '(?:' . $ipv6v4_full . ')|(?:' . $ipv6v4_comp . ')';

$ipv4 = '(?:25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9]?[0-9])(?:\.(?:25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9]?[0-9])){3}';

switch (true) {

case ($this->ipv4 && $this->ipv6 && $this->ipv6v4):
$ip = '(?:(?:' . $ipv6 . ')|(?:(?:' . $ipv6v4 . ')?' . $ipv4 . '))';
break;
case ($this->ipv4 && $this->ipv6):
$ip = '(?:(?:' . $ipv6 . ')|(?:' . $ipv4 . '))';
break;
case ($this->ipv4 && $this->ipv6v4):
$ip = '(?:' . $ipv6v4 . ')?' . $ipv4;
break;
case ($this->ipv6 && $this->ipv6v4):
$ip = '(?:(?:' . $ipv6 . ')|(?:(?:' . $ipv6v4 . ')' . $ipv4 . '))';
break;
case ($this->ipv6):
$ip = $ipv6;
break;
case ($this->ipv6v4):
$ip = '(?:' . $ipv6v4 . ')' . $ipv4;
break;
default:
$ip = $ipv4;

}

return preg_match('/^' . $ip . '$/i', $this->ip_address);

}

}

The object is used like so:




// Returns true

SetIPAddress('255.255.255.255')->Validate();

// Returns false

SetIPAddress('255.255.255.255')->SetIPv4(false)->Validate();

// Returns true

SetIPAddress('FFFF::255.255.255.255')->Validate();

// Returns false

SetIPAddress('FFFF::255.255.255.255', true)->Validate();

// Returns true

SetIPAddress('FFFF::255.255.255.255', true)->SetIPv6v4()->Validate();



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum