我知道这是旧的,但我尝试了其他一些解决方案在这里,他们似乎是过时的或只是返回null。我是这么做的。
使用http://www.geoplugin.net/json.gp?ip=,不需要任何类型的注册或支付服务。
function get_client_ip_server() {
$ipaddress = '';
if (isset($_SERVER['HTTP_CLIENT_IP']))
$ipaddress = $_SERVER['HTTP_CLIENT_IP'];
else if(isset($_SERVER['HTTP_X_FORWARDED_FOR']))
$ipaddress = $_SERVER['HTTP_X_FORWARDED_FOR'];
else if(isset($_SERVER['HTTP_X_FORWARDED']))
$ipaddress = $_SERVER['HTTP_X_FORWARDED'];
else if(isset($_SERVER['HTTP_FORWARDED_FOR']))
$ipaddress = $_SERVER['HTTP_FORWARDED_FOR'];
else if(isset($_SERVER['HTTP_FORWARDED']))
$ipaddress = $_SERVER['HTTP_FORWARDED'];
else if(isset($_SERVER['REMOTE_ADDR']))
$ipaddress = $_SERVER['REMOTE_ADDR'];
else
$ipaddress = 'UNKNOWN';
return $ipaddress;
}
$ipaddress = get_client_ip_server();
function getCountry($ip){
$curlSession = curl_init();
curl_setopt($curlSession, CURLOPT_URL, 'http://www.geoplugin.net/json.gp?ip='.$ip);
curl_setopt($curlSession, CURLOPT_BINARYTRANSFER, true);
curl_setopt($curlSession, CURLOPT_RETURNTRANSFER, true);
$jsonData = json_decode(curl_exec($curlSession));
curl_close($curlSession);
return $jsonData->geoplugin_countryCode;
}
echo "County: " .getCountry($ipaddress);
如果你想要更多关于它的信息,这是一个完整的Json返回:
{
"geoplugin_request":"IP_ADDRESS",
"geoplugin_status":200,
"geoplugin_delay":"2ms",
"geoplugin_credit":"Some of the returned data includes GeoLite data created by MaxMind, available from <a href='http:\/\/www.maxmind.com'>http:\/\/www.maxmind.com<\/a>.",
"geoplugin_city":"Current City",
"geoplugin_region":"Region",
"geoplugin_regionCode":"Region Code",
"geoplugin_regionName":"Region Name",
"geoplugin_areaCode":"",
"geoplugin_dmaCode":"650",
"geoplugin_countryCode":"US",
"geoplugin_countryName":"United States",
"geoplugin_inEU":0,
"geoplugin_euVATrate":false,
"geoplugin_continentCode":"NA",
"geoplugin_continentName":"North America",
"geoplugin_latitude":"37.5563",
"geoplugin_longitude":"-99.9413",
"geoplugin_locationAccuracyRadius":"5",
"geoplugin_timezone":"America\/Chicago",
"geoplugin_currencyCode":"USD",
"geoplugin_currencySymbol":"$",
"geoplugin_currencySymbol_UTF8":"$",
"geoplugin_currencyConverter":1
}