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
.
Learn more about IPStack here: ipstack.net
- Retrieve the Geo Location data for any IP address.
- (Legacy) Link to a custom FreeGeoIP server
Note: See Location.php for a list of available properties on the Location 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)
);
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
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)
);