Coder Social home page Coder Social logo

ipinfo / php Goto Github PK

View Code? Open in Web Editor NEW
233.0 30.0 79.0 294 KB

Official PHP library for IPinfo (IP geolocation and other types of IP data)

Home Page: https://ipinfo.io

License: Apache License 2.0

PHP 100.00%
ipaddress php ipinfo ip-geolocation geoip ip-data

php's Introduction

IPinfo IPinfo PHP Client Library

This is the official PHP client library for the IPinfo.io IP address API, allowing you to look up your own IP address, or get any of the following details for an IP:

  • IP to Geolocation data (city, region, country, postal code, latitude, and longitude)
  • ASN information (ISP or network operator, associated domain name, and type, such as business, hosting, or company)
  • Company details (the name and domain of the business that uses the IP address)
  • Carrier information (the name of the mobile carrier and MNC and MCC for that carrier if the IP is used exclusively for mobile traffic)

Check all the data we have for your IP address here.

Getting Started

You'll need an IPinfo API access token, which you can get by signing up for a free account at https://ipinfo.io/signup.

The free plan is limited to 50,000 requests per month, and doesn't include some of the data fields such as IP type and company data. To enable all the data fields and additional request volumes see https://ipinfo.io/pricing.

Installation

The package works with PHP 8 and is available using Composer.

composer require ipinfo/ipinfo

Quick Start

<?php

require_once __DIR__ . '/vendor/autoload.php';

use ipinfo\ipinfo\IPinfo;

$access_token = '123456789abc';
$client = new IPinfo($access_token);
$ip_address = '216.239.36.21';
$details = $client->getDetails($ip_address);

echo $details->city; // Mountain View
echo $details->loc; // 37.4056,-122.0775

Usage

The IPinfo->getDetails() method accepts an IP address as an optional, positional argument. If no IP address is specified, the API will return data for the IP address from which it receives the request.

$client = new IPinfo();
$ip_address = '216.239.36.21';
$details = $client->getDetails($ip_address);
echo $details->city; // Mountain View
echo $details->loc; // 37.4056,-122.0775

Authentication

The IPinfo library can be authenticated with your IPinfo API token, which is passed in as a positional argument. It also works without an authentication token, but in a more limited capacity.

$access_token = '123456789abc';
$client = new IPinfo($access_token);

Details Data

IPinfo->getDetails() will return a Details object that contains all fields listed IPinfo developer docs with a few minor additions. Properties can be accessed directly.

$details->hostname; // cpe-104-175-221-247.socal.res.rr.com

Country Name

Details->country_name will return the country name, as supplied by the countries object. See below for instructions on changing that object for use with non-English languages. Details->country will still return the country code.

$details->country; // US
$details->country_name; // United States

EU Country

Details->is_eu will return true if the country is a member of the EU, as supplied by the eu object.

$details->is_eu; // False

Country Flag

Details->country_flag will return the emoji and Unicode representations of the country's flag, as supplied by the flags object.

$details->country_flag['emoji']; // 🇺🇸
$details->country_flag['unicode']; // U+1F1FA U+1F1F8

Country Flag URL

Details->country_flag_url will return a public link to the country's flag image as an SVG which can be used anywhere.

$details->country_flag_url; // https://cdn.ipinfo.io/static/images/countries-flags/US.svg

Country Currency

Details->country_currency will return the code and symbol of the country's currency, as supplied by the currency object.

$details->country_currency['code']; // USD
$details->country_currency['symbol']; // $

Continent

Details->continent will return the code and name of the continent, as supplied by the continents object.

$details->continent['code']; // NA
$details->continent['name']; // North America

Longitude and Latitude

Details->latitude and Details->longitude will return latitude and longitude, respectively, as strings. Details->loc will still return a composite string of both values.

$details->loc; // 37.4056,-122.0775
$details->latitude; // 37.4056
$details->longitude; // -122.0775

Accessing all properties

Details->all will return all details data as a dictionary.

