How to use IP2Location and IP2Location.io PHP SDKs in Slim

IP2Location and IP2Location.io PHP SDKs in Slim

Slim PHP is a micro framework for PHP that simplifies web application development, offering essential features like routing and middleware, making it ideal for small to medium-sized projects requiring efficient and streamlined code.

Slim PHP packages are reusable code modules that can be easily installed via Composer, a popular PHP package manager. Found on Packagist repository, they provide a convenient way to enhance and customize the capabilities of Slim applications.

IP2Location and IP2Location.io PHP SDKs

The IP2Location PHP package is a specialized software library that helps PHP developers obtain geolocation data from IP addresses.

The IP2Location PHP package utilizes the comprehensive IP2Location BIN database to provide a wide range of geographic information for IP addresses. It offers details including country, region, district, city, latitude, longitude, ZIP code, time zone, ISP, domain name, connection speed, IDD code, area code, weather station code, weather station name, MNC, MCC, mobile brand, elevation, usage type, address type, IAB category and ASN. It supports both IPv4 and IPv6 address lookups, making it suitable for various PHP projects.

Conversely, the IP2Location.io PHP SDK simplifies the integration of the IP2Location.io geolocation service into PHP applications. It enables easy retrieval of geolocation information through a RESTFUL API based on IP addresses. By utilizing the PHP SDK, developers can effortlessly incorporate IP geolocation functionality into their applications. They can retrieve information such as country, region, district, city, latitude, longitude, ZIP code, time zone, ASN, ISP, domain, net speed, IDD code, area code, weather station data, MNC, MCC, mobile brand, elevation, usage type, address type, advertisement category and proxy data. The SDK eliminates the need for manual HTTP requests and supports both IPv4 and IPv6 address lookups.

Getting Started

This tutorial will guide you through the process of using the IP2Location and IP2Location.io PHP SDKs with the Slim framework to retrieve geolocation information for the purpose of displaying it.

To begin with, we assumed that the Slim framework had been properly configured before proceeding with this tutorial. The IP2Location PHP SDK necessitates the use of a BIN database, but you can acquire a free database from https://lite.ip2location.com/. The IP2Location.io PHP SDK relies on an API key, which can be obtained by registering for a free account at https://www.ip2location.io/pricing. However, please note that continent, country, region, and city translations are only available in the Plus and Security Plans.

Display Geolocation Data Using IP2Location PHP SDK

  1. To obtain the package and incorporate it into the Slim platform, use the following command.
composer require ip2location/ip2location-php
  1. In any text editor, access the public/index.php file.
  2. Add the following codes into PHP files for utilizing the IP2Location PHP SDK and showcasing geolocation information:
<?php
use Psr\Http\Message\ResponseInterface as Response;
use Psr\Http\Message\ServerRequestInterface as Request;
use Slim\Factory\AppFactory;

// This is used to load the required classes and dependencies
require __DIR__ . '/../vendor/autoload.php';

//Create a new application instance using AppFactory.
$app = AppFactory::create();

//Define a route for the root to handle requests
$app->get('/', function (Request $request, Response $response, $args) {

    // Replace with the IP address you want to geolocate
    $ipAddress = "8.8.8.8";

    // Specify the path to the BIN database file
    $database = new \IP2Location\Database('path/to/your/IP2Location_BIN_DATABASE.BIN', \IP2Location\Database::FILE_IO);

    // Retrieve geolocation data
    $record = $database->lookup($ipAddress, \IP2Location\Database::ALL);

    // Create the HTML output
    $output = '<pre>';
    $output .= 'IP Number             : ' . $record['ipNumber'] . "\n";
    $output .= 'IP Version            : ' . $record['ipVersion'] . "\n";
    $output .= 'IP Address            : ' . $record['ipAddress'] . "\n";
    $output .= 'Country Code          : ' . $record['countryCode'] . "\n";
    $output .= 'Country Name          : ' . $record['countryName'] . "\n";
    $output .= 'Region Name           : ' . $record['regionName'] . "\n";
    $output .= 'City Name             : ' . $record['cityName'] . "\n";
    $output .= 'Latitude              : ' . $record['latitude'] . "\n";
    $output .= 'Longitude             : ' . $record['longitude'] . "\n";
    $output .= 'Area Code             : ' . $record['areaCode'] . "\n";
    $output .= 'IDD Code              : ' . $record['iddCode'] . "\n";
    $output .= 'Weather Station Code  : ' . $record['weatherStationCode'] . "\n";
    $output .= 'Weather Station Name  : ' . $record['weatherStationName'] . "\n";
    $output .= 'MCC                   : ' . $record['mcc'] . "\n";
    $output .= 'MNC                   : ' . $record['mnc'] . "\n";
    $output .= 'Mobile Carrier        : ' . $record['mobileCarrierName'] . "\n";
    $output .= 'Usage Type            : ' . $record['usageType'] . "\n";
    $output .= 'Elevation             : ' . $record['elevation'] . "\n";
    $output .= 'Net Speed             : ' . $record['netSpeed'] . "\n";
    $output .= 'Time Zone             : ' . $record['timeZone'] . "\n";
    $output .= 'ZIP Code              : ' . $record['zipCode'] . "\n";
    $output .= 'Domain Name           : ' . $record['domainName'] . "\n";
    $output .= 'ISP Name              : ' . $record['isp'] . "\n";
    $output .= 'Address Type          : ' . $record['addressType'] . "\n";
    $output .= 'Category              : ' . $record['category'] . "\n";
    $output .= 'District              : ' . $record['district'] . "\n";
    $output .= 'ASN                   : ' . $record['asn'] . "\n";
    $output .= 'AS                    : ' . $record['as'] . "\n";
    $output .= '</pre>';

    // Set the response body
    $response->getBody()->write($output);

    return $response;
});

