Php geoip country codes

geoip_record_by_name

Функция geoip_record_by_name() возвращает информацию об адресе, соответствующую имени хоста или IP адреса.

Функция доступна для бесплатной версии GeoLite City Edition и коммерческой GeoIP City Edition. Если необходимые базы отсутствует, выводится предупреждение.

Следующие имена ключей возвращаемого ассоциативного массива:

  • «continent_code» — Двухбуквенный код континента (с версии 1.0.4 с libgeoip 1.4.3 или более новой)
  • «country_code» — Двухбуквенный код страны (смотрите geoip_country_code_by_name() )
  • «country_code3» — Трёхбуквенный код страны (смотрите geoip_country_code3_by_name() )
  • «country_name» — Название страны (смотрите geoip_country_name_by_name() )
  • «region» — Код региона (например: CA для Калифорнии)
  • «city» — Город.
  • «postal_code» — Почтовый индекс, FSA или Zip-код
  • «latitude» — Широта, число с плавающей точкой ( float ) без знака.
  • «longitude» — Долгота, число с плавающей точкой ( float ) без знака.
  • «dma_code» — Код рыночной зоны (Designated Market Area, DMA), только для США и Канады
  • «area_code» — Код телефонной сети общего пользования (PSTN), например, 212

Список параметров

Имя хоста или IP-адрес, данные по которому должны быть получены.

Возвращаемые значения

Возвращает ассоциативный массив в случае успешного выполнения или false , если адрес не может быть найден в базе.

Список изменений

Версия Описание
PECL geoip 1.0.4 Добавлен код континента (continent_code) с GeoIP Library 1.4.3 или более новыми.
PECL geoip 1.0.3 Добавлен трёхбуквенный код страны (country_code3) и название страны (country_name).

Примеры

Пример #1 Пример использования geoip_record_by_name()

Выведет массив, содержащий запись о хосте example.com.

Результат выполнения данного примера:

Array ( [continent_code] => NA [country_code] => US [country_code3] => USA [country_name] => United States [region] => CA [city] => Marina Del Rey [postal_code] => [latitude] => 33.9776992798 [longitude] => -118.435096741 [dma_code] => 803 [area_code] => 310 )

User Contributed Notes 4 notes

I know this may be obvious to some but I thought I would post it anyway to help others. The GEOIP section of the PHP site is a bit limited in useful tips/documentation other than the initial functions and examples.

If you are trying to get information about the specific user visiting your site, you should use their IP address via the remote address in the GEOIP function. In addition here are some useful bits of code to pull certain information from the function.
# Collect a specific users GEOIP info
$info = geoip_record_by_name ( $_SERVER [ ‘REMOTE_ADDR’ ]);
print_r ( $info );

# To get the info from one specific field
$country = $info [ ‘country_name’ ];
echo $country ;

# To combine information from the array into a string
$info = implode ( «/» , $info );
echo $info ;
?>

Note on field in this array is NOT included, the connection speed of the user. To find the connection speed/connection type the visitor has, you can use the geoip_id_by_name() function. Lastly it is a good idea on whatever platform you are using GEOIP on to make sure it’s data is up-to-date. On most Linux/UNIX systems with terminal you can use «pear update-channels» and «pecl update-channels» commands to keep your libraries updated. This is a good idea because GEOIP databases and country/location codes often change over time.

Источник

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

Источник

geoip_country_code_by_name

Функция geoip_country_code_by_name() возвращает двухсимвольный код страны, соответствующий имени хоста или IP-адресу.

Список параметров

Имя хоста или IP-адрес, по которому будет вестись поиск.

Возвращаемые значения

Возвращает два символа, содержащих код страны по ISO 3166-1, при нахождении адреса в базе данных, в противном случае false .

Примеры

Пример #1 Пример использования geoip_country_code_by_name()

Данный пример выведет расположение хоста example.com.

$country = geoip_country_code_by_name ( ‘www.example.com’ );
if ( $country ) echo ‘Хост расположен в ‘ . $country ;
>
?>

Результат выполнения данного примера:

Примечания

Пожалуйста, ознакомьтесь с полным списком допустимых возвращаемых значений, в том числе и специальных кодов, здесь » http://www.maxmind.com/en/iso3166.

Смотрите также

User Contributed Notes 2 notes

Latest version v1.1.1 https://pecl.php.net/package-changelog.php?package=geoip&release=1.1.1 support IPv6 four country database. New functions geoip_country_code_by_name_v6(), geoip_country_code3_by_name_v6() and geoip_country_name_by_name_v6() are not mentioned in doc at all.

The doc example gets the country of the website.
However, to get the country of your website’s «visitor/user»,
use the «user’s» IP address as parameter:

$country = geoip_country_code_by_name ( $_SERVER [ ‘REMOTE_ADDR’ ]);
?>

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