PS:此代码是从Getting visitors country from their IP修改的
我尝试使用https://api.ipdata.co/的ipdata服务,但是当我尝试使用PHP解码json时,没有任何反应。即使我试图打印出api响应。任何人都可以帮助我哈哈..
php代码:
function ip_info($ip = NULL, $purpose = "location", $deep_detect = TRUE) {
$output = NULL;
if (filter_var($ip, FILTER_VALIDATE_IP) === FALSE) {
$ip = $_SERVER["REMOTE_ADDR"];
if ($deep_detect) {
if (filter_var(@$_SERVER['HTTP_X_FORWARDED_FOR'], FILTER_VALIDATE_IP))
$ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
if (filter_var(@$_SERVER['HTTP_CLIENT_IP'], FILTER_VALIDATE_IP))
$ip = $_SERVER['HTTP_CLIENT_IP'];
} else {
echo "error [2]";
}
} else {
echo "error [1]";
}
$rdata = file_get_contents("http://api.ipdata.co/" . $ip);
echo $rdata;
$ipdat = @json_decode($rdata);
echo $ipdat;
$output = @$ipdat->country_code;
return $output;
}
echo ip_info("Visitor", "country");
试试这个
function ip_info($ip = NULL, $deep_detect = TRUE) {
if ($ip == NULL || !filter_var($ip, FILTER_VALIDATE_IP)) {
$ip = $_SERVER["REMOTE_ADDR"];
if ($deep_detect) {
if (filter_var(@$_SERVER['HTTP_X_FORWARDED_FOR'], FILTER_VALIDATE_IP)){
$ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
}
if (filter_var(@$_SERVER['HTTP_CLIENT_IP'], FILTER_VALIDATE_IP)){
$ip = $_SERVER['HTTP_CLIENT_IP'];
}
}
}
$ch = curl_init("http://ip-api.com/json/".$ip);
curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, 5);
$result = curl_exec($ch);
curl_close($ch);
$result = json_decode($result, true);
if($result['status'] == "fail"){
$result = FALSE; /* If an Error has come back, you can use $result['message'] to get why. */
}
else { $result = $result['countryCode']; } // If Sucess
return $result;
}
我们昨天早上发生了停电事故,这可能是造成这种情况的原因。我已经测试了以下代码,它对我有用。如果您有任何问题,请告诉我。
function ip_info($ip = NULL, $deep_detect = TRUE) {
if ($ip == NULL || !filter_var($ip, FILTER_VALIDATE_IP)) {
$ip = $_SERVER["REMOTE_ADDR"];
if ($deep_detect) {
if (filter_var(@$_SERVER['HTTP_X_FORWARDED_FOR'], FILTER_VALIDATE_IP)){
$ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
}
if (filter_var(@$_SERVER['HTTP_CLIENT_IP'], FILTER_VALIDATE_IP)){
$ip = $_SERVER['HTTP_CLIENT_IP'];
}
}
}
$ch = curl_init("https://api.ipdata.co/".$ip);
curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, 5);
$result = curl_exec($ch);
curl_close($ch);
$result = json_decode($result, true);
$result = $result['country_code'];
return $result;
}
var_dump(ip_info('1.1.1.1'));
//string(2) "AU"