为了保存并在 Mysql 中,我建议使用 Mysql 函数INET_NTOA()和INET_ATON()
为了验证和获取 IP 地址,我使用以下函数:
function is_ip($ip) {
global $localIPs;
$test = 0;
$pattern='/^(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9])\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9]|0)\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9]|0)\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[0-9])$/';
$ip = explode(',', $ip);
$ip = array_map('trim', $ip);
foreach ($ip as $key => $value) {
if(array_search($value, $localIPs)===false && preg_match($pattern, $value)) $test = $value;
}
if(!empty($test)) return $test;
else return false;
}
function get_ip() {
$ip='';
if(!empty($_SERVER['HTTP_X_REAL_IP']) && is_ip($_SERVER['HTTP_X_REAL_IP'])) $ip=is_ip($_SERVER['HTTP_X_REAL_IP']);
elseif(!empty($_SERVER['HTTP_CLIENT_IP']) && is_ip($_SERVER['HTTP_CLIENT_IP'])) $ip=is_ip($_SERVER['HTTP_CLIENT_IP']);
elseif(!empty($_SERVER['HTTP_X_FORWARDED_FOR']) && is_ip($_SERVER['HTTP_X_FORWARDED_FOR'])) $ip=is_ip($_SERVER['HTTP_X_FORWARDED_FOR']);
else $ip=is_ip($_SERVER['REMOTE_ADDR']);
return $ip;
}