PHP code example of ipwhois / ipwhois-php

1. Go to this page and download the library: Download ipwhois/ipwhois-php 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/ */

    

ipwhois / ipwhois-php example snippets


$free = new \Ipwhois\IPWhois();               // Free plan — no API key
$paid = new \Ipwhois\IPWhois('YOUR_API_KEY'); // Paid plan — with API key



use Ipwhois\IPWhois;

$ipwhois = new IPWhois(); // no API key

$info = $ipwhois->lookup('8.8.8.8');

echo $info['country'] . ' ' . $info['flag']['emoji'] . PHP_EOL;
// → United States 🇺🇸

echo $info['city'] . ', ' . $info['region'] . PHP_EOL;
// → Mountain View, California



use Ipwhois\IPWhois;

$ipwhois = new IPWhois('YOUR_API_KEY'); // with API key

$info = $ipwhois->lookup('8.8.8.8');

echo $info['country'] . ' ' . $info['flag']['emoji'] . PHP_EOL;
// → United States 🇺🇸

echo $info['city'] . ', ' . $info['region'] . PHP_EOL;
// → Mountain View, California

use Ipwhois\IPWhois;

// Free plan
$ipwhois = (new IPWhois())
    ->setLanguage('en')
    ->setFields(['success', 'country', 'city', 'flag.emoji'])
    ->setTimeout(8);

use Ipwhois\IPWhois;

// Paid plan
$ipwhois = (new IPWhois('YOUR_API_KEY'))
    ->setLanguage('en')
    ->setFields(['success', 'country', 'city', 'flag.emoji'])
    ->setTimeout(8);

$ipwhois->lookup('8.8.8.8');                   // uses lang=en, the field whitelist, and timeout=8
$ipwhois->lookup('1.1.1.1', ['lang' => 'de']); // overrides lang for this single call only

use Ipwhois\IPWhois;

// Free plan
$ipwhois = new IPWhois(null, ['ssl' => false]);

use Ipwhois\IPWhois;

// Paid plan
$ipwhois = new IPWhois('YOUR_API_KEY', ['ssl' => false]);

$ipwhois = new IPWhois('YOUR_API_KEY');

$results = $ipwhois->bulkLookup([
    '8.8.8.8',
    '1.1.1.1',
    '208.67.222.222',
    '2c0f:fb50:4003::',   // IPv6 is fine — mix freely
]);

foreach ($results as $row) {
    if (($row['success'] ?? false) === false) {
        // Per-IP errors (e.g. "Invalid IP address") are returned inline,
        // they do NOT throw — the rest of the batch is still usable.
        echo "skip {$row['ip']}: {$row['message']}\n";
        continue;
    }
    echo "{$row['ip']} → {$row['country']}\n";
}

$info = $ipwhois->lookup('8.8.8.8');

if (!$info['success']) {
    error_log("Lookup failed: {$info['message']}");
    return;
}

echo $info['country'];

$info = $ipwhois->lookup('8.8.8.8');

if (!$info['success']) {
    if (($info['http_status'] ?? 0) === 429) {
        sleep($info['retry_after'] ?? 60);
        // …retry
    }
    if (($info['error_type'] ?? null) === 'network') {
        // DNS failure, connection refused, timeout, …
    }
    error_log("Error: {$info['message']}");
    return;
}
bash
composer