Hi, freegeoip.net is no longer going to work stable. My question is what alternative can be used? I use geolocation to pay users.
I believe CloudFlare can provide user's location in a custom HTTP header. Not only it will be stable, it'll also be much faster (as you won't need extra http request to external service).
If this doesn't work for you, you can use the
other geo-location service I mentioned a page back in this way:
$countryCode = json_decode(file_get_contents('http://geoip.nekudo.com/api/' . getIP()))->country->code;
I'm not sure but Remote addr won't work with cloudflare. I had the problem and it worked with x-forwarded for.
Remote address return the ip of the cloudflare server.
You may look
here minifrij's example uses getIP() which can handle that (and does that securely). The problem here isn't getting the IP itself, but getting the geographical location of user.
Well, in one of my project I use to get the country of the user an with php function and an api.
The PHP function (from
here)
function get_ip()
{
if (isset($_SERVER['HTTP_X_FORWARDED_FOR']) && $_SERVER['HTTP_X_FORWARDED_FOR']) {
$ipList = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);
$_SERVER['HTTP_X_FORWARDED_FOR'] = array_pop($ipList);
} else {
$_SERVER['HTTP_X_FORWARDED_FOR'] = false;
}
if (filter_var($_SERVER['HTTP_X_FORWARDED_FOR'], FILTER_VALIDATE_IP, FILTER_FLAG_IPV4)) {
return $_SERVER['HTTP_X_FORWARDED_FOR'];
} else {
return $_SERVER['REMOTE_ADDR'];
}
return $_SERVER['REMOTE_ADDR'];
}
And the PHP API
$location = unserialize(file_get_contents('http://www.geoplugin.net/php.gp?ip='.get_ip()));
echo strtolower($location['geoplugin_countryCode']); // if you come from russian, you get: ru
It returns 'ru' if you are russian.
The API works on my site although remote_addr don't work. The function checks if ip from $_SERVER['REMOTE_ADDR'] is valid, if not it get the IP from $_SERVER['HTTP_X_FORWARDED_FOR'].