Skip to content

Instantly share code, notes, and snippets.

@elhardoum
Last active February 6, 2020 12:40
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save elhardoum/081821491e8f58a35fd9c56c7798ea7f to your computer and use it in GitHub Desktop.
Save elhardoum/081821491e8f58a35fd9c56c7798ea7f to your computer and use it in GitHub Desktop.
<?php
/**
* Get the user country code with package
*
* Requires geoiplookup package installed
* @link http://manpages.ubuntu.com/manpages/trusty/man1/geoiplookup.1.html
* @param $ip user IP string
* @param $args Array (optional parameters)
*/
function geoiplookup($ip, $args=null) {
ob_start();
system(sprintf('geoiplookup %s | sed -e "s/geoip country edition://I"', escapeshellarg($ip)));
$raw = trim(ob_get_clean());
if ( in_array('code', (array) $args) ) {
// get only code
preg_match('/[a-zA-Z]+,/si', $raw, $m);
$code = array_shift($m);
$c = preg_replace('/\,$/si', '', $code);
} else if ( !in_array('full', (array) $args) ) {
// get only name
preg_match('/[a-zA-Z]+,(.*)/si', $raw, $m);
$c = array_pop($m);
} else {
$c = $raw;
}
return trim($c);
}
// usage
geoiplookup('23.66.166.151');
// United States
geoiplookup('23.66.166.151', 'code');
// US
geoiplookup('23.66.166.151', 'full');
// US, United States
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment