Skip to content
internetdataPublic

About

Official PHP client library for the InternetData API: look up any IP address, AS or domain, and download the databases.

Topics

Resources

Security policy

Stars

1 star

Watchers

1 watching

Forks

Repository files navigation

InternetData InternetData PHP Client Library

Packagist license

The official PHP client library for the InternetData API.

It looks up what every InternetData database says about an IP address, an AS or a domain, and downloads and verifies the databases your organization is licensed for.

Getting Started

composer require internetdata/internetdata

Requires PHP 8.2 or newer. Everything is typed, and the fields a plan leaves out are nullable so an absent answer never reads as a false one.

Usage

Start with a free API key, no card needed: create one in the console and pass it in. A free key answers the basics on its organization's quota: the Tor, relay and anycast flags, the hostname, location to the country and asn without its type, an AS's registry row, and a domain's registration and record-type flags. Past the quota, each lookup raises quota_exceeded until the quota resets. The Data plan answers every field, the company and its abuse contact, the VPN and proxy flags, the city, WHOIS, the services and a domain's records among them, at the volume you need (pricing).

use InternetData\Client;
use InternetData\Options;

$client = new Client(new Options(apiKey: getenv('INTERNETDATA_API_KEY') ?: null));

$result = $client->lookup('146.70.116.130');
echo $result->location->country;   // AT
echo $result->asn->name;           // M247 Europe SRL

On a paid plan

A paid plan answers every field: the address's company and abuse contact, the VPN, proxy, hosting, CDN, bot, carrier, satellite and service flags as well, the detail behind each flag, the AS's type, the city, both Whois records and how many domains an address hosts. The same call then carries them:

$result = $client->lookup('146.70.116.130');
$result->company?->name;       // 'M247 LTD Vienna Infrastructure', on a paid plan
$result->abuse?->email;        // 'abuse@m247.ro', on a paid plan
$result->isVpn;                // true, on a paid plan
$result->vpn->providerName;    // 'Mullvad', on a paid plan
$result->location->city;       // 'Vienna', on a paid plan
$result->bot->agents;          // ['Googlebot'] for a crawler's address, on a paid plan

isIspproxy and ispproxy are paid members too: an ISP proxy, a proxy server in a datacenter on address space an internet service provider registers or announces, so you can treat it apart from a datacenter proxy. ispproxy names the provider, the firstSeen and lastSeen days and a confidence of high, medium or low.

An AS or a domain

$as = $client->lookupAsn(9009);
echo $as->name;          // M247 Europe SRL
echo $as->allocated;     // 2005-06-06
$as->prefixes;           // what it announces, on a paid plan

$domain = $client->lookupDomain('example.com');
$domain->isRegistered;   // true
$domain->hasMx;          // whether it has MX records
$domain->dns->mx;        // the records themselves, on a paid plan
$domain->web->title;     // its home page's title, on a paid plan

A paid plan also adds the network behind each of its addresses (hosting), the other domains on its first IPv4 address (reverseIp), the domains using it as their nameserver or mail server (reverseNs, reverseMx), the company IP Company names by it (company), and the domains whose home pages redirect or link to it (redirects, backlinks). reverseIp replaces cohostedDomains, which is deprecated and served beside it until the next major version.

An address's answer carries its reverseIp and an AS's its reverseAsn, each replacing the deprecated hostedDomains the same way.

Unlike an address, an AS or a domain is never cached and has no batch. lookup takes an IP address alone, and refuses anything else as a bad_request before sending it.

Your own address

$result = $client->myIp();
echo $result->ip;   // the address we saw this call come from

Same answer lookup would give for that address, and the same cost against your quota. It is deliberately not cached: which address you are is the whole question, and a machine that moves between networks would otherwise be told where it used to be.

Your plan and usage

$acct = $client->myEntitlement();
echo $acct->plan->key;          // the plan your organization is on
echo $acct->plan->name;         // its name to show, "Free" on free
echo $acct->usage->requests;    // 580
echo $acct->usage->windowEnd->format('c');   // when the quota resets

Usage counts against your organization's quota, from windowStart to windowEnd: the same number a lookup is gated on. hardLimit is where answers stop (on the free plan, the quota); null means never, the normal state of a paid plan with no overage cap, which is not the same as zero.

Batch lookup

Look up many addresses at once. Bogons and cached answers are handled locally, and everything else goes to the batch endpoint in chunks of up to 1000 addresses, in parallel. The batch endpoint needs a paid plan:

use InternetData\InternetDataException;

$results = $client->lookupBatch(['146.70.116.130', '8.8.8.8', '1.1.1.1']);

