php获取用户IP地址

一、获取用户客户端的IP
if(getenv('HTTP_CLIENT_IP') && strcasecmp(getenv('HTTP_CLIENT_IP'), 'unknown')) {
    $ip = getenv('HTTP_CLIENT_IP');
} elseif(getenv('HTTP_X_FORWARDED_FOR') && strcasecmp(getenv('HTTP_X_FORWARDED_FOR'), 'unknown')) {
    $ip = getenv('HTTP_X_FORWARDED_FOR');
} elseif(getenv('REMOTE_ADDR') && strcasecmp(getenv('REMOTE_ADDR'), 'unknown')) {
    $ip = getenv('REMOTE_ADDR');
} elseif(isset($_SERVER['REMOTE_ADDR']) && $_SERVER['REMOTE_ADDR'] && strcasecmp($_SERVER['REMOTE_ADDR'], 'unknown')) {
    $ip = $_SERVER['REMOTE_ADDR'];
}
$clientIp = preg_match ( '/[\d\.]{7,15}/', $ip, $matches ) ? $matches [0] : '';

二、根据用户IP获取用户所在城市
$link  = sprintf('http://int.dpool.sina.com.cn/iplookup/iplookup.php?format=js&ip=%s', $clientIp);
@preg_match('/{[\s\S]*?}/', curl_get($link, 3), $match);
$result= @json_decode(@array_shift($match), true);
if($result && $result['ret'] > 0){
    $city = !empty($result['city']) ? $result['city'] : (!empty($result['province']) ? $result['province'] : $result['country']);
    echo $city;
}

你可能感兴趣的:(php)