Skip to content

nathan-fiscaletti/ipstackgeo-php

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

36 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

IPStack for PHP (Geo Location Library)

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.

StyleCI TravisCI Latest Stable Version Total Downloads Latest Unstable Version License

Learn more about IPStack here: ipstack.net

Features

  • 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 
    // github.com by using it's hostname.
    // 
    // This function will work with hostnames
    // or IP addresses.
    $location = $geoLookup->getLocationFor('github.com');

    // 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.
        print_r($location->_asStdArray());

        // 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\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)
);