From 92fa72e07a52c3fce1c3fa82175e6ca5a758c3c1 Mon Sep 17 00:00:00 2001 From: Dennis Eichhorn Date: Thu, 21 Jul 2016 15:00:44 +0200 Subject: [PATCH] Ip converter/lookup (country) Can be considered as converter since ip->country is performed --- Utils/Converter/Ip.php | 87 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 87 insertions(+) create mode 100644 Utils/Converter/Ip.php diff --git a/Utils/Converter/Ip.php b/Utils/Converter/Ip.php new file mode 100644 index 000000000..af243582f --- /dev/null +++ b/Utils/Converter/Ip.php @@ -0,0 +1,87 @@ + + * @author Dennis Eichhorn + * @copyright 2013 Dennis Eichhorn + * @license OMS License 1.0 + * @version 1.0.0 + * @link http://orange-management.com + */ +namespace phpOMS\Utils\Converter; + +/** + * Ip converter. + * + * @category Framework + * @package phpOMS\Utils\Converter + * @author OMS Development Team + * @author Dennis Eichhorn + * @license OMS License 1.0 + * @link http://orange-management.com + * @since 1.0.0 + */ +class Ip +{ + const IP_TABLE_PATH = __DIR__ . '/../../Localization/Default/Ip/ipGeoLocation.csv'; + const IP_TABLE_ITERATIONS = 100; + + private function __construct() {} + + public static function ip2Float(string $ip) : float + { + $split = explode('.', $ip); + return $split[0] * (256 ** 3) + $split[1] * (256 ** 2) + $split[2] * (256 ** 1) + $split[3]; + } + + public static function ip2Country(string $ip) : string + { + $fh = fopen(self::IP_TABLE_PATH, 'r'); + + fseek($fh, 0, SEEK_END); + $end = ftell($fh); + fseek($fh, 0); + $start = 0; + $current = $start; + + $ip = self::ip2Float($ip); + $country = ''; + $counter = 0; + + while($counter < self::IP_TABLE_ITERATIONS) { + $line = fgets($fh, 150); + if($current !== 0) { + $line = fgets($fh, 150); + } + + $split = explode(',', $line); + + if($ip >= $split[0] && $ip <= $split[1]) { + $country = $split[2]; + break; + } + + if($ip > $split[1]) { + $larger = true; + $start = $current; + fseek($fh, ($end - $current) / 2, SEEK_CUR); + } else { + $larger = false; + $end = $current; + fseek($fh, ($start - $current) / 2, SEEK_CUR); + } + + $counter++; + $current = ftell($fh); + } + + fclose($fh); + + return $country; + } +} \ No newline at end of file