Code: Select all
function is_ip_address($ip_address) {
return preg_match('/^(?:(?:(?:[a-f0-9]{1,4}(?::[a-f0-9]{1,4}){7})|(?:(?!(?:.*[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})?))|(?:(?:(?:[a-f0-9]{1,4}(?::[a-f0-9]{1,4}){5}:)|(?:(?!(?:.*[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}:)?))?(?: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}))$/i', $ip_address);
}
Code: Select all
/*
* 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);
}
}