This function returns a PHP Notice when a address can not be found.
(PECL geoip >= 0.2.0)
geoip_record_by_name — 返回 GeoIP 数据库中详细的城市信息
geoip_record_by_name() 函数将会返回主机或者 IP 地址所对应的记录信息。
该函数在 GeoLite City 版本和商业 GeoIP City 版本中可用。 版本不对的话,将会抛出一个警告。
返回的关联数组不同的键名对应如下:
hostname
所要查找的主机或者 IP 地址。
成功,返回关联数组,未找到相关信息则返回 false
。
版本 | 说明 |
---|---|
PECL geoip 1.0.4 | 给 GeoIP 1.4.4及以上版本的库添加 continent_code 字段。 |
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 )
This function returns a PHP Notice when a address can not be found.
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.
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.