この関数を使用して、ユーザーエージェントから IP を取得します
<?php
# validip/getip courtesy of manolete <manolete@myway.com>
# IP Validation
function validip($ip) {
if (!empty($ip) && $ip==long2ip(ip2long($ip))) {
# reserved IANA IPv4 addresses
# http://www.iana.org/assignments/ipv4-address-space
$reserved_ips = array (
array('0.0.0.0','2.255.255.255'),
array('10.0.0.0','10.255.255.255'),
array('127.0.0.0','127.255.255.255'),
array('169.254.0.0','169.254.255.255'),
array('172.16.0.0','172.31.255.255'),
array('192.0.2.0','192.0.2.255'),
array('192.168.0.0','192.168.255.255'),
array('255.255.255.0','255.255.255.255')
);
foreach ($reserved_ips as $r)
if ((ip2long($ip) >= ip2long($r[0])) && (ip2long($ip) <= ip2long($r[1])))
return false;
return true;
}
return false;
}
/* Patched function to detect REAL IP address if it's valid */
function getip() {
if (getenv('HTTP_CLIENT_IP') && long2ip(ip2long(getenv('HTTP_CLIENT_IP')))==getenv('HTTP_CLIENT_IP') && validip(getenv('HTTP_CLIENT_IP')))
return getenv('HTTP_CLIENT_IP');
if (getenv('HTTP_X_FORWARDED_FOR') && long2ip(ip2long(getenv('HTTP_X_FORWARDED_FOR')))==getenv('HTTP_X_FORWARDED_FOR') && validip(getenv('HTTP_X_FORWARDED_FOR')))
return getenv('HTTP_X_FORWARDED_FOR');
if (getenv('HTTP_X_FORWARDED') && long2ip(ip2long(getenv('HTTP_X_FORWARDED')))==getenv('HTTP_X_FORWARDED') && validip(getenv('HTTP_X_FORWARDED')))
return getenv('HTTP_X_FORWARDED');
if (getenv('HTTP_FORWARDED_FOR') && long2ip(ip2long(getenv('HTTP_FORWARDED_FOR')))==getenv('HTTP_FORWARDED_FOR') && validip(getenv('HTTP_FORWARDED_FOR')))
return getenv('HTTP_FORWARDED_FOR');
if (getenv('HTTP_FORWARDED') && long2ip(ip2long(getenv('HTTP_FORWARDED')))==getenv('HTTP_FORWARDED') && validip(getenv('HTTP_FORWARDED')))
return getenv('HTTP_FORWARDED');
$ip = htmlspecialchars($_SERVER['REMOTE_ADDR']);
/* Added support for IPv6 connections. otherwise ip returns null */
if (strpos($ip, '::') === 0) {
$ip = substr($ip, strrpos($ip, ':')+1);
}
return long2ip(ip2long($ip));
}
?>