foreach ($results as $ip => $result) {
    if ($result instanceof InternetDataException) {
        echo "{$ip}: {$result->getMessage()}\n";
        continue;
    }
    echo "{$ip}: {$result->location->country}\n";
}

Results are keyed by address, in the order you first listed each one, so duplicates in your list collapse into a single entry and one address failing never loses the rest: it carries its error as its value, with the status the API would have given that address on its own. An address past the organization's quota carries a quota_exceeded error as its value, and one whose answer carries capReached true (none does today) a CapReachedException, with its result, below.

There's no limit on how many addresses you pass. How many chunks are in flight at once, how many times a failed chunk is retried, and how long each attempt may take are configurable per call:

$results = $client->lookupBatch($manyIps, ['concurrency' => 4, 'retries' => 4, 'timeout' => 10]);

Is that crawler really who it says?

Pass the User-Agent of the request you are deciding on, and on a paid plan the answer says whose bot it names and whether this address bears that out: verified, spoofed, unverifiable or not_bot. A free key's answer never carries it, and userAgent is then null. A batch takes one agent per address, keyed as you pass the address:

$result = $client->lookup('66.249.66.1', ['userAgent' => $_SERVER['HTTP_USER_AGENT'] ?? '']);

if ($result->userAgent?->verdict === 'spoofed') {
    // Claims to be a crawler its operator does not run from here.
}

$results = $client->lookupBatch(['66.249.66.1', '146.70.116.130'], [
    'userAgents' => ['66.249.66.1' => 'Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)'],
]);

myIp takes userAgent too. An empty agent is none. An answer with an agent is cached apart from the address's plain answer and from another agent's, and a private or reserved address is still answered locally, with no userAgent. A verdict the API adds later is read as it is served.

Caching

Answers are cached by default, so repeat lookups of the same address are free:

$client = new Client(new Options(apiKey: getenv('INTERNETDATA_API_KEY') ?: null));

$result = $client->lookup('146.70.116.130');   // API request
$result2 = $client->lookup('146.70.116.130');  // no API request, result was cached

You can change the default cache variables (max size, TTL in seconds, etc) on initialization, or even disable it:

$client = new Client(new Options(apiKey: $key, cacheMaxSize: 50_000, cacheTtlSeconds: 6 * 60 * 60));
$clientNoCache = new Client(new Options(apiKey: $key, cache: false));

An answer that carries capReached true (none does today) is cached for a minute at most, in memory and in a cacheStore, and every hit raises again.

The cache lives on the client instance, so how much it buys you depends on how long that instance lives. A worker, a queue consumer or a long-running server gets the full benefit. Under PHP-FPM or mod_php the client is built for every request, so give it a PSR-16 cache that outlives the request, such as your framework's:

$client = new Client(new Options(apiKey: $key, cacheStore: $cache));

Entries are keyed by a hash of your API key, the base URL and the address, so two keys never share an answer, and they live cacheTtlSeconds. The store's own eviction takes the place of cacheMaxSize, and a store that fails is a miss, never a failed lookup. internetdata/symfony and internetdata/laravel wire the framework's cache for you.

Private and reserved addresses

Private, loopback, link-local, documentation and multicast addresses (and their IPv6 equivalents, including the 6to4 and Teredo ranges) aren't on the public internet. The library answers them locally, so they cost no request and no quota:

$result = $client->lookup('192.168.1.1');
$result->isBogon;   // true, this answer was computed rather than served
$result->isVpn;     // false

The check is available on the client, which is handy when your inputs are addresses anyway:

$client->isBogon('10.0.0.1');   // true
$client->isBogon('8.8.8.8');    // false

It is also callable on its own, if you want it without a client:

use InternetData\Bogon;

Bogon::isBogon('10.0.0.1');   // true

Errors

Failures throw an InternetDataException carrying a kind and an isRetryable() flag:

use InternetData\InternetDataException;

try {
    $client->lookup('1.1.1.1');
} catch (InternetDataException $err) {
    echo $err->kind->value, ' ', $err->isRetryable() ? 'retryable' : 'final', "\n";
}

kind is one of bad_request, unauthorized, forbidden, rate_limited, quota_exceeded, server_error or network. The message is the API's own, and a database call's is its result code, so a refusal says which refusal it was: NOT_LICENSED and LICENSE_EXPIRED are both a forbidden, and only one of them is fixed by renewing.

