PHP Velho Oeste 2024

geoip_record_by_name

(PECL geoip >= 0.2.0)

geoip_record_by_nameВозвращает подробную информацию об адресе, найденном в базе GeoIP

Описание

geoip_record_by_name(string $hostname): array

Функция 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

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

hostname

Имя хоста или 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.

<?php
$record
= geoip_record_by_name('www.example.com');
if (
$record) {
print_r($record);
}
?>

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

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
)

add a note add a note

User Contributed Notes 3 notes

up
6
wouter dot berben at ignitione dot com
12 years ago
This function returns a PHP Notice when a address can not be found.
up
4
etbwebdesign.com
11 years ago
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.
<?php
# 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.
up
-7
bogdan at grabinski dot com
10 years ago
I use this additional code in my error handler class to suppress "PHP Notice" send by the function geoip_record_by_name() in case of IP not found. No e-mails or echo on display is welcome for this notice in development environment.

public static function Handler($errNo, $errStr, $errFile, $errLine){
   $backtrace = ErrorHandler::GetBacktrace(2);
   // detection of unwelcome  PHP Notice and its ignoring.
   if($errNo == E_NOTICE && preg_match('/^geoip_record_by_name.*Host.*not found$/', $errStr)){
            return;
        }

The rest of normal error handler code remains.
To Top