maxmindgeoip2

Maxmind GeoIP2 tutorial (How-to)?


I used GeoIp, with pure PHP codes.. but GeoIp2 become namespaced and etc, and at this moment i couldnt find out how to use that.. i have downloaded GeoLite2-Country.mmdb, and now how to get the country name for IP, i.e. 123.123.123.123.

p.s. I dont have GIT/COMPOSER or etc..


Solution

  • How i did it: let's say, create a folder named "My_Folder" and inside it:

    1) create folder GeoIp2 and put in it content of this "SRC" folder (download).
    2) put MaxMind folder (download, from "SRC" folder).
    3) place i.e. GeoLite2-Country.mmdb (download).

    then, in My_Folder create a example.php file and put this code:

    $user_ip='123.123.123.123';
    
    spl_autoload_register('func888'); function func888($class){ include_once(str_replace(array('/','\\'), DIRECTORY_SEPARATOR, dirname(__file__)."/$class.php")) ;}
    use GeoIp2\Database\Reader; 
    //you can do it for "city" too.. just everywhere change phrase "country" with "city".
    try{
        $reader = new Reader(dirname(__file__)."/GeoLite2-Country.mmdb");
        $record = $reader->country($user_ip);
        $reader->close();
        $country_name =  $record->raw['country']['names']['en'];
    } catch ( GeoIp2\Exception\AddressNotFoundException $e ){    $country_name = 'not_found';  }
    
    echo $country_name;
    // RESULTS -------------- > China
    

    p.s. other examples found at:https://github.com/maxmind/GeoIP2-php