note 106749 modified in function.ip2long by danbrown

From: Date: Tue, 06 Dec 2011 18:42:20 +0000
Subject: note 106749 modified in function.ip2long by danbrown
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-184951@lists.php.net to get a copy of this message
Universal ip4/ip6 <?php // encoded -- function encode_ip ($ip) { $d = explode('.', $ip); if (count($d) == 4) return sprintf('%02x%02x%02x%02x', $d[0], $d[1], $d[2], $d[3]); $d = explode(':', preg_replace('/(^:)|(:$)/', '', $ip)); $res = ''; foreach ($d as $x) $res .= sprintf('%0'. ($x == '' ? (9 - count($d)) * 4 : 4) .'s', $x); return $res; } // decoded function decode_ip($int_ip) { function hexhex($value) { return dechex(hexdec($value)); }; if (strlen($int_ip) == 32) { $int_ip = substr(chunk_split($int_ip, 4, ':'), 0, 39); $int_ip = ':'. implode(':', array_map("hexhex", explode(':',$int_ip))) .':'; preg_match_all("/(:0)+/", $int_ip, $zeros); if (count($zeros[0]) > 0) { $match = ''; foreach($zeros[0] as $zero) if (strlen($zero) > strlen($match)) $match = $zero; $int_ip = preg_replace('/'. $match .'/', ':', $int_ip, 1); } return preg_replace('/(^:([^:]))|(([^:]):$)/', '$2$4', $int_ip); } $hexipbang = explode('.', chunk_split($int_ip, 2, '.')); return hexdec($hexipbang[0]). '.' . hexdec($hexipbang[1]) . '.' . hexdec($hexipbang[2]) . '.' . hexdec($hexipbang[3]); } ?> DB: user_ip varchar(32) DEFAULT NULL --was-- Universal ip4/ip6 // encoded -- function encode_ip ($ip) { $d = explode('.', $ip); if (count($d) == 4) return sprintf('%02x%02x%02x%02x', $d[0], $d[1], $d[2], $d[3]); $d = explode(':', preg_replace('/(^:)|(:$)/', '', $ip)); $res = ''; foreach ($d as $x) $res .= sprintf('%0'. ($x == '' ? (9 - count($d)) * 4 : 4) .'s', $x); return $res; } // decoded function decode_ip($int_ip) { function hexhex($value) { return dechex(hexdec($value)); }; if (strlen($int_ip) == 32) { $int_ip = substr(chunk_split($int_ip, 4, ':'), 0, 39); $int_ip = ':'. implode(':', array_map("hexhex", explode(':',$int_ip))) .':'; preg_match_all("/(:0)+/", $int_ip, $zeros); if (count($zeros[0]) > 0) { $match = ''; foreach($zeros[0] as $zero) if (strlen($zero) > strlen($match)) $match = $zero; $int_ip = preg_replace('/'. $match .'/', ':', $int_ip, 1); } return preg_replace('/(^:([^:]))|(([^:]):$)/', '$2$4', $int_ip); } $hexipbang = explode('.', chunk_split($int_ip, 2, '.')); return hexdec($hexipbang[0]). '.' . hexdec($hexipbang[1]) . '.' . hexdec($hexipbang[2]) . '.' . hexdec($hexipbang[3]); } DB: user_ip varchar(32) DEFAULT NULL http://php.net/manual/en/function.ip2long.php

« previous php.notes (#184951) next »