Php geolocation by ip

Geo IP Location

require_once( «geoip2.phar» );
use GeoIp2 \ Database \ Reader ;
// City DB
$reader = new Reader ( ‘/path/to/GeoLite2-City.mmdb’ );
$record = $reader -> city ( $_SERVER [ ‘REMOTE_ADDR’ ]);
// or for Country DB
// $reader = new Reader(‘/path/to/GeoLite2-Country.mmdb’);
// $record = $reader->country($_SERVER[‘REMOTE_ADDR’]);
print( $record -> country -> isoCode . «\n» );
print( $record -> country -> name . «\n» );
print( $record -> country -> names [ ‘zh-CN’ ] . «\n» );
print( $record -> mostSpecificSubdivision -> name . «\n» );
print( $record -> mostSpecificSubdivision -> isoCode . «\n» );
print( $record -> city -> name . «\n» );
print( $record -> postal -> code . «\n» );
print( $record -> location -> latitude . «\n» );
print( $record -> location -> longitude . «\n» );
$>

It should be noted that this extension has now been superseded by the GeoIP2 API that MaxMind now produces. There is a pure-PHP set of classes and a C library and extension you can optionally install. The code can be found in various projects on MaxMind’s GitHub page: https://github.com/maxmind/

If you want to use the C Library
Example for Ubuntu and PHP 7.4

sudo apt install libmaxminddb0 libmaxminddb-dev mmdb-bin
pecl install maxminddb
vi /etc/php/7.4/mods-available/maxmind.ini
add
extension=maxminddb.so
phpenmod maxmind

$ipAddress = ‘24.24.24.24’ ;
$databaseFile = ‘/usr/share/GeoIP/GeoLite2-Country.mmdb’ ;

Читайте также:  Html code to add website

$reader = new Reader ( $databaseFile );

// get returns just the record for the IP address
print_r ( $reader -> get ( $ipAddress ));

// getWithPrefixLen returns an array containing the record and the
// associated prefix length for that record.
print_r ( $reader -> getWithPrefixLen ( $ipAddress ));

The 3rd party geolite2legacy script can also used to convert the newer GeoLite2 format downloads into the legacy format which can be read by the PHP GeoIP extension.

Источник

Определение местоположения посетителя по IP-адресу в PHP

Несколько способов определить примерное местоположение пользователя по IP-адресу.

Sypex Geo

Sypex Geo – продукт для определение местоположения посетителя по IP-адресу, распространяется по лицензии BSD, т. е. является абсолютно бесплатным. Получив IP-адрес, Sypex Geo выдает информацию о местоположении посетителя – страну, регион, город, географические координаты из локальной базы данных, которая периодически обновляется.

Пример использования:

getCityFull($_SERVER['REMOTE_ADDR']); print_r($res);

Результат:

