0👍
I use a couple of services to get a country code. If one doesn’t work for some reason (e.g. limit exceeded) it tries the next service:
/**
* Make cUrl request.
*/
private static function _getCurl(string $url, int $timeout = 400):?string {
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT_MS, $timeout); // If it takes too long just try the next api
curl_setopt($ch, CURLOPT_TIMEOUT_MS, $timeout);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$output = curl_exec($ch);
curl_close($ch);
return $output;
}
/**
* Try to get the country code of the current user based on it's ip.
*/
public static function getCountryCode():?string {
// https://hostip.info/ - unlimited? requests per day
// https://ipinfo.io/ - 1000 requests per day
// https://ipdata.co/ - 1500 requests per day
// https://ipstack.com/ - 10000 requests per month (not used at the moment)
// Get country code:
$ip = $_SERVER['HTTP_CLIENT_IP']);
$countryCode = null;
if (!$countryCode) { // Try hostip.info
try {
$output = self::_getCurl('https://api.hostip.info/get_json.php?ip=' . $ip);
$output = json_decode($output);
$countryCode = ($output->country_code == 'XX') ? null : $output->country_code;
}
catch (Throwable $t) {}
}
if (!$countryCode) { // Try ipinfo.io
try {
$output = self::_getCurl('http://ipinfo.io/' . $ip . '/json?token=[ipinfo.io TOKEN HERE]');
$output = json_decode($output);
$countryCode = ($output->country == 'XX') ? null : $output->country;
}
catch (Throwable $t) {}
}
if (!$countryCode) { // Try ipdata.co
try {
$output = self::_getCurl('https://api.ipdata.co/' . $ip . '?api-key=[ipdata.co TOKEN HERE]');
$output = json_decode($output);
$countryCode = ($output->country_code == 'XX') ? null : $output->country_code;
}
catch (Throwable $t) {}
}
return $countryCode;
}
It’s a cut past from a larger class so you might need do some adjusting here and there.
ipinfo.io and ipdata.co need api tokens, so you need to get those from their sites first (both are free).
- [Vuejs]-Creating a custom Markdown-it plugin for Nuxt application results in TypeError when rendering in browser
- [Vuejs]-Vue with Web Component "is" Attribute
Source:stackexchange.com