Skip to content

Commit

Permalink
Fixed valid_ip() for PHP < 5.2
Browse files Browse the repository at this point in the history
  • Loading branch information
narfbg committed Jun 7, 2012
1 parent 45927d8 commit 7281159
Showing 1 changed file with 21 additions and 22 deletions.
43 changes: 21 additions & 22 deletions system/core/Input.php
Expand Up @@ -389,11 +389,10 @@ public function valid_ip($ip, $which = '')
break;
}

return filter_var($ip, FILTER_VALIDATE_IP, $flag) !== FALSE;
return (bool) filter_var($ip, FILTER_VALIDATE_IP, $flag);
}

// If it's not we'll do it manually
if ($which != 'ipv6' OR $which != 'ipv4')

if ($which !== 'ipv6' && $which !== 'ipv4')
{
if (strpos($ip, ':') !== FALSE)
{
Expand All @@ -405,16 +404,16 @@ public function valid_ip($ip, $which = '')
}
else
{
return FALSE;
return $this->_valid_ipv4($ip) OR $this->_valid_ipv6($ip);
}
}

$func = '_valid_'.$which;
return $this->$func($ip);
}

// --------------------------------------------------------------------

/**
* Validate IPv4 Address
*
Expand All @@ -429,7 +428,7 @@ protected function _valid_ipv4($ip)
$ip_segments = explode('.', $ip);

// Always 4 segments needed
if (count($ip_segments) != 4)
if (count($ip_segments) !== 4)
{
return FALSE;
}
Expand All @@ -438,7 +437,7 @@ protected function _valid_ipv4($ip)
{
return FALSE;
}

// Check each segment
foreach ($ip_segments as $segment)
{
Expand All @@ -452,9 +451,9 @@ protected function _valid_ipv4($ip)

return TRUE;
}

// --------------------------------------------------------------------

/**
* Validate IPv6 Address
*
Expand All @@ -467,33 +466,33 @@ protected function _valid_ipv6($str)
// 8 groups, separated by :
// 0-ffff per group
// one set of consecutive 0 groups can be collapsed to ::

$groups = 8;
$collapsed = FALSE;

$chunks = array_filter(
preg_split('/(:{1,2})/', $str, NULL, PREG_SPLIT_DELIM_CAPTURE)
);

// Rule out easy nonsense
if (current($chunks) == ':' OR end($chunks) == ':')
{
return FALSE;
}

// PHP supports IPv4-mapped IPv6 addresses, so we'll expect those as well
if (strpos(end($chunks), '.') !== FALSE)
{
$ipv4 = array_pop($chunks);

if ( ! $this->_valid_ipv4($ipv4))
{
return FALSE;
}

$groups--;
}

while ($seg = array_pop($chunks))
{
if ($seg[0] == ':')
Expand All @@ -502,19 +501,19 @@ protected function _valid_ipv6($str)
{
return FALSE; // too many groups
}

if (strlen($seg) > 2)
{
return FALSE; // long separator
}

if ($seg == '::')
{
if ($collapsed)
{
return FALSE; // multiple collapsed
}

$collapsed = TRUE;
}
}
Expand Down

0 comments on commit 7281159

Please sign in to comment.