« Previous entry | Next entry » Browse > Snippets
Skip to comments (3)
A better way to get a visitors IP in PHP
Posted by Erik on Jan 07 2008 @ 14:47 :: 1134 unique visits
CODE: PHP
<?
function _ip2long($str) {
if (($pos = strpos($str, ',')) != false) {
return ip2long(substr($str, 0, $pos));
} else {
return ip2long($str);
}
}
function ip_valid($ip) {
if (($ip === -1) || ($ip === false)) {
return false;
}
if ((($ip >= 167772160) && ($ip <= 184549375)) || // 10.0.0.0 - 10.255.255.255
(($ip >= 2886729728) && ($ip <= 2887778303)) || // 172.16.0.0 - 172.31.255.255
(($ip >= 3232235520) && ($ip <= 3232301055)) || // 192.168.0.0 - 192.168.255.255
(($ip >= 16777217) && ($ip <= 16777217 )) // 1.0.0.1 - 1.0.0.1
) {
return false;
}
return true;
}
function ip() {
$check = array('HTTP_X_FORWARDED_FOR', 'HTTP_X_FORWARDED', 'HTTP_FORWARDED_FOR', 'HTTP_FORWARDED',
'HTTP_VIA', 'HTTP_X_COMING_FROM', 'HTTP_COMING_FROM', 'REMOTE_ADDR');
foreach ($check as $c) {
if (isset($_SERVER[$c])) {
$ip = _ip2long($_SERVER[$c]);
if (ip_valid($ip)) {
return long2ip($ip);
}
}
}
return '0.0.0.0';
}
?>
function _ip2long($str) {
if (($pos = strpos($str, ',')) != false) {
return ip2long(substr($str, 0, $pos));
} else {
return ip2long($str);
}
}
function ip_valid($ip) {
if (($ip === -1) || ($ip === false)) {
return false;
}
if ((($ip >= 167772160) && ($ip <= 184549375)) || // 10.0.0.0 - 10.255.255.255
(($ip >= 2886729728) && ($ip <= 2887778303)) || // 172.16.0.0 - 172.31.255.255
(($ip >= 3232235520) && ($ip <= 3232301055)) || // 192.168.0.0 - 192.168.255.255
(($ip >= 16777217) && ($ip <= 16777217 )) // 1.0.0.1 - 1.0.0.1
) {
return false;
}
return true;
}
function ip() {
$check = array('HTTP_X_FORWARDED_FOR', 'HTTP_X_FORWARDED', 'HTTP_FORWARDED_FOR', 'HTTP_FORWARDED',
'HTTP_VIA', 'HTTP_X_COMING_FROM', 'HTTP_COMING_FROM', 'REMOTE_ADDR');
foreach ($check as $c) {
if (isset($_SERVER[$c])) {
$ip = _ip2long($_SERVER[$c]);
if (ip_valid($ip)) {
return long2ip($ip);
}
}
}
return '0.0.0.0';
}
?>
3 comments posted so far
Add your own »
2. On Jul 14 2009 @ 08:15 guest wrote:
AVI to DVD Converter,AVI to DVD Creator,iPhone Ringtone Maker for Mac,AVI Converter OS X,VOB Converter OS X,AVCHD Video Converter,FLV Converter,PowerPoint Converter,AVCHD Converter,Blue-Ray ripper,FLV to MOV Mac,VOB to DVD,HD Video Converter,iPod Playlist Transfer3. On Jan 05 2010 @ 14:56 uggbaileybutton wrote:
bailey button uggs-ugg boots cheap
ugg boots uk
ugg classic
1. On May 13 2009 @ 15:48 guest wrote:
Need Furniture? And need to buy furniture from China at competitive price? LongYear Furniture is your source for quality bedroom furniture featuring a huge selection of home furniture a happy home for beautiful life, kids furniture for a good memory of childhood, and to gain an extra good price from wholesale furniture and direct from furniture manufacturers China, styles of China furniture are available, living room furniture is also nice for your house, find dining room furniture and more!