<?php
namespace org;
class IpHelper
{
public static function ip2region($ip){
$re=self::ip_2_region($ip);
$str='';
if (is_array($re) && isset($re['region'])){
$str=$re['region'];
}
return $str;
}
public static function ip_2_region($ip){
if (is_numeric($ip)){
$ip=long2ip($ip);
}
$class = new \Ip2Region();
return $class->btreeSearch($ip);
}
public static function checkIP($ip, $valid_list, $invalid_list=array(), $is_strict=true)
{
$ip_segs = explode('.', $ip);
if (!empty($invalid_list))
{
return self::isInSection($ip_segs, $invalid_list) ? false : true;
}
if (!empty($valid_list))
{
return self::isInSection($ip_segs, $valid_list);
}
return $is_strict == true ? false : true;
}
public static function isInSection($ip_segs, $ip_list)
{
foreach ($ip_list as $key => $val)
{
$ip_str = self::formatIp($val);
if (!empty($ip_str))
{
$segments = explode('.', $ip_str);
if (self::isValidSegment($ip_segs, $segments))
{
return true;
}
}
}
return false;
}
public static function formatIp($ip)
{
$arr = explode('.', $ip);
$repeat_count = 4 - count($arr);
if ($repeat_count < 0)
{
return false;
}
$ip .= str_repeat('.*', $repeat_count) return str_replace('*', '0-255', $ip) }
public static function isValidSegment($ip_segs, $segments)
{
foreach ($segments as $key => $val)
{
if (strstr($val, '-') !== false)
{
$range = explode('-', $val);
if ($ip_segs[$key] < (int)$range[0] || $ip_segs[$key] > (int)$range[1])
{
return false;
}
}
else
{
if ((string)$ip_segs[$key] != trim($val))
{
return false;
}
}
}
return true;
}
}