$details->all;
/*
(
    [ip] => 216.239.36.21
    [hostname] => any-in-2415.1e100.net
    [anycast] => 1
    [city] => Mountain View
    [region] => California
    [country] => US
    [loc] => 37.4056,-122.0775
    [org] => AS15169 Google LLC
    [postal] => 94043
    [timezone] => America/Los_Angeles
    [asn] => Array
        (
            [asn] => AS15169
            [name] => Google LLC
            [domain] => google.com
            [route] => 216.239.36.0/24
            [type] => hosting
        )

    [company] => Array
        (
            [name] => Google LLC
            [domain] => google.com
            [type] => hosting
        )

    [privacy] => Array
        (
            [vpn] => 
            [proxy] => 
            [tor] => 
            [relay] => 
            [hosting] => 1
            [service] => 
        )

    [abuse] => Array
        (
            [address] => US, CA, Mountain View, 1600 Amphitheatre Parkway, 94043
            [country] => US
            [email] => [email protected]
            [name] => Abuse
            [network] => 216.239.32.0/19
            [phone] => +1-650-253-0000
        )

    [domains] => Array
        (
            [ip] => 216.239.36.21
            [total] => 2535948
            [domains] => Array
                (
                    [0] => pub.dev
                    [1] => virustotal.com
                    [2] => blooket.com
                    [3] => go.dev
                    [4] => rytr.me
                )

        )

    [country_name] => United States
    [is_eu] => 
    [country_flag] => Array
        (
            [emoji] => 🇺🇸
            [unicode] => U+1F1FA U+1F1F8
        )

    [country_flag_url] => https://cdn.ipinfo.io/static/images/countries-flags/US.svg
    [country_currency] => Array
        (
            [code] => USD
            [symbol] => $
        )

    [continent] => Array
        (
            [code] => NA
            [name] => North America
        )

    [latitude] => 37.4056
    [longitude] => -122.0775
)

*/

Caching

In-memory caching of Details data is provided by default via the symfony/cache library. LRU (least recently used) cache-invalidation functionality has been added to the default TTL (time to live). This means that values will be cached for the specified duration; if the cache's max size is reached, cache values will be invalidated as necessary, starting with the oldest cached value.

Modifying cache options

Default cache TTL and maximum size can be changed by setting values in the $settings argument array.

  • Default maximum cache size: 4096 (multiples of 2 are recommended to increase efficiency)
  • Default TTL: 24 hours (in seconds)
$access_token = '123456789abc';
$settings = ['cache_maxsize' => 30, 'cache_ttl' => 128];
$client = new IPinfo($access_token, $settings);

Using a different cache

It's possible to use a custom cache by creating a child class of the CacheInterface class and passing this into the handler object with the cache keyword argument. FYI this is known as the Strategy Pattern.

$access_token = '123456789abc';
$settings = ['cache' => $my_fancy_custom_cache];
$client = new IPinfo($access_token, $settings);

Disabling the cache

You may disable the cache by passing in a cache_disabled key in the settings:

$access_token = '123456789abc';
$settings = ['cache_disabled' => true];
$client = new IPinfo($access_token, $settings);

Overriding HTTP Client options

The IPinfo client constructor accepts a timeout key which is the request timeout in seconds.

For full flexibility, a guzzle_opts key is accepted which accepts an associative array which is described in Guzzle Request Options. Options set here will override any custom settings set by the IPinfo client internally in case of conflict, including headers.

Batch Operations

Looking up a single IP at a time can be slow. It could be done concurrently from the client side, but IPinfo supports a batch endpoint to allow you to group together IPs and let us handle retrieving details for them in bulk for you.

$access_token = '123456789abc';
$client = new IPinfo($access_token);
$ips = ['1.1.1.1', '8.8.8.8', '1.2.3.4/country'];
$results = $client->getBatchDetails($ips);
echo $results['1.2.3.4/country']; // AU
var_dump($results['1.1.1.1']);
var_dump($results['8.8.8.8']);

The input size is not limited, as the interface will chunk operations for you behind the scenes.

Please see the official documentation for more information and limitations.

Internationalization

When looking up an IP address, the response object includes a Details->country_name attribute which includes the country name based on American English. It is possible to return the country name in other languages by setting the countries object inside the IPinfo object, when creating the IPinfo object.

The php object must be with the following structure:

countries = [
    "BD" => "Bangladesh",
    "BE" => "Belgium",
    "BF" => "Burkina Faso",
    "BG" => "Bulgaria"
    ...
]
continents = [
        "BD" => ["code" => "AS", "name" => "Asia"],
        "BE" => ["code" => "EU", "name" => "Europe"],
        "BF" => ["code" => "AF", "name" => "Africa"],
        "BG" => ["code" => "EU", "name" => "Europe"],
        "BA" => ["code" => "EU", "name" => "Europe"],
        "BB" => ["code" => "NA", "name" => "North America"]
        ...
]

Other Libraries

There are official IPinfo client libraries available for many languages including PHP, Python, Go, Java, Ruby, and many popular frameworks such as Django, Rails, and Laravel. There are also many third-party libraries and integrations available for our API.