Note that rate_limited and quota_exceeded both arrive as HTTP 429 and are not the same thing. A rate limit is when the API faces extreme traffic bursts and so retrying later works; but a 429 without Retry-After is quota_exceeded: the organization's quota is spent (or a paid key's overage cap is reached), and it lasts until the quota resets, so the library never retries it. A proxy in between can send one too. The database API has no quota, so you won't see quota_exceeded from it.

A spent quota

The API answers a spent quota with a 429, raised as quota_exceeded. An answer that carries cap_reached true (none does today) raises CapReachedException, kind quota_exceeded, with the answer as result, so an integration never runs on without the fields it was built on:

use InternetData\CapReachedException;
use InternetData\ErrorKind;
use InternetData\InternetDataException;

try {
    $result = $client->lookup('146.70.116.130');
} catch (CapReachedException $e) {
    $result = $e->result;   // the answer that carried cap_reached
} catch (InternetDataException $e) {
    if ($e->kind === ErrorKind::QuotaExceeded) {
        // The quota is spent until it resets, and the library does not retry it.
    }
}

The AS and domain lookups and myIp raise CapReachedException too, with an AsnResult, a DomainResult or a Result, and so does a cache hit. In a batch the address's value is the exception and the batch returns. A private or reserved address never raises, and no option turns it off: catching it is the way to carry on.

Timeouts and retries

Each attempt gives up after 30 seconds, and a transient failure is retried twice. Both can be changed for the client, and for a single lookup:

$client = new Client(new Options(apiKey: $key, timeout: 10, retries: 4));

$result = $client->lookup('146.70.116.130', ['timeout' => 2.5, 'retries' => 0]);

The timeout is in seconds and applies to each attempt, so a retried call can take longer in total. An attempt that runs out of time fails as a retryable network error. A database download isn't bound by it, since a large file takes as long as it takes.

Database downloads

Every database call needs a key carrying the db.download scope, which you create in the console. The Open databases are licensed to every organization from the start and are free under CC BY-SA 4.0, and list() marks them open. The rest are licensed by contract; if your organization doesn't have a license yet, request an evaluation. Then:

foreach ($client->database->list() as $database) {
    echo "{$database->base}: {$database->standing}\n";   // bogon_ip: licensed
}

Every database call hangs off $client->database, which is where the sibling VPNDetection library keeps the same seven calls.

A license is held against a database FAMILY, while a download names one version, so the IDs you pass everywhere else come from versions:

$database->base;                    // 'bogon_ip'
$database->versions[0]->id;         // 'bogon_ip_v1', the ID a download takes
$database->versions[0]->formats;    // ['csvgz', 'mmdb']
$database->licenseType;             // 'standard', or null when there is no license

Downloading

download streams a file straight to disk, so nothing bigger than a chunk is ever held in memory whatever the database weighs. It writes through a neighboring .part file and renames on success, so a transfer that dies half way leaves no truncated file that reads as a whole database:

$written = $client->database->download('bogon_ip_v1', 'mmdb', '/srv/data/bogon_ip_v1.mmdb');
echo "{$written} bytes";

Pass a stream you opened instead of a path, and it stays yours to close:

$handle = fopen('php://temp', 'w+b');
$client->database->download('bogon_ip_v1', 'csvgz', $handle);

downloadUrl hands back the time-limited link the API redirects to, without following it. The link authorizes itself, so it carries none of your credentials and you can pass it to whatever should run the transfer:

$url = $client->database->downloadUrl('bogon_ip_v1', 'mmdb');

downloadBytes returns the file as a string. It holds the whole thing in memory, and the catalog spans seven orders of magnitude, so check metadata first for anything you have not measured: past your memory_limit this is a fatal error, not merely a slow one.

$bytes = $client->database->downloadBytes('bogon_asn_v1', 'csvgz');

Each of the three downloads the build that is live unless you name one. A database.updated webhook names the build it announces and carries its sha256, so a receiver that downloads after the next publish asks for that build to get the file the hash is of:

$client->database->download('vpn_ip_v1', 'mmdb', './vpn_ip_v1.mmdb', $event['data']['build']);

A build is kept 7 days. Past that the call throws bad_request with the message BUILD_GONE, and downloading without a build fetches the live one. A name that is not a build's shape (20261105.0t53s5) throws InvalidArgumentException before anything is sent.

What is inside, and whether it changed

metadata answers the schema, a few real rows, the row count and the size of every published format, without moving the file. Poll it to decide whether today's build is worth fetching, and to budget a transfer before you start it:

$meta = $client->database->metadata('bogon_ip_v1');

$meta->updated->format('Y-m-d');   // '2026-09-04'
$meta->entries;                    // 44
$meta->size['csvgz'];              // 760
$meta->schema['csvgz'][0]->name;   // 'start_ip'

checksums publishes four digests per file, so a download can be verified against what the API says it served:

$sums = $client->database->checksums('bogon_ip_v1', 'csvgz');

hash_file('sha256', '/srv/data/bogon_ip_v1.csv.gz') === $sums->sha256;   // true

Download history

downloads lists your organization's recent attempts, newest first. Refusals are listed too, because a denial is what answers "it stopped working" and its absence answers nothing:

foreach ($client->database->downloads(20) as $attempt) {
    echo "{$attempt->created->format('c')} {$attempt->databaseId} {$attempt->outcome}\n";
}

What your key can see

list is the catalog as the API served it for your key, and the library keeps no copy of its own.

Sign in with OAuth (device flow)

A program running on the person's own machine can let them sign in with a browser and pick one of their API keys, instead of asking them to paste it:

// $client is the Client built under Usage.
$device = $client->oauth->deviceAuthorization('your-client-id', [
    'scope' => 'account.read apikeys.read apikeys.reveal',
]);
echo "Open {$device->verificationUri} and enter {$device->userCode}\n";

$token = $client->oauth->pollDeviceToken('your-client-id', $device);
if ($token->apikey === null) {
    throw new RuntimeException("no API key came back: none was picked, or it can't be shown again");
}
$keyed = new Client(new Options(apiKey: $token->apikey));

A denied sign-in throws OauthAccessDeniedException and a code that ran out OauthExpiredTokenException. $client->oauth->revoke('your-client-id', $token->refreshToken) signs the machine out again. Only a client we registered, such as our CLI, can use the device flow: an app of your own signs people in with the authorization code flow below.

Sign in with OAuth (authorization code)

An app that can take a browser redirect signs the person in there instead, with a PKCE pair made for that one sign-in:

// $client is the Client built under Usage.
$redirectUri = 'http://127.0.0.1:8765/callback';
$pkce = $client->oauth->createPkce();

$url = $client->oauth->authorizationUrl('your-client-id', $redirectUri, $pkce->challenge, [
    'scope' => 'apikeys.use', 'state' => 'your-state',
]);
// Open $url in the browser. Its redirect to $redirectUri carries code and state.
$token = $client->oauth->exchangeAuthorizationCode('your-client-id', $code, $pkce->verifier, $redirectUri);

Check that state came back as you sent it before you exchange code, which works once. The client ID can also be the https URL of a client metadata document your app serves, and such an app is never handed a key, so $token->apikey stays null.

Register a client

An app with no client ID, and no client metadata document to use as one, registers itself, then signs in with the clientId it gets back as the client ID for authorizationUrl and exchangeAuthorizationCode:

// $client is the Client built under Usage.
$registration = $client->oauth->register(['http://127.0.0.1:8765/callback'], ['clientName' => 'Your App']);

Each redirect URI must be https on a public host name, or http on a loopback address, which then matches any port. Nothing is kept until a person approves the client, so an app with no client ID saved can simply register again.

Absent is not false

The free plan's answer leaves out the address's company and abuse contact, the VPN, proxy, hosting, CDN, bot, carrier, satellite and service flags, the detail behind each flag but Tor's and relay's, the AS's type, the city, both Whois records and the hosted domains. A field your key does not include is null, which is not the same answer as false: null means "not in your plan", false means "checked, and no". That holds for every member, the eight flags isBot, isCarrier, isSatellite, isSsh, isSmtp, isWeb, isDnsResolver and isBittorrent, asn->type, company and abuse included: none reads false, '' or an empty object when the answer leaves it out. Every answer carries capReached, false today (above).

$result->isVpn ?? false;          // when you only want the flag
$result->isVpn === null;          // on the free plan: not in your plan
$result->isCarrier === null;      // on the free plan: null, never false
$result->company === null;        // on the free plan: no company object
$result->asn->type;               // null on the free plan, never ''
$result->location->city;          // null on the free plan, never ''
$result->capReached === false;    // every answer

Other Libraries

There are official InternetData client libraries available for many languages including PHP, Python, Go, Java, and Ruby. See our GitHub at https://github.com/internetdata for more.

About InternetData

Geolocation, anonymity, ownership, network, service and domain data for any IP address, AS or domain, by API or as databases you download.

InternetData

License

This project is licensed under the MIT License.

About

Official PHP client library for the InternetData API: look up any IP address, AS or domain, and download the databases.

Topics

Resources

Security policy

Stars

1 star

Watchers

1 watching

Forks

Releases

Packages

Used by

Contributors

Languages