PHP code example of gpslab / geoip2

1. Go to this page and download the library: Download gpslab/geoip2 library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

gpslab / geoip2 example snippets


use GeoIp2\Database\Reader;

// get a GeoIP2 reader
$reader = $this->get(Reader::class);
// or
//$reader = $this->get('geoip2.reader');

// get a GeoIP2 City model
$record = $reader->city('128.101.101.101');

print($record->country->isoCode . "\n"); // 'US'
print($record->country->name . "\n"); // 'United States'
print($record->country->names['zh-CN'] . "\n"); // '美国'

print($record->mostSpecificSubdivision->name . "\n"); // 'Minnesota'
print($record->mostSpecificSubdivision->isoCode . "\n"); // 'MN'

print($record->city->name . "\n"); // 'Minneapolis'

print($record->postal->code . "\n"); // '55455'

print($record->location->latitude . "\n"); // 44.9733
print($record->location->longitude . "\n"); // -93.2323

// get a GeoIP2 reader for City database
$default_reader = $this->get('geoip2.database.default_reader');
// or
//$default_reader = $this->get(Reader::class);
// or
//$default_reader = $this->get('geoip2.reader');

// get a GeoIP2 reader for Country database
$country_reader = $this->get('geoip2.database.country_reader');

// get a GeoIP2 reader for ASN database
$asn_reader = $this->get('geoip2.database.asn_reader');

// get a GeoIP2 reader for City database
$default_reader = $this->get('geoip2.database.city_reader');
// or
//$default_reader = $this->get(Reader::class);
// or
//$default_reader = $this->get('geoip2.reader');

use GpsLab\Bundle\GeoIP2Bundle\Reader\ReaderFactory;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;

class GeoIPController
{
    public function index(Request $request, ReaderFactory $factory): Response
    {
        $client_locale = $request->getLocale();
        $client_ip = $request->getClientIp();
        $database_name = 'default';
        $fallback_locale = 'en';
    
        $reader = $factory->create($database_name, [$client_locale, $fallback_locale]);
        $record = $reader->city($client_ip);
    
        return new Response(sprintf('You are from %s?', $record->country->name));
    }
}

composer req splitbrain/php-archive