Skip to content

Instantly share code, notes, and snippets.

@luckyshot
Last active November 13, 2020 17:58
Show Gist options
  • Save luckyshot/2a6a59070803536a6651 to your computer and use it in GitHub Desktop.
Save luckyshot/2a6a59070803536a6651 to your computer and use it in GitHub Desktop.
PHP - Geolocalization by IP address
<?php
define('GEOIP_CACHE_TIME', 5184000); // 5184000 = 60 days
/**
* Returns the country of an IP address
* If IP is cached and less than 2 months old, otherwhise requests it to geoplugin.com API
*
* @string $ip The IP address
* @bool $justcountry If you want the full array or just the country
* @returns The two-letter country, array with all data if $justcountry=false or false if nothing found
*/
public function geoIp( $ip = '', $justcountry = true )
{
if ( $ip == '' )
{
$ip = $_SERVER['REMOTE_ADDR'];
}
if ( !filter_var( $ip, FILTER_VALIDATE_IP ) )
{
return false;
}
$file = CACHE_PATH . $ip . '.json';
if ( file_exists( $file ) && time() < filemtime( $file ) + GEOIP_CACHE_TIME )
{
$data = include( $file );
}
else
{
$data = @json_decode( file_get_contents('http://www.geoplugin.net/json.gp?ip=' . $ip), true );
if ( !is_array( $data ) )
{
return false;
}
file_put_contents( $file, '<?php return ' . var_export( $data, true ) . ';' );
}
if ( $justcountry == false )
{
return $data;
}
else
{
return $data['geoplugin_countryCode'];
}
return false;
}
/**
* Examples
*/
if ( geoIp() == 'ES' )
{
// Visitor is from Spain
}
// User's currency
$data = geoIp( '89.140.161.225', true );
echo 'User currency is ' . $data['geoplugin_currencyCode'] . '.';
// Full Response Example
/*
{
"geoplugin_request":"89.140.161.225",
"geoplugin_status":200,
"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":"Barcelona",
"geoplugin_region":"Catalonia",
"geoplugin_areaCode":"0",
"geoplugin_dmaCode":"0",
"geoplugin_countryCode":"ES",
"geoplugin_countryName":"Spain",
"geoplugin_continentCode":"EU",
"geoplugin_latitude":"41.3853",
"geoplugin_longitude":"2.1774",
"geoplugin_regionCode":"56",
"geoplugin_regionName":"Catalonia",
"geoplugin_currencyCode":"EUR",
"geoplugin_currencySymbol":"&#8364;",
"geoplugin_currencySymbol_UTF8":"\u20ac",
"geoplugin_currencyConverter":0.8018
};
*/
@emresaracoglu
Copy link

Thank you!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment