PHP code example of germania-kg / ipstack

1. Go to this page and download the library: Download germania-kg/ipstack library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

germania-kg / ipstack example snippets



use Germania\IpstackClient\IpstackClient;

// Setup the Client
$endpoint  = "http://api.ipstack.com/";
$api_key   = "your_api_key";
$ipstack   = new IpstackClient( $endpoint, $api_key);

// Ask ipstack
$client_ip = "8.8.8.8";
$response  = $ipstack->get( $client_ip );

$response = $ipstack->get( "8.8.8.8", array(
  'language' => "de",
  'fields'   => "ip,country_code,country_name,latitude,longitude,region_name"
));


use Germania\IpstackClient\IpstackClientPsr6CacheDecorator;
use Germania\IpstackClient\IpstackClient;
use Stash\Pool as CacheItemPool;

// Setup your client as shown above
$ipstack = new IpstackClient( $endpoint, $api_key);

// Example cache 
$cache   = new \Stash\Pool(
  new \Stash\Driver\Sqlite( array('path' => "/tmp" ))
);

// Setup the decorator
$caching_ipstack = new IpstackClientPsr6CacheDecorator($ipstack, $cache);

// Optional: Set lifetime in seconds (or null)
$caching_ipstack->setCacheLifeTime( 3600 );

// Use as usual
$response = $caching_ipstack->get( "8.8.8.8" );


use Germania\IpstackClient\IpstackMiddleware;

// Setup your client as shown above
$ipstack = new IpstackClient( $endpoint, $api_key);

// The middleware:
$ipstack_middleware = new IpstackMiddleware( $ipstack );

// Setup Slim app
$app = new \Slim\App;
$app->add( $ipstack_middleware );


$ipstack_attr = $request->getAttribute( "ipstack" );

echo $ipstack_attr['ip'];
echo $ipstack_attr['country_code'];
echo $ipstack_attr['country_name'];


use RKA\Middleware\IpAddress as IpAddressMiddleware;
use Germania\IpstackClient\IpstackMiddleware;

// Setup Slim app
$app = new \Slim\App;

// Executed second
$ipstack_middleware = new IpstackMiddleware( $ipstack, "ip_address" );
$app->add( $ipstack_middleware );

// Executed first
$checkProxyHeaders = true; // Note: Never trust the IP address for security processes!
$trustedProxies = ['10.0.0.1', '10.0.0.2']; // example
$akrabats_middleware = new IpAddressMiddleware($checkProxyHeaders, $trustedProxies);
$app->add( $akrabats_middleware );


use Germania\IpstackClient\IpstackExceptionInterface;
use Germania\IpstackClient\IpstackRequestException;
use Germania\IpstackClient\IpstackResponseException;

try {
  $ipstack = new IpstackClient( $endpoint, $api_key);
  $response = $ipstack->get( $client_ip );
}
catch( IpstackExceptionInterface $e ) {

  // a) IpstackResponseException
  // b) IpstackRequestException 
  echo $e->getMessage();
  echo $e->getCode();  
  
  // to get Guzzle's original exception:
  $original_guzzle_exception = $e->getPrevious();
}