獲得IP地址
在 PHP 中得到當前訪問者的IP地址,還是比較簡單的:
$ip = $_SERVER['REMOTE_ADDR']
上面IP有時獲取不到真實IP地址我們可以如下操作
$ip = GetIP();
將IP轉換為城市等信息
淘寶提供了一個IP數據接口: http://ip.taobao.com/service/getIpInfo.php?ip=ip地址
$response = file_get_contents('http://ip.taobao.com/service/getIpInfo.php?ip='.$ip);
$result = json_decode($response);
print_r($result);
輸出結果為:
stdClass Object
(
[code] => 0
[data] => stdClass Object
(
[country] => 中國
[country_id] => CN
[area] => 華南
[area_id] => 800000
[region] => 廣東省
[region_id] => 440000
[city] => 深圳市
[city_id] => 440300
[county] =>
[county_id] => -1
[isp] => 電信
[isp_id] => 100017
[ip] => 183.16.191.102
)
)
function GetIP() {
if ($_SERVER["HTTP_X_FORWARDED_FOR"])
$ip = $_SERVER["HTTP_X_FORWARDED_FOR"];
else if ($_SERVER["HTTP_CLIENT_IP"])
$ip = $_SERVER["HTTP_CLIENT_IP"];
else if ($_SERVER["REMOTE_ADDR"])
$ip = $_SERVER["REMOTE_ADDR"];
else if (getenv("HTTP_X_FORWARDED_FOR"))
$ip = getenv("HTTP_X_FORWARDED_FOR");
else if (getenv("HTTP_CLIENT_IP"))
$ip = getenv("HTTP_CLIENT_IP");
else if (getenv("REMOTE_ADDR"))
$ip = getenv("REMOTE_ADDR");
else
$ip = "Unknown";
return $ip;
}
echo GetIP();