About IPinfo

Founded in 2013, IPinfo prides itself on being the most reliable, accurate, and in-depth source of IP address data available anywhere. We process terabytes of data to produce our custom IP geolocation, company, carrier, privacy, hosted domains and IP type data sets. Our API handles over 40 billion requests a month for 100,000 businesses and developers.

image

php's People

Contributors

abu-usama avatar adeel-usmani avatar alexbilbie avatar assertchris avatar awaismslm avatar barryvdh avatar bcrowe avatar browner12 avatar coderholic avatar colinodell avatar dragoonis avatar emanueleminotto avatar frankdejonge avatar hansott avatar hassankhan avatar jclyons52 avatar jhtimmins avatar jotaelesalinas avatar kdubuc avatar marcqualie avatar noamanahmed avatar philsturgeon avatar ravage84 avatar reinink avatar rm-umar avatar robloach avatar rvalitov avatar samuel-gill avatar st-polina avatar umanshahzad avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

php's Issues

Not working with ipv6

Hello,

I found that it is not working with ipv6. As I am not getting location for ipv6 please update it as soon as posible

PHP 8 Support

Unable to download if you have PHP 8

Output below:

Problem 1
- ipinfo/ipinfo[dev-master, v2.0.0] require php ~7.0 -> your php version (8.0.0) does not satisfy that requirement.
- ipinfo/ipinfo 2.0.x-dev is an alias of ipinfo/ipinfo dev-master and thus requires it to be installed too.
- Root composer.json requires ipinfo/ipinfo ^2.0.0 -> satisfiable by ipinfo/ipinfo[v2.0.0, 2.0.x-dev (alias of dev-master)].

Does not work with PHP 8.2+

It seems that it does not work with PHP 8.2+. Creating a dynamic property is deprecated.

Deprecated: Creation of dynamic property ipinfo\ipinfo\Details::$carrier is deprecated in XXX/vendor/ipinfo/ipinfo/src/Details.php on line 40 PHP Deprecated: Creation of dynamic property ipinfo\ipinfo\Details::$carrier is deprecated in XXX/vendor/ipinfo/ipinfo/src/Details.php on line 40