//Execute the application and handle requests
$app->run();
?>
  1. Initiate a web server by executing the following command in the CLI from your project directory:
php -S localhost:8000 -t public
  1. Now you can view the Slim application by opening your browser and visiting “http://localhost:8000”. The webpage will show the IP geolocation information obtained from the IP2Location BIN database.
  2. Done.

Display Geolocation Data Using IP2Location.io PHP SDK

  1. To obtain the package and incorporate it into the Slim platform, use the following command.
composer require ip2location/ip2location-io-php
  1. In any text editor, access the public/index.php file.
  2. Add the following codes into PHP files for utilizing the IP2Location.io PHP SDK and showcasing geolocation information:
<?php
use Psr\Http\Message\ResponseInterface as Response;
use Psr\Http\Message\ServerRequestInterface as Request;
use Slim\Factory\AppFactory;

// This is used to load the required classes and dependencies
require __DIR__ . '/../vendor/autoload.php';

//Create a new application instance using AppFactory
$app = AppFactory::create();

//Define a route for the root to handle requests
$app->get('/', function (Request $request, Response $response, $args) {
    // Replace with your actual API key
    $apiKey = "YOUR_API_KEY";

    // Replace with the IP address you want to geolocate
    $ipAddress = "8.8.8.8";

    // This class represents the configuration for the IP2Location.io API
    $config = new \IP2LocationIO\Configuration($apiKey);

    // This class is used to perform the geolocation lookup
    $ip2locationio = new IP2LocationIO\IPGeolocation($config);

    // Sends a request to the IP2Location.io API to retrieve the geolocation information
    $responses = $ip2locationio->lookup($ipAddress);

    try {
        $output =  '<pre>';
        $output .=  'IP Address           : ' . $responses->ip . "<br>";
        $output .=  'Country Code         : ' . $responses->country_code . "<br>";
        $output .=  'Country Name         : ' . $responses->country_name . "<br>";
        $output .=  'Region Name          : ' . $responses->region_name . "<br>";
        $output .=  'City Name            : ' . $responses->city_name . "<br>";
        $output .=  'City Latitude        : ' . $responses->latitude . "<br>";
        $output .=  'City Longitude       : ' . $responses->longitude . "<br>";
        $output .=  'ZIP Code             : ' . $responses->zip_code . "<br>";
        $output .=  'Time Zone            : ' . $responses->time_zone . "<br>";
        $output .=  'ASN                  : ' . $responses->asn . "<br>";
        $output .=  'AS                   : ' . $responses->as . "<br>";
        $output .=  'Is Proxy             : ';
        $output .=  ($responses->is_proxy) ? 'TRUE' : 'FALSE'; $output .=  "<br>";
        $output .=  'ISP Name             : ' . ($responses->isp ?? 'FIELD NOT SUPPORTED') . "<br>";
        $output .=  'Domain Name          : ' . ($responses->domain ?? 'FIELD NOT SUPPORTED') . "<br>";
        $output .=  'Net Speed            : ' . ($responses->net_speend ?? 'FIELD NOT SUPPORTED') . "<br>";
        $output .=  'IDD Code             : ' . ($responses->idd_code ?? 'FIELD NOT SUPPORTED') . "<br>";
        $output .=  'Area Code            : ' . ($responses->area_code ?? 'FIELD NOT SUPPORTED') . "<br>";
        $output .=  'Weather Station Code : ' . ($responses->weather_station_code ?? 'FIELD NOT SUPPORTED') . "<br>";
        $output .=  'Weather Station Name : ' . ($responses->weather_station_name ?? 'FIELD NOT SUPPORTED') . "<br>";
        $output .=  'MCC                  : ' . ($responses->mcc ?? 'FIELD NOT SUPPORTED') . "<br>";
        $output .=  'MNC                  : ' . ($responses->mnc ?? 'FIELD NOT SUPPORTED') . "<br>";
        $output .=  'Mobile Carrier       : ' . ($responses->mobile_brand ?? 'FIELD NOT SUPPORTED') . "<br>";
        $output .=  'Elevation            : ' . ($responses->elevation ?? 'FIELD NOT SUPPORTED') . "<br>";
        $output .=  'Usage Type           : ' . ($responses->usage_type ?? 'FIELD NOT SUPPORTED') . "<br>";
        $output .=  'Address Type         : ' . ($responses->address_type ?? 'FIELD NOT SUPPORTED') . "<br>";
        $output .=  'Category Code        : ' . ($responses->ads_category ?? 'FIELD NOT SUPPORTED') . "<br>";
        $output .=  'Category Name        : ' . ($responses->ads_category_name ?? 'FIELD NOT SUPPORTED') . "<br>";
        $output .=  'District Name        : ' . ($responses->district ?? 'FIELD NOT SUPPORTED') . "<br>";
        if (isset($responses->continent)) {
            $output .=  'Continent Name        : ' . $responses->continent->name . "<br>";
            $output .=  'Continent Code        : ' . $responses->continent->code . "<br>";
            $output .=  'Continent Hemisphere  : ' . (implode(", ", $responses->continent->hemisphere)) . "<br>";
            $output .=  'Continent Translation : ' . $responses->continent->translation->value . ' (' . $responses->continent->translation->lang . ')' . "<br>";
        }
        if (isset($responses->country)) {
            $output .=  'Country Name          : ' . $responses->country->name . "<br>";
            $output .=  'Country Alpha 3 Code  : ' . $responses->country->alpha3_code . "<br>";
            $output .=  'Country Numeric Code  : ' . $responses->country->numeric_code . "<br>";
            $output .=  'Country Demonym       : ' . $responses->country->demonym . "<br>";
            $output .=  'Country Flag          : ' . $responses->country->flag . "<br>";
            $output .=  'Country Capital       : ' . $responses->country->capital . "<br>";
            $output .=  'Country Total Area    : ' . $responses->country->total_area . "<br>";
            $output .=  'Country Population    : ' . $responses->country->population . "<br>";
            $output .=  'Country Currency Code : ' . $responses->country->currency->code . "<br>";
            $output .=  'Country Currency Name : ' . $responses->country->currency->name . ' (' . $responses->country->currency->symbol . ')' . "<br>";
            $output .=  'Country Language      : ' . $responses->country->language->name . ' (' . $responses->country->language->code . ')' . "<br>";
            $output .=  'Country TLD           : ' . $responses->country->tld . "<br>";
            $output .=  'Country Translation   : ' . $responses->country->translation->value . ' (' . $responses->country->translation->lang . ')' . "<br>";
        }
        if (isset($responses->region)) {
            $output .=  'Region Name        : ' . $responses->region->name . "<br>";
            $output .=  'Region Code        : ' . $responses->region->code . "<br>";
            $output .=  'Region Translation : ' . $responses->region->translation->value . ' (' . $responses->region->translation->lang . ')' . "<br>";
        }
        if (isset($responses->city)) {
            $output .=  'City Name        : ' . $responses->city->name . "<br>";
            $output .=  'City Translation : ' . $responses->city->translation->value . ' (' . $responses->city->translation->lang . ')' . "<br>";
        }
        if (isset($responses->time_zone_info)) {
            $output .=  'Olson Time Zone : ' . $responses->time_zone_info->olson . "<br>";
            $output .=  'Current Time    : ' . $responses->time_zone_info->current_time . "<br>";
            $output .=  'GMT Offset      : ' . $responses->time_zone_info->gmt_offset . "<br>";
            $output .=  'Is DST          : '; $output .=  ($responses->time_zone_info->is_dst) ? 'TRUE' : 'FALSE'; $output .=  "<br>";
            $output .=  'Sunrise Time    : ' . $responses->time_zone_info->sunrise . "<br>";
            $output .=  'Sunset Time     : ' . $responses->time_zone_info->sunset . "<br>";
        }
        if (isset($responses->geotargeting)) {
            $output .=  'Metro Code : ' . $responses->geotargeting->metro . "<br>";
        }
        if (isset($responses->proxy)) {
            $output .=  'Proxy Last Seen : ' . $responses->proxy->last_seen . "<br>";
            $output .=  'Proxy Type      : ' . $responses->proxy->proxy_type . "<br>";
            $output .=  'Proxy Threat    : ' . $responses->proxy->threat . "<br>";
            $output .=  'Proxy Provider  : ' . $responses->proxy->provider . "<br>";
        }
        $output .=  '</pre>';

        // Set the response body
        $response->getBody()->write($output);
        return $response;

    }catch (Exception $e) {
        $response->getBody()->write("Error: " . $e->getMessage());
        return $response;
    }
});

//Execute the application and handle requests
$app->run();
?>
  1. Initiate a web server by executing the following command in the CLI from your project directory:
php -S localhost:8000 -t public
  1. Now you can view the Slim application by opening your browser and visiting “http://localhost:8000”. The webpage will show the IP geolocation information obtained from the IP2Location.io API.
  2. Done.

By the end of this tutorial, you will gain the ability to perform an IP geolocation lookup using the IP2Location and IP2Location.io PHP SDKs within the Slim framework. This will allow you to retrieve geolocation data that can be utilized to determine the geographical details of users and applied in data analysis.

Learn more on how to use IP2Location.io PHP SDK in various frameworks.

Was this article helpful?

Related Articles