我想通过他们的IP吸引游客…现在我正在使用这个(http://api.hostip.info/country.php?ip=......)
这是我的代码:
<?php
if (isset($_SERVER['HTTP_CLIENT_IP']))
{
$real_ip_adress = $_SERVER['HTTP_CLIENT_IP'];
}
if (isset($_SERVER['HTTP_X_FORWARDED_FOR']))
{
$real_ip_adress = $_SERVER['HTTP_X_FORWARDED_FOR'];
}
else
{
$real_ip_adress = $_SERVER['REMOTE_ADDR'];
}
$cip = $real_ip_adress;
$iptolocation = 'http://api.hostip.info/country.php?ip=' . $cip;
$creatorlocation = file_get_contents($iptolocation);
?>
好吧,它正常工作,但问题是,这返回国家代码,如US或CA.,而不是整个国家名称,如美国或加拿大。
那么,除了hostip.info提供的这些,还有什么好的选择吗?
我知道我可以编写一些代码,最终将这两个字母转换为整个国家的名称,但我实在懒得编写包含所有国家的代码……
注:出于某种原因,我不想使用任何现成的CSV文件或任何代码,将抓取这个信息为我,像ip2country现成的代码和CSV。
在code.google上查看php-ip-2-country。他们提供的数据库每天都会更新,所以如果你拥有自己的SQL服务器,就没有必要连接到外部服务器进行检查。所以使用代码你只需要输入:
<?php
$ip = $_SERVER['REMOTE_ADDR'];
if(!empty($ip)){
require('./phpip2country.class.php');
/**
* Newest data (SQL) avaliable on project website
* @link http://code.google.com/p/php-ip-2-country/
*/
$dbConfigArray = array(
'host' => 'localhost', //example host name
'port' => 3306, //3306 -default mysql port number
'dbName' => 'ip_to_country', //example db name
'dbUserName' => 'ip_to_country', //example user name
'dbUserPassword' => 'QrDB9Y8CKMdLDH8Q', //example user password
'tableName' => 'ip_to_country', //example table name
);
$phpIp2Country = new phpIp2Country($ip,$dbConfigArray);
$country = $phpIp2Country->getInfo(IP_COUNTRY_NAME);
echo $country;
?>
示例代码(来自资源)
<?
require('phpip2country.class.php');
$dbConfigArray = array(
'host' => 'localhost', //example host name
'port' => 3306, //3306 -default mysql port number
'dbName' => 'ip_to_country', //example db name
'dbUserName' => 'ip_to_country', //example user name
'dbUserPassword' => 'QrDB9Y8CKMdLDH8Q', //example user password
'tableName' => 'ip_to_country', //example table name
);
$phpIp2Country = new phpIp2Country('213.180.138.148',$dbConfigArray);
print_r($phpIp2Country->getInfo(IP_INFO));
?>
输出
Array
(
[IP_FROM] => 3585376256
[IP_TO] => 3585384447
[REGISTRY] => RIPE
[ASSIGNED] => 948758400
[CTRY] => PL
[CNTRY] => POL
[COUNTRY] => POLAND
[IP_STR] => 213.180.138.148
[IP_VALUE] => 3585378964
[IP_FROM_STR] => 127.255.255.255
[IP_TO_STR] => 127.255.255.255
)
不确定这是否是一个新的服务,但现在(2016)在php中最简单的方法是使用geoplugin的php web服务:http://www.geoplugin.net/php.gp:
基本用法:
// GET IP ADDRESS
if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
$ip = $_SERVER['HTTP_CLIENT_IP'];
} else if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
$ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
} else if (!empty($_SERVER['REMOTE_ADDR'])) {
$ip = $_SERVER['REMOTE_ADDR'];
} else {
$ip = false;
}
// CALL THE WEBSERVICE
$ip_info = unserialize(file_get_contents('http://www.geoplugin.net/php.gp?ip='.$ip));
它们还提供了一个现成的类:http://www.geoplugin.com/_media/webservices/geoplugin.class.php.tgz?id=webservices%3Aphp&cache=cache