Array ( [city] => Array ( [id] => 468902 [lat] => 5762987 [lon] => 3987368 [name_ru] => Ярославль [name_en] => Yaroslavl ) [region] => Array ( [id] => 468898 [name_ru] => Ярославская область [name_en] => Yaroslavskaya Oblast' [iso] => RU-YAR ) [country] => Array ( [id] => 185 [iso] => RU [lat] => 6000 [lon] => 10000 [name_ru] => Россия [name_en] => Russia ) )

ip-api.com

IP Geolocation API – бесплатен для некоммерческого использования, ключ к API не требуется. Сервис возвращает данные в формате JSON, XML, CSV, Newline, PHP (serialize) по GET-запросу.

Ограничения

45 запросов в минуту с одного IP-адреса, при превышении лимита будет отдаваться 429-я ошибка до тех пор, пока не будет сброшено ограничение. Если вы постоянно превышаете лимит, ваш IP-адрес будет заблокирован на 1 час.

Пример использования:

Результат:

Array ( [status] => success [country] => Россия [countryCode] => RU [region] => SPE [regionName] => Санкт-Петербург [city] => Санкт-Петербург [zip] => 191015 [lat] => 59,9417 [lon] => 30,3096 [timezone] => Europe/Moscow [isp] => OOO "Network of data-centers "Selectel" [org] => Selectel [as] => AS49505 OOO "Network of data-centers "Selectel" [query] => 95.143.190.109 )

DaData.ru

Среди разделов сайта «DaData.ru» есть сервис «Город по IP-адресу», после регистрации по ключу можно получить детальную информацию о городе, в том числе почтовый индекс.

Бесплатен до 10 000 запросов в сутки, максимум 20 запросов в секунду.

Результат:

Array ( [location] => Array ( [value] => г Ярославль [unrestricted_value] => 150000, Ярославская обл, г Ярославль [data] => Array ( [postal_code] => 150000 [country] => Россия [country_iso_code] => RU [federal_district] => Центральный [region_fias_id] => a84b2ef4-db03-474b-b552-6229e801ae9b [region_kladr_id] => 7600000000000 [region_iso_code] => RU-YAR [region_with_type] => Ярославская обл [region_type] => обл [region_type_full] => область [region] => Ярославская [area_fias_id] => [area_kladr_id] => [area_with_type] => [area_type] => [area_type_full] => [area] => [city_fias_id] => 6b1bab7d-ee45-4168-a2a6-4ce2880d90d3 [city_kladr_id] => 7600000100000 [city_with_type] => г Ярославль [city_type] => г [city_type_full] => город [city] => Ярославль [city_area] => [city_district_fias_id] => [city_district_kladr_id] => [city_district_with_type] => [city_district_type] => [city_district_type_full] => [city_district] => [settlement_fias_id] => [settlement_kladr_id] => [settlement_with_type] => [settlement_type] => [settlement_type_full] => [settlement] => [street_fias_id] => [street_kladr_id] => [street_with_type] => [street_type] => [street_type_full] => [street] => [stead_fias_id] => [stead_cadnum] => [stead_type] => [stead_type_full] => [stead] => [house_fias_id] => [house_kladr_id] => [house_cadnum] => [house_type] => [house_type_full] => [house] => [block_type] => [block_type_full] => [block] => [entrance] => [floor] => [flat_fias_id] => [flat_cadnum] => [flat_type] => [flat_type_full] => [flat] => [flat_area] => [square_meter_price] => [flat_price] => [room_fias_id] => [room_cadnum] => [room_type] => [room_type_full] => [room] => [postal_box] => [fias_id] => 6b1bab7d-ee45-4168-a2a6-4ce2880d90d3 [fias_code] => [fias_level] => 4 [fias_actuality_state] => 0 [kladr_id] => 7600000100000 [geoname_id] => 468902 [capital_marker] => 2 [okato] => 78401000000 [oktmo] => 78701000001 [tax_office] => 7600 [tax_office_legal] => 7600 [timezone] => [geo_lat] => 57.621562 [geo_lon] => 39.897822 [beltway_hit] => [beltway_distance] => [metro] => [divisions] => [qc_geo] => 4 [qc_complete] => [qc_house] => [history_values] => [unparsed_parts] => [source] => [qc] => ) ) )

Источник

Saved searches

Use saved searches to filter your results more quickly

You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window. Reload to refresh your session.

PHP library for Abstract’s IP Geolocation API (free)

License

abstractapi/php-ip-geolocation

This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Name already in use

A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?

Sign In Required

Please sign in to use Codespaces.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching Xcode

If nothing happens, download Xcode and try again.

Launching Visual Studio Code

Your codespace will open once ready.

There was a problem preparing your codespace, please try again.

Latest commit

Git stats

Files

Failed to load latest commit information.

README.md

AbstractAPI php-ip-geolocation library

Integrate the powerful IP Geolocation API from Abstract in your PHP project in a few lines of code.

Abstract’s IP Geolocation API is a fast, lightweight, modern, and RESTful JSON API allowing you to look up the location, timezone, country details, and more of an IPv4 or IPv6 address.

It’s very simple to use: you only need to submit your API key and an IP address, and the API will respond with an assessment of its geographical location, as well as additional details like the timezone, if it’s a VPN address, and more.

Validating and verifying IP addresses is a critical step to reducing the chances of low-quality data and fraudulent or risky users in your website or application.

This library supports the PHP version 5.6 and higher.

You can install php-ip-geolocation via composer or by downloading the source.

php-ip-geolocation is available on Packagist as the abstractapi/php-ip-geolocation package:

composer require abstractapi/php-ip-geolocation

Get your API key for free and without hassle from the Abstact website.

Geolocation from an IP Address

// Get a Geolocation from an IP Address Abstract's IP Geolocation API and PHP  $api_key pl-s">YYYYYY"; // Your API Key from https://app.abstractapi.com/api/ip-geolocation/documentation Abstractapi\IpGeolocation\AbstractIpGeolocation::configure($api_key); $info = Abstractapi\IpGeolocation\AbstractIpGeolocation::look_up('8.8.8.8'); print $info->city;

The API response is returned in a IpGeolocationData object.

PARAMETER TYPE DETAILS
Parameter Type Details
ip_address String The requested IP address
city String City’s name.
city_geoname_id String City’s geoname ID.
region String State or province in which the the city is located.
region_iso_code Char[2] State or province’s ISO 3166-2 code.
region_geoname_id String State or province’s geoname ID.
postal_code String ZIP or postal code.
country String Country’s name.
country_code Char[2] Country’s ISO 3166-1 alpha-2 code.
country_geoname_id String Country’s geoname ID.
country_is_eu Boolean True if the country is in the EU, false if it is not.
continent String Continent’s name.
continent_code Char[2] 2 letter continent code: AF, AS, EU, NA, OC, SA, AN
continent_geoname_id String Continent’s geoname ID.
longitude Float Decimal of the longitude.
latitude Float Decimal of the latitude.
security > is_vpn Boolean Whether the IP address is using from a VPN or using a proxy
timezone > name String Timezone’s name from the IANA Time Zone Database.
timezone > abbreviation String Timezone’s abbreviation, also from the IANA Time Zone Database.
timezone > gmt_offset String Timezone’s offset from Greenwich Mean Time (GMT).
timezone > current_time String Current time in the local time zone.
timezone > is_dst Boolean True if the location is currently in Daylight Savings Time (DST).
flag > svg String Link to a hosted version of the country’s flag in SVG format.
flag > png String Link to a hosted version of the country’s flag in PNG format.
flag > emoji String Country’s flag as an emoji.
flag > unicode String Country’s flag in unicode.
currency > currency_name String The currency’s name.
currency > currency_code String The currency’s code in ISO 4217 format.
connection > connection_type String Type of network connection: Dialup, Cable/DSL, Cellular, Corporate
connection > autonomous_system_number Uint32 Autonomous System number
connection > autonomous_system_organization String Autonomous System Organization name.
connection > isp_name String Internet Service Provider (ISP) name.
connection > organization_name String Organization name.

You will find additional information and request examples in the Abstract help page.

If you need help installing or using the library, please contact Abstract’s Support.

For bug report and feature suggestion, please use this repository issues page.

Contributions are always welcome, as they improve the quality of the libraries we provide to the community.

Please provide your changes covered by the appropriate unit tests, and post them in the pull requests page.

To work on the source code, you need to install composer on your local computer. At the time of writing, the latest version of composer is v2.0.12. The installation instructions can be found here: https://getcomposer.org/download/.

To install the requirements, run:

composer install --prefer-source --no-interaction --ignore-platform-reqs

Once you implementer all your changes and the unit tests, run the following command to run the tests:

About

PHP library for Abstract’s IP Geolocation API (free)

Источник

Оцените статью