This failure cost us 817.487 api calls :-(

Retrieving an IPV6 throw an exception

When you retrieve an ipv6 via getDetails for example, it throws Symfony\Component\Cache\Exception\InvalidArgumentException Cache key "xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx_v1" contains reserved characters "{}()/\@:".

Does not work with Guzzle7

If I use this library in a project with Guzzle7, then the following error is displayed by composer:

ipinfo/ipinfo v1.1.1 requires guzzlehttp/guzzle ^6.3 -> satisfiable by guzzlehttp/guzzle[6.3.0, 6.3.1, 6.3.2, 6.3.3, 6.4.0, 6.4.1, 6.5.0, 6.5.1, 6.5.2, 6.5.3, 6.5.4, 6.5.5, 6.5.x-dev] but these conflict with your requirements or minimum-stability.

Make caching more easily optional

Right now caching can be modified by a settings key to choose your own cache implementation.

However it should be easier to disable caching (it should really default to disabling, but that would be a breaking change); currently that requires creating a custom cache implementation which simply does nothing.

We can either create such an implementation that does nothing, or have a new key like cache_disabled and update cache-using code to check if the cache exists before using it.

Use versioned cache key

Make sure the cache key contains a number to indicate the version of the cached data. Data changes that change what's expected in cached data require a version change.

Add timeout

Please, add timeout option, so that we can control how long the request may work.

Request: New Map feature to be added

Hello!

I really love IP info and recently you guys launched: Map IPs: https://ipinfo.io/map

Would it be possible to get this in the library? I was thinking of PRing it but unsure if it's more of an "experimental/fun" thing at the moment or if it's something that will stick around and is production ready.

Kind Regards!

Token Referrer restriction with PHP Lib

When using a Domainname Referrer restriction on my token, the PHP library fails to fetch user details with an error

400 Bad Request

I assume this is because my script runs Serverside hence not having a referrer http header.

Any ideas how to overcome this? Like can I force pass a referrer serverside to the IPinfo Library?

Features of extracting json Not working

There are some features like directly getting Lattitude with $details->lattitude or $details['lattitude'] is not working, and for ipinfo.io/43.241.71.120/privacy?token=$TOKEN This part of feature is not working or I'm unable to get the result using simple php command.

Retrieving your public IPv6 address

I am trying to retrieve my public IPv6 address but the getDetails() function, with $ip_address paramater set to null, only returns the IPv4 address. i have tried changing the const API_URL of the IPinfo class to 'https://v6.ipinfo.io' but somehow that leads to an curl error 7 which i do not understand. because if i use curl directly it works.

curl ipinfo.io/?token=mytoken

returns json with ip as ipv4 address

curl ipinfo.io/ip/?token=mytoken

returns string ip as ipv4 address

curl v6.ipinfo.io/ip/?token=mytoken

returns string ip as ipv6 address

curl https://v6.ipinfo.io/ip/?token=mytoken

returns string ip as ipv6 address

any idea why the curl error?

guzzlehttp/guzzle v7.2

HI,

I want to use this package into my project and my project using guzzlehttp/guzzle v7.2 and your package is require a guzzlehttp/guzzle v ^6.3 so I am unable to import package via composer

can you please update your package at packagist?

thanks

use this library without composer

Hi
I want to use it without the composer. I tried to add files with require_once function nut it does not work. example: require_once('ipinfo/src/IPinfo.php')
can you help me?

Error with cache key

I tried for the first time the API, with a simple symfony code I get the error:

Cache key "xxxx:1" contains reserved characters "{}()/\@:"

With xxxx being the ip adress of my server.

$client = new IPinfo($access_token);
$details = $client->getDetails($_SERVER["REMOTE_ADDR"]);

I tried setting the ip_address myself, and always the same result, the code add a ":1" at the end of my IP.

The php api does not work on the server but it does on the localhost

The problem is that it returns a 400 error, but in the local environment it works correctly, I already configured Whitelist Referring Domains.

`
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
require_once FCPATH.'vendor/autoload.php';

      use ipinfo\ipinfo\IPinfo;
      use ipinfo\ipinfo\IPinfoException;
      ...
      
      $access_token = 'xxx';
      $client = new IPinfo($access_token); 
      $ip_address = '190.129.164.188';
      $details = $client->getDetails($this->ip());
      echo "<pre>";
      var_dump($details);
      echo "</pre>";

`

ERROR

An uncaught Exception was encountered
Type: ipinfo\ipinfo\IPinfoException

Message: Exception: {"status":400,"reason":"Bad Request"}

Filename: /home3/antraxse/public_html/vendor/ipinfo/ipinfo/src/IPinfo.php

Line Number: 209

Backtrace:

Inline all data files

We have several files like eu.json, countries.json, continents.json and so on, which are loaded during initialization / startup of the client.

Instead of loading these as such, which has risks such as the asset not appearing in a production environment properly, and has a performance penalty during init of loading an on-disk file, we should inline the files into a static, in-memory map / dictionary or similar.

PSR-4 non-compliance warning by composer

Here is the error I get every time I run composer update.

Deprecation Notice: Class ipinfo\ipinfo\cache\CacheInterface located in ./vendor/ipinfo/ipinfo/src/cache/Interface.php does not comply with psr-4 autoloading standard. It will not autoload anymore in Composer v2.0. in phar:///usr/local/bin/composer/src/Composer/Autoload/ClassMapGenerator.php:185
Deprecation Notice: Class ipinfo\ipinfo\cache\DefaultCache located in ./vendor/ipinfo/ipinfo/src/cache/Default.php does not comply with psr-4 autoloading standard. It will not autoload anymore in Composer v2.0. in phar:///usr/local/bin/composer/src/Composer/Autoload/ClassMapGenerator.php:185

Add optional IP selection handler

Add an optional IP selection handler to the SDK client initialization step which accepts the request context and expects returning an IP.

Add a default handler for this which looks at the X-Forwarded-For header and falls back to the source IP.

The resulting IP is the IP for which details are fetched.

Can I use downloaded Geolocation API database to initialize this client?

As far as I understand, this client makes api requests ещ ipinfo.io. I was wondering if I purchase a geolocation database (I need it for other purposes as well), can I somehow initialize the client with data from the database. So that it does not make any requests over the network and works only with local data?

More info on why response object can be null when calling IPinfo::getDetails()

Hi, I am using the package to get info about a specific ip, and sometimes, in a context I do not understand yet, I get empty (null) response when calling IPinfo::getDetails(). I would like to know why it can return null (is it because the API throttle, server error, or any other reason?).

Not that no IPinfoException is thrown, I just get null as a result.

Also not that when I retry a few moment later the same request, it gets the result without issues.

If I know the reason I can take required measures to mitigate the issue. Thank you.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.