Skip to content

Instantly share code, notes, and snippets.

@joshuaadickerson
Last active August 29, 2015 14:27
Show Gist options
  • Save joshuaadickerson/38ce06ec68f19397febb to your computer and use it in GitHub Desktop.
Save joshuaadickerson/38ce06ec68f19397febb to your computer and use it in GitHub Desktop.
<?php
function getIPBanRange(array $start, array $end)
{
$parts_count = count($start);
if ($parts_count !== count($end))
{
throw new \InvalidArgumentException('$start and $end must be the same length');
}
// Find the first element that isn't the same
for ($i = 0; $i < $parts_count; $i++)
{
if ($start[$i] !== $end[$i])
{
// @todo check if $end > $start
$size = $end[$i] - $start[$i];
$starting_part = $i;
break;
}
}
$parts = array_fill(0, $parts_count, array('low' => 0, 'high' => 255));
$range = array_fill(0, $size, $parts);
for ($i = 0; $i < $parts_count; $i++)
{
$range[0][$i]['low'] = $start[$i];
}
if ($starting_part !== 0)
{
for ($i = 1; $i < $size; $i++)
{
for($p = 0; $p < $starting_part; $p++)
{
$range[$i] = array(
'low' => $start[$p],
'high' => $start[$p]
);
}
}
}
// Set the maximums
for ($i = 0; $i < $parts_count; $i++)
{
$range[$size][$i]['high'] = $end[$i];
}
return $range;
}
$start = explode('152.9.13.4', '.');
$end = explode('187.22.1.122', '.');
var_dump(getIPBanRange($start, $end));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment