The almost missing Geocoder PHP library!

View the Project on GitHub geocoder-php/StackGeoIp

StackGeoIp

Geolocation Stack middleware that adds geolocation results to the request for subsequent middlewares by leveraging the Geocoder library.

Build
Status

Intallation

The recommended way to install StackGeoIp is through Composer:

{
    "require": {
        "geocoder-php/stack-geo-ip": "@stable"
    }
}

Protip: you should browse the geocoder-php/stack-geo-ip page to choose a stable version to use, avoid the @stable meta constraint.

Usage

Example

Here we create a simple application that returns the IP address of the request and the contents of the X-Country header to the browser. Normally, the X-Country header would not exists.

By wrapping the GeoIP middleware around it using the StackBuilder, if the IP address can be matched to a country, the X-Country header will be set to the two-letter code for that country, and be available to the application.

<?php

use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\RedirectResponse;

require __DIR__ . '/vendor/autoload.php';

$app = new \Silex\Application();

$app->get('/', function(Request $request) {
    $ip      = $request->getClientIp();
    $country = $request->headers->get('X-Country', 'UNKNOWN');

    return new Response($ip . ' => '. $country, 200);
});

$stack = (new \Stack\Builder())
    ->push('Geocoder\Stack\GeoIp')
    ;

$app = $stack->resolve($app);

$request  = Request::createFromGlobals();
$response = $app->handle($request)->send();
$app->terminate($request, $response);

Options

The following options can be used:

See the Geocoder documentation for a list of available adapters and providers.

License

StackGeoIp is released under the MIT License. See the bundled LICENSE file for details.