A PHP library for interfacing with IPStack Geo API

v1.5 2018-12-28 21:15 UTC


IPStack for PHP is a simple library used to interface with an IPStack Geo API.

Hint: IPStack for PHP is available through Composer. composer require nafisc/ipstackgeo-php.

Maintainability StyleCI TravisCI Latest Stable Version Total Downloads Latest Unstable Version License

Learn more about IPStack here:


  • Retrieve the Geo Location data for any IP address.
  • (Legacy) Link to a custom FreeGeoIP server

Example Usage

Note: See Location.php for a list of available properties on the Location object.

Create the GeoLookup object

use IPStack\PHP\GeoLookup;

$geoLookup = new GeoLookup(
    'acecac3893c90871c3', // API Key
    false,                // Use HTTPS (IPStack Basic plan and up only, defaults to false)
    10                    // Timeout in seconds (defaults to 10 seconds)

Lookup a location for an IP Address

Note: Locations are returned using a library called ExtendedArrays. This library gives us more options on how we access the properties of the location. See the Acessing Array Elements portion of the ExtendedArrays documentation for more information on this.

// Lookup a location for an IP Address
// and catch any exceptions that might
// be thrown by Guzzle or IPStack.
try {
    // Retrieve the location information for 
    // by using it's hostname.
    // This function will work with hostnames
    // or IP addresses.
    $location = $geoLookup->getLocationFor('');

    // You can alternately look up the information
    // for the current client's IP address.
    $location = $geoLookup->getClientLocation();

    // If we are unable to retrieve the location information
    // for an IP address, null will be returned.
    if ($location == null) {
        echo 'Failed to find location.'.PHP_EOL;
    } else {
        // Convert the location to a standard PHP array.

        // Any of these formats will work for 
        // retrieving a property.
        echo $location->latitude . PHP_EOL;
        echo $location['longitude'] . PHP_EOL;
        echo $location->region_name() . PHP_EOL;
} catch (\Exception $e) {
    echo $e->getMessage();

Using the the Legacy FreeGeoIP Binary

You can still use the legacy FreeGeoIP Binary hosted on a server

Note: FreeGeoIP has been deprecated.

use IPStack\PHP\Legacy\FreeGeoIp as GeoLookup;

// Address, Port, Protocol, Timeout
$geoLookup = new GeoLookup(
    'localhost', // Address hosting the legacy FreeGeoIP Binary
    8080,        // Port that the binary is running on (defaults to 8080)
    'http',      // Protocol to use (defaults to http)
    10           // Timeout (defaults to 10 seconds)