Detect country by ip php

GeoIP Functions

If you want to use this extension in SUSE/openSUSE, it is available here:

Both, Ubuntu and Debian itself make usage of version 1.3.x of the c libraries, so installation can’t be done with the debian packages, because configure stops with:

== configure: error: You need version 1.4.0 or higher of the C API ==

so you must download it from maxmind.

The GeoLiteCity free db works and can resolve city names and other informations.

Make sure the instructions are followed regarding it’s installation.

At step 2 the decompress file must be moved and renamed.
The files needs to be called GeoIPCity.dat if not the mod_geoip will not find it.

I couldn’t get it to work with the DMA code database (product ID 137). It seems to only work with the country database. The documentation should contain a warning that this code (as of 0.2.0) is incomplete and that Net_GeoIP should be used for non-country databases.

If you are a Debian or Ubuntu user, instead of building it from source, you can:
aptitude install libgeoip-dev libgeoip1

The geoip_country_*_by_name functions only work with GeoIP Country. The geoip_record_by_name function works with GeoIP City. geoip_region_by_name works with GeoIP Region. So the API should work with all of the GeoIP databases, as long as you call the correct function.

While trying to update the GeoIP.dat file under debian, I’ve found out that automatic updates via the geoipupdate (in geoip-bin package) is not available for the free edition. Here is a one-liner script that will do it. You can put it in a crontab, it will download the .dat file only if it has change :

cd /usr/share/GeoIP && wget GEOIP_URL -N && cat GeoIP.dat.gz | gzip -d > GeoIP.dat

Note : GEOIP_URL is to be found on the page http://www.maxmind.com/app/geoip_country, under the Binary Format section (The php note system won’t allow me to put the full URL here

you can use this function to determine the continent of a country:

function getContinentFromCountry($country)
$data = array («AF»=> «AS»,»AX»=>»EU»,»AL»=>»EU», «DZ»=>»AF»,»AS»=>»OC», «AD»=>»EU»,»AO»=> «AF» . );
return $data[$country];
>

unfortunately this comment’s size is restricted, so you will have the rest by yourself

for example:
getContinentFromCountry(«DE») will result in «EU»

this data is based on
wikipedia’s
List_of_countries_by_continent_(data_file)

For Debian etch users : libgeoip is in version 1.4 so get the source from lenny (apt-get build-dep libgeoip;apt-get source libgeoip), compile it on etch (dpkg-buildpackage -rfakeroot in source folder) and install resulting libgeoip1 and libgeo-dev packages (dpkg -i). Together with php5-dev this package is easy to install (phpize5;./configure —enable-geoip;make;make install). Then check your install in php with :
echo geoip_database_info ( GEOIP_COUNTRY_EDITION );
echo $_SERVER [ ‘REMOTE_ADDR’ ];
echo geoip_country_code3_by_name ( $_SERVER [ ‘REMOTE_ADDR’ ]);
?>

please note free .dat is in /usr/share/GeoIP/GeoIP.dat
Use geoip-bin package to schedule automatic updates (configure /etc/geoip.default.conf and copy to /etc/geoip.conf, then add a crontab to make the updates. )
hope this helps

Just to clarify the other comments, the maxmind post seems to be out of date / incorrect.

This module fails to work (ie: resolve cities) with the GeoLite City database from here:
http://www.maxmind.com/app/geolitecity

The error occurs when calling the function geoip_record_by_name(), which states incorrectly that the required database is not available. I have tested it with the very latest database, for which geoip_database_info() returns the version:
GEO-533LITE 20070601 Build 1 Copyright (c) 2007 MaxMind LLC All Rights Reserved

It does, however, resolve countries OK via the GeoLite Country database, which you can grab here: http://www.maxmind.com/app/geoip_country
I tested with the version:

GEO-106FREE 20070601 Build 1 Copyright (c) 2007 MaxMind LLC All Rights Reserved

Источник

Как в PHP узнать IP пользователя и определить его страну?

Как в PHP узнать IP пользователя и определить его страну?

Получить IP адрес клиента в PHP можно через суперглобальный массив $_SERVER . В этом массиве IP адрес посетителя доступен через ключ REMOTE_ADDR .

// сохраним в переменную ip значение IP адреса клиента $ip = $_SERVER['REMOTE_ADDR'];

Но, если клиент использует прокси-сервер, то значение $_SERVER[‘REMOTE_ADDR’] будет содержать IP последнего прокси-сервера, через который клиент попал на сайт.

В этом случае, чтобы узнать IP посетителя можно попробовать использовать $_SERVER[‘HTTP_CLIENT_IP’] и $_SERVER[‘HTTP_X_FORWARDED_FOR’] . HTTP_CLIENT_IP и HTTP_X_FORWARDED_FOR – это заголовки, содержащие IP адрес пользователя. Данные заголовки устанавливает прокси-сервер. Обычно прокси-сервер устанавливает один из них. Данным в этих заголовках можно доверять, только если прокси-сервер надёжный. В противном случае, им доверять не стоит, т.к. их можно очень просто подделать. В этом случае лучше просто использовать $_SERVER[‘REMOTE_ADDR’] или сохранять в базу как $_SERVER[‘REMOTE_ADDR’] , так и заголовок, устанавливаемый прокси-сервером.

function getIp() { $keys = [ 'HTTP_CLIENT_IP', 'HTTP_X_FORWARDED_FOR', 'REMOTE_ADDR' ]; foreach ($keys as $key) { if (!empty($_SERVER[$key])) { $ip = trim(end(explode(',', $_SERVER[$key]))); if (filter_var($ip, FILTER_VALIDATE_IP)) { return $ip; } } } } $ip = getIp(); // выведем IP клиента на экран echo 'ip = ' . $ip;

Определение страны по ip с помощью Sypex Geo

Основные шаги по созданию php скрипта, с помощью которого можно будет определять страну по ip:

1. Скачаем Sypex Geo для PHP и базу данных стран. Sypex Geo распространяется по лицензии BSD, т.е. является абсолютно бесплатным.

2. Распакуем архивы и загрузим на сервер файлы «SxGeo.php» и «SxGeo.dat». В качестве примера, создадим на сервере папку SxGeo и загрузим эти файлы в неё.

3. Создадим свой скрипт, например, «get_country_code.php».

4. Вставим в этот файл следующий код:

5. Включим файл «get_country_code.php» в другие скрипты, в которых нужно реализовать выполнение кода в зависимости от принадлежности ip посетителя к той или иной стране.

require_once 'SxGeo/get_country_code.php'; if ($country_сode === 'RU') { // код для посетителей из России. } else { // код для посетителей из других стран. }

Определение города по ip с помощью Sypex Geo

Для определения города, потребуется загрузить архив с базой данных городов для Sypex Geo, распаковать его и загрузить на сервер.

Скрипт в этом случае будет следующий:

get($ip); // также можно использовать следующий код // $SxGeo->getCity($ip); // широта $lat = $city['city']['lat']; // долгота $lon = $city['city']['lon']; // название города на русском языке $city_name_ru = $city['city']['name_ru']; // название города на английском языке $city_name_en = $city['city']['name_en']; // ISO-код страны $country_code = $city['country']['iso']; // для получения информации более полной информации (включая регион) можно осуществить через метод getCityFull $city = $SxGeo->getCityFull($ip); // название региона на русском языке $region_name_ru = $city['region']['name_ru']; // название региона на английском языке $region_name_en = $city['city']['name_en']; // ISO-код региона $region_name_iso = $city['city']['iso'];

Для автоматического обновления баз можно воспользоваться этим архивом. В этом архиве находится php скрипт. Этот скрипт необходимо настроить, т.е. указать в нём URL для скачивания базы и пути к файлам на сервере. После этого загрузить его на сервер и настроить его запуск по расписанию с помощью cron.

Определение страны и города по ip через сервис через сервис ipstack

Рассмотрим ещё один вариант определения в php местоположения по ip посетителя, но уже не через Sypex Geo, а с помощью сервиса ipstack.

Сервис ipstack имеет бесплатный план, который позволяет обрабатывать до 10000 запросов в месяц.

Планы сервиса ipstack для определения страны и города посетителя по его ip

Для получения бесплатного плана нажимаем на кнопку «GET FREE API KEY» и переходим на страницу, на которой нужно заполнить регистрационную карточку.

После регистрации, на личной странице ipstack вам будет назначен «API Access Key», который нужно скопировать. Он нам потребуется при создании php скрипта.

Как в PHP получить IP адрес сервера

Узнать IP адрес сервера в PHP можно с помощью следующей инструкции:

// сохраним IP адрес сервера в переменную $ip_server $ip_server = $_SERVER['SERVER_ADDR']; // выведем IP адрес сервера на экран $echo $ip_server;

Пример реализации определения локации в CMS MODX

В качестве примере рассмотрим, как в CMS MODX Revolution можно очень просто без сторонних сервисов осуществить определение страны посетителя. Разработаем решение на базе Sypex Geo.

1. Для этого сначала нужно загрузить Sypex Geo в проект:

Загрузка библиотеки Sypex Geo в проект на CMS MODX Revolution с помощью которой организуем определение страны посетителя по его ip

Файл «SxGeo.php» – это основной скрипт, а «SxGeo.dat» – это база стран. Этих двух файлов достаточно для определения страны пользователя по его ip. Дополнительно в каталоге SxGeo ещё расположен файл «SxGeoCity.dat», данный файл в текущей реализации не нужен, он может потребовать, если в проекте потребуется определять не только страну пользователя, а ещё его регион и город.

2. Создадим сниппет, например «get_location.php». В качестве примера организуем это с помощью файлов. Для этого нужно чтобы был установлен pdoTools и в настройках включена опция «Использовать Fenom на страницах».

Код сниппета «get_location.php»:

getCountry($ip); unset($SxGeo); $modx->setPlaceholder('countrycode', $country); return;

Поместим файл «get_location.php» в каталог /core/elements/snippets/ .

Данный сниппет будет определять страну и помещать его код в плейсхолдер countrycode .

3. После этого в нужных шаблонах поместим код вызова сниппета и сохранение значение плейсхолдера countrycode в переменную $country_code .

{$_modx->runSnippet('@FILE snippets/get_location.php')} {set $country_code = $_modx->getPlaceholder('countrycode')}

Всё теперь чтобы написать логику достаточно использовать эту переменную.

{if $country_code === 'UA'} Код для Украины {else} Код для других стран {/if}

Источник

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’ ;

$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.

Источник

Читайте также:  Php добавление html элемента
Оцените статью