我希望通过他们的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);
?>
嗯,它运行正常,但问题是,这会返回美国或CA等国家/地区代码,而不是像美国或加拿大这样的整个国家/地区名称。
那么,有没有什么比hostip.info更好的替代方案呢?
我知道我可以编写一些代码,最终将这两个字母转换为整个国家/地区名称,但我只是懒得编写一个包含所有国家/地区的代码...
P.S:出于某种原因,我不想使用任何现成的CSV文件或任何能为我获取此信息的代码,例如ip2country现成代码和CSV。
答案 0 :(得分:447)
试试这个简单的PHP函数。
<?php
function ip_info($ip = NULL, $purpose = "location", $deep_detect = TRUE) {
$output = NULL;
if (filter_var($ip, FILTER_VALIDATE_IP) === FALSE) {
$ip = $_SERVER["REMOTE_ADDR"];
if ($deep_detect) {
if (filter_var(@$_SERVER['HTTP_X_FORWARDED_FOR'], FILTER_VALIDATE_IP))
$ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
if (filter_var(@$_SERVER['HTTP_CLIENT_IP'], FILTER_VALIDATE_IP))
$ip = $_SERVER['HTTP_CLIENT_IP'];
}
}
$purpose = str_replace(array("name", "\n", "\t", " ", "-", "_"), NULL, strtolower(trim($purpose)));
$support = array("country", "countrycode", "state", "region", "city", "location", "address");
$continents = array(
"AF" => "Africa",
"AN" => "Antarctica",
"AS" => "Asia",
"EU" => "Europe",
"OC" => "Australia (Oceania)",
"NA" => "North America",
"SA" => "South America"
);
if (filter_var($ip, FILTER_VALIDATE_IP) && in_array($purpose, $support)) {
$ipdat = @json_decode(file_get_contents("http://www.geoplugin.net/json.gp?ip=" . $ip));
if (@strlen(trim($ipdat->geoplugin_countryCode)) == 2) {
switch ($purpose) {
case "location":
$output = array(
"city" => @$ipdat->geoplugin_city,
"state" => @$ipdat->geoplugin_regionName,
"country" => @$ipdat->geoplugin_countryName,
"country_code" => @$ipdat->geoplugin_countryCode,
"continent" => @$continents[strtoupper($ipdat->geoplugin_continentCode)],
"continent_code" => @$ipdat->geoplugin_continentCode
);
break;
case "address":
$address = array($ipdat->geoplugin_countryName);
if (@strlen($ipdat->geoplugin_regionName) >= 1)
$address[] = $ipdat->geoplugin_regionName;
if (@strlen($ipdat->geoplugin_city) >= 1)
$address[] = $ipdat->geoplugin_city;
$output = implode(", ", array_reverse($address));
break;
case "city":
$output = @$ipdat->geoplugin_city;
break;
case "state":
$output = @$ipdat->geoplugin_regionName;
break;
case "region":
$output = @$ipdat->geoplugin_regionName;
break;
case "country":
$output = @$ipdat->geoplugin_countryName;
break;
case "countrycode":
$output = @$ipdat->geoplugin_countryCode;
break;
}
}
}
return $output;
}
?>
使用方法:
示例1:获取访问者IP地址详细信息
<?php
echo ip_info("Visitor", "Country"); // India
echo ip_info("Visitor", "Country Code"); // IN
echo ip_info("Visitor", "State"); // Andhra Pradesh
echo ip_info("Visitor", "City"); // Proddatur
echo ip_info("Visitor", "Address"); // Proddatur, Andhra Pradesh, India
print_r(ip_info("Visitor", "Location")); // Array ( [city] => Proddatur [state] => Andhra Pradesh [country] => India [country_code] => IN [continent] => Asia [continent_code] => AS )
?>
示例2:获取任何IP地址的详细信息。 [支持IPV4&amp; IPV6]
<?php
echo ip_info("173.252.110.27", "Country"); // United States
echo ip_info("173.252.110.27", "Country Code"); // US
echo ip_info("173.252.110.27", "State"); // California
echo ip_info("173.252.110.27", "City"); // Menlo Park
echo ip_info("173.252.110.27", "Address"); // Menlo Park, California, United States
print_r(ip_info("173.252.110.27", "Location")); // Array ( [city] => Menlo Park [state] => California [country] => United States [country_code] => US [continent] => North America [continent_code] => NA )
?>
答案 1 :(得分:47)
您可以使用http://www.geoplugin.net/
中的简单API$xml = simplexml_load_file("http://www.geoplugin.net/xml.gp?ip=".getRealIpAddr());
echo $xml->geoplugin_countryName ;
echo "<pre>";
foreach ($xml as $key => $value)
{
echo $key , "= " , $value , " \n" ;
}
echo "</pre>";
使用的功能
function getRealIpAddr()
{
if (!empty($_SERVER['HTTP_CLIENT_IP'])) //check ip from share internet
{
$ip=$_SERVER['HTTP_CLIENT_IP'];
}
elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) //to check ip is pass from proxy
{
$ip=$_SERVER['HTTP_X_FORWARDED_FOR'];
}
else
{
$ip=$_SERVER['REMOTE_ADDR'];
}
return $ip;
}
输出
United States
geoplugin_city= San Antonio
geoplugin_region= TX
geoplugin_areaCode= 210
geoplugin_dmaCode= 641
geoplugin_countryCode= US
geoplugin_countryName= United States
geoplugin_continentCode= NA
geoplugin_latitude= 29.488899230957
geoplugin_longitude= -98.398696899414
geoplugin_regionCode= TX
geoplugin_regionName= Texas
geoplugin_currencyCode= USD
geoplugin_currencySymbol= $
geoplugin_currencyConverter= 1
它让你可以玩很多选项
由于
:)
答案 2 :(得分:23)
我尝试过Chandra的答案,但我的服务器配置不允许 file_get_contents()
PHP Warning: file_get_contents() URL file-access is disabled in the server configuration
我修改了Chandra的代码,以便它也适用于使用cURL的服务器:
function ip_visitor_country()
{
$client = @$_SERVER['HTTP_CLIENT_IP'];
$forward = @$_SERVER['HTTP_X_FORWARDED_FOR'];
$remote = $_SERVER['REMOTE_ADDR'];
$country = "Unknown";
if(filter_var($client, FILTER_VALIDATE_IP))
{
$ip = $client;
}
elseif(filter_var($forward, FILTER_VALIDATE_IP))
{
$ip = $forward;
}
else
{
$ip = $remote;
}
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://www.geoplugin.net/json.gp?ip=".$ip);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
$ip_data_in = curl_exec($ch); // string
curl_close($ch);
$ip_data = json_decode($ip_data_in,true);
$ip_data = str_replace('"', '"', $ip_data); // for PHP 5.2 see stackoverflow.com/questions/3110487/
if($ip_data && $ip_data['geoplugin_countryName'] != null) {
$country = $ip_data['geoplugin_countryName'];
}
return 'IP: '.$ip.' # Country: '.$country;
}
echo ip_visitor_country(); // output Coutry name
?>
希望有所帮助; - )
答案 3 :(得分:12)
实际上,您可以调用http://api.hostip.info/?ip=123.125.114.144来获取以XML格式显示的信息。
答案 4 :(得分:11)
使用MaxMind GeoIP(如果您还没准备好支付GeoIPLite)。
$gi = geoip_open('GeoIP.dat', GEOIP_MEMORY_CACHE);
$country = geoip_country_code_by_addr($gi, $_SERVER['REMOTE_ADDR']);
geoip_close($gi);
答案 5 :(得分:10)
使用以下服务
1)http://api.hostip.info/get_html.php?ip=12.215.42.19
2)
$json = file_get_contents('http://freegeoip.appspot.com/json/66.102.13.106');
$expression = json_decode($json);
print_r($expression);
答案 6 :(得分:10)
从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
)
答案 7 :(得分:10)
我们可以使用geobytes.com来获取使用用户IP地址的位置
$user_ip = getIP();
$meta_tags = get_meta_tags('http://www.geobytes.com/IPLocator.htm?GetLocation&template=php3.txt&IPAddress=' . $user_ip);
echo '<pre>';
print_r($meta_tags);
它会返回这样的数据
Array(
[known] => true
[locationcode] => USCALANG
[fips104] => US
[iso2] => US
[iso3] => USA
[ison] => 840
[internet] => US
[countryid] => 254
[country] => United States
[regionid] => 126
[region] => California
[regioncode] => CA
[adm1code] =>
[cityid] => 7275
[city] => Los Angeles
[latitude] => 34.0452
[longitude] => -118.2840
[timezone] => -08:00
[certainty] => 53
[mapbytesremaining] => Free
)
获取用户IP的功能
function getIP(){
if (isset($_SERVER["HTTP_X_FORWARDED_FOR"])){
$pattern = "/^(([1-9]?[0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5]).){3}([1-9]?[0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])$/";
if(preg_match($pattern, $_SERVER["HTTP_X_FORWARDED_FOR"])){
$userIP = $_SERVER["HTTP_X_FORWARDED_FOR"];
}else{
$userIP = $_SERVER["REMOTE_ADDR"];
}
}
else{
$userIP = $_SERVER["REMOTE_ADDR"];
}
return $userIP;
}
答案 8 :(得分:9)
尝试这个简单的一行代码,您将从他们的ip远程地址获得访客的国家和城市。
$tags = get_meta_tags('http://www.geobytes.com/IpLocator.htm?GetLocation&template=php3.txt&IpAddress=' . $_SERVER['REMOTE_ADDR']);
echo $tags['country'];
echo $tags['city'];
答案 9 :(得分:9)
您可以使用http://ip-api.com中的网络服务
在您的PHP代码中,执行以下操作:
<?php
$ip = $_REQUEST['REMOTE_ADDR']; // the IP address to query
$query = @unserialize(file_get_contents('http://ip-api.com/php/'.$ip));
if($query && $query['status'] == 'success') {
echo 'Hello visitor from '.$query['country'].', '.$query['city'].'!';
} else {
echo 'Unable to get location';
}
?>
查询还有许多其他信息:
array (
'status' => 'success',
'country' => 'COUNTRY',
'countryCode' => 'COUNTRY CODE',
'region' => 'REGION CODE',
'regionName' => 'REGION NAME',
'city' => 'CITY',
'zip' => ZIP CODE,
'lat' => LATITUDE,
'lon' => LONGITUDE,
'timezone' => 'TIME ZONE',
'isp' => 'ISP NAME',
'org' => 'ORGANIZATION NAME',
'as' => 'AS NUMBER / NAME',
'query' => 'IP ADDRESS USED FOR QUERY',
)
答案 10 :(得分:8)
由Perl社区在CPAN
维护的ip-&gt;国家数据库维护良好的平面文件版本访问这些文件不需要数据服务器,数据本身大约为515k
Higemaru编写了一个PHP包装器来与该数据进行通信:php-ip-country-fast
答案 11 :(得分:6)
许多不同的方法......
您可以使用的第三方服务是http://ipinfodb.com。它们提供主机名,地理位置和其他信息。
在此处注册API密钥:http://ipinfodb.com/register.php。这将允许您从他们的服务器检索结果,如果没有它将无法工作。
复制并通过以下PHP代码:
$ipaddress = $_SERVER['REMOTE_ADDR'];
$api_key = 'YOUR_API_KEY_HERE';
$data = file_get_contents("http://api.ipinfodb.com/v3/ip-city/?key=$api_key&ip=$ipaddress&format=json");
$data = json_decode($data);
$country = $data['Country'];
<强>缺点:强>
从他们的网站引用:
我们的免费API使用的IP2Location Lite版本较低 精度。
此功能将使用http://www.netip.de/服务返回国家/地区名称。
$ipaddress = $_SERVER['REMOTE_ADDR'];
function geoCheckIP($ip)
{
$response=@file_get_contents('http://www.netip.de/search?query='.$ip);
$patterns=array();
$patterns["country"] = '#Country: (.*?) #i';
$ipInfo=array();
foreach ($patterns as $key => $pattern)
{
$ipInfo[$key] = preg_match($pattern,$response,$value) && !empty($value[1]) ? $value[1] : 'not found';
}
return $ipInfo;
}
print_r(geoCheckIP($ipaddress));
<强>输出:强>
Array ( [country] => DE - Germany ) // Full Country Name
答案 12 :(得分:5)
我的服务ipdata.co提供5种语言的国家/地区名称!以及来自任何IPv4或IPv6地址的组织,货币,时区,呼叫代码,标志,移动运营商数据,代理数据和Tor退出节点状态数据。
这个答案使用了&#39;测试&#39; API密钥非常有限,仅用于测试几个调用。 Signup用于您自己的免费API密钥,每天最多可获得1500个请求以进行开发。
它还具有极高的可扩展性,全球有10个地区,每个地区每秒可处理10,000个请求!
选项包括;英语(en),德语(de),日语(ja),法语(fr)和简体中文(za-CH)
false
答案 13 :(得分:4)
不确定这是否是新服务,但现在(2016)php中最简单的方法是使用geoplugin的php网络服务: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
答案 14 :(得分:2)
我在项目中使用了一个简短的答案。 在我的回答中,我认为你有访问者的IP地址。
A B A_ratio B_ratio
0 5 10 0.333333 0.666667
1 15 3 0.833333 0.166667
答案 15 :(得分:2)
带有IP address to country API
的单行班次echo file_get_contents('https://ipapi.co/8.8.8.8/country_name/');
> United States
示例:
https://ipapi.co/country_name/ - 您所在的国家/地区
https://ipapi.co/8.8.8.8/country_name/ - 国家/地区IP 8.8.8.8
答案 16 :(得分:2)
将 127.0.0.1
替换为访问者IpAddress。
$country = geoip_country_name_by_name('127.0.0.1');
安装说明为here和read this to know how to obtain City, State, Country, Longitude, Latitude, etc...
答案 17 :(得分:2)
您可以使用http://ipinfo.io/获取IP地址的详细信息。它易于使用。
<?php
function ip_details($ip)
{
$json = file_get_contents("http://ipinfo.io/{$ip}");
$details = json_decode($json);
return $details;
}
$details = ip_details(YoUR IP ADDRESS);
echo $details->city;
echo "<br>".$details->country;
echo "<br>".$details->org;
echo "<br>".$details->hostname; /
?>
答案 18 :(得分:2)
我正在使用ipinfodb.com
api并准确地获取您正在寻找的内容。
它完全免费,你只需要注册就可以获得你的api密钥。您可以通过从他们的网站下载来包含他们的php类,或者您可以使用url格式来检索信息。
这就是我正在做的事情:
我在他的脚本中包含他们的php类并使用以下代码:
$ipLite = new ip2location_lite;
$ipLite->setKey('your_api_key');
if(!$_COOKIE["visitorCity"]){ //I am using cookie to store information
$visitorCity = $ipLite->getCity($_SERVER['REMOTE_ADDR']);
if ($visitorCity['statusCode'] == 'OK') {
$data = base64_encode(serialize($visitorCity));
setcookie("visitorCity", $data, time()+3600*24*7); //set cookie for 1 week
}
}
$visitorCity = unserialize(base64_decode($_COOKIE["visitorCity"]));
echo $visitorCity['countryName'].' Region'.$visitorCity['regionName'];
多数民众赞成。
答案 19 :(得分:1)
我写了一个基于“钱德拉·纳卡”答案的课程。希望它可以帮助人们将信息从geoplugin保存到会话中,以便在调用信息时加快加载速度。还将这些值保存到私有数组中,因此在相同的代码中进行调用是最快的。
class Geo {
private $_ip = null;
private $_useSession = true;
private $_sessionNameData = 'GEO_SESSION_DATA';
private $_hasError = false;
private $_geoData = [];
const PURPOSE_SUPPORT = [
"all", "*", "location",
"request",
"latitude",
"longitude",
"accuracy",
"timezonde",
"currencycode",
"currencysymbol",
"currencysymbolutf8",
"country",
"countrycode",
"state", "region",
"city",
"address",
"continent",
"continentcode"
];
const CONTINENTS = [
"AF" => "Africa",
"AN" => "Antarctica",
"AS" => "Asia",
"EU" => "Europe",
"OC" => "Australia (Oceania)",
"NA" => "North America",
"SA" => "South America"
];
function __construct($ip = null, $deepDetect = true, $useSession = true)
{
// define the session useage within this class
$this->_useSession = $useSession;
$this->_startSession();
// define a ip as far as possible
$this->_ip = $this->_defineIP($ip, $deepDetect);
// check if the ip was set
if (!$this->_ip) {
$this->_hasError = true;
return $this;
}
// define the geoData
$this->_geoData = $this->_fetchGeoData();
return $this;
}
function get($purpose)
{
// making sure its lowercase
$purpose = strtolower($purpose);
// makeing sure there are no error and the geodata is not empty
if ($this->_hasError || !count($this->_geoData) && !in_array($purpose, self::PURPOSE_SUPPORT)) {
return 'error';
}
if (in_array($purpose, ['*', 'all', 'location'])) {
return $this->_geoData;
}
if ($purpose === 'state') $purpose = 'region';
return (isset($this->_geoData[$purpose]) ? $this->_geoData[$purpose] : 'missing: '.$purpose);
}
private function _fetchGeoData()
{
// check if geo data was set before
if (count($this->_geoData)) {
return $this->_geoData;
}
// check possible session
if ($this->_useSession && ($sessionData = $this->_getSession($this->_sessionNameData))) {
return $sessionData;
}
// making sure we have a valid ip
if (!$this->_ip || $this->_ip === '127.0.0.1') {
return [];
}
// fetch the information from geoplusing
$ipdata = @json_decode($this->curl("http://www.geoplugin.net/json.gp?ip=" . $this->_ip));
// check if the data was fetched
if (!@strlen(trim($ipdata->geoplugin_countryCode)) === 2) {
return [];
}
// make a address array
$address = [$ipdata->geoplugin_countryName];
if (@strlen($ipdata->geoplugin_regionName) >= 1)
$address[] = $ipdata->geoplugin_regionName;
if (@strlen($ipdata->geoplugin_city) >= 1)
$address[] = $ipdata->geoplugin_city;
// makeing sure the continentCode is upper case
$continentCode = strtoupper(@$ipdata->geoplugin_continentCode);
$geoData = [
'request' => @$ipdata->geoplugin_request,
'latitude' => @$ipdata->geoplugin_latitude,
'longitude' => @$ipdata->geoplugin_longitude,
'accuracy' => @$ipdata->geoplugin_locationAccuracyRadius,
'timezonde' => @$ipdata->geoplugin_timezone,
'currencycode' => @$ipdata->geoplugin_currencyCode,
'currencysymbol' => @$ipdata->geoplugin_currencySymbol,
'currencysymbolutf8' => @$ipdata->geoplugin_currencySymbol_UTF8,
'city' => @$ipdata->geoplugin_city,
'region' => @$ipdata->geoplugin_regionName,
'country' => @$ipdata->geoplugin_countryName,
'countrycode' => @$ipdata->geoplugin_countryCode,
'continent' => self::CONTINENTS[$continentCode],
'continentcode' => $continentCode,
'address' => implode(", ", array_reverse($address))
];
if ($this->_useSession) {
$this->_setSession($this->_sessionNameData, $geoData);
}
return $geoData;
}
private function _startSession()
{
// only start a new session when the status is 'none' and the class
// requires a session
if ($this->_useSession && session_status() === PHP_SESSION_NONE) {
session_start();
}
}
private function _defineIP($ip, $deepDetect)
{
// check if the ip was set before
if ($this->_ip) {
return $this->_ip;
}
// check if the ip given is valid
if (filter_var($ip, FILTER_VALIDATE_IP)) {
return $ip;
}
// try to get the ip from the REMOTE_ADDR
$ip = filter_input(INPUT_SERVER, 'REMOTE_ADDR', FILTER_VALIDATE_IP);
// check if we need to end the search for a IP if the REMOTE_ADDR did not
// return a valid and the deepDetect is false
if (!$deepDetect) {
return $ip;
}
// try to get the ip from HTTP_X_FORWARDED_FOR
if (($ip = filter_input(INPUT_SERVER, 'HTTP_X_FORWARDED_FOR', FILTER_VALIDATE_IP))) {
return $ip;
}
// try to get the ip from the HTTP_CLIENT_IP
if (($ip = filter_input(INPUT_SERVER, 'HTTP_CLIENT_IP', FILTER_VALIDATE_IP))) {
return $ip;
}
return $ip;
}
private function _hasSession($key, $filter = FILTER_DEFAULT)
{
return (isset($_SESSION[$key]) ? (bool)filter_var($_SESSION[$key], $filter) : false);
}
private function _getSession($key, $filter = FILTER_DEFAULT)
{
if ($this->_hasSession($key, $filter)) {
$value = filter_var($_SESSION[$key], $filter);
if (@json_decode($value)) {
return json_decode($value, true);
}
return filter_var($_SESSION[$key], $filter);
} else {
return false;
}
}
private function _setSession($key, $value)
{
if (is_array($value)) {
$value = json_encode($value);
}
$_SESSION[$key] = $value;
}
function emptySession($key) {
if (!$this->_hasSession($key)) {
return;
}
$_SESSION[$key] = null;
unset($_SESSION[$key]);
}
function curl($url)
{
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$output = curl_exec($ch);
curl_close($ch);
return $output;
}
}
在此类中回答“ op”问题,您可以致电
$country = (new \Geo())->get('country'); // United Kingdom
其他可用属性是:
$geo = new \Geo('185.35.50.4');
var_dump($geo->get('*')); // allias all / location
var_dump($geo->get('country'));
var_dump($geo->get('countrycode'));
var_dump($geo->get('state')); // allias region
var_dump($geo->get('city'));
var_dump($geo->get('address'));
var_dump($geo->get('continent'));
var_dump($geo->get('continentcode'));
var_dump($geo->get('request'));
var_dump($geo->get('latitude'));
var_dump($geo->get('longitude'));
var_dump($geo->get('accuracy'));
var_dump($geo->get('timezonde'));
var_dump($geo->get('currencyCode'));
var_dump($geo->get('currencySymbol'));
var_dump($geo->get('currencySymbolUTF8'));
返回
array(15) {
["request"]=>
string(11) "185.35.50.4"
["latitude"]=>
string(7) "51.4439"
["longitude"]=>
string(7) "-0.1854"
["accuracy"]=>
string(2) "50"
["timezonde"]=>
string(13) "Europe/London"
["currencycode"]=>
string(3) "GBP"
["currencysymbol"]=>
string(2) "£"
["currencysymbolutf8"]=>
string(2) "£"
["city"]=>
string(10) "Wandsworth"
["region"]=>
string(10) "Wandsworth"
["country"]=>
string(14) "United Kingdom"
["countrycode"]=>
string(2) "GB"
["continent"]=>
string(6) "Europe"
["continentcode"]=>
string(2) "EU"
["address"]=>
string(38) "Wandsworth, Wandsworth, United Kingdom"
}
string(14) "United Kingdom"
string(2) "GB"
string(10) "Wandsworth"
string(10) "Wandsworth"
string(38) "Wandsworth, Wandsworth, United Kingdom"
string(6) "Europe"
string(2) "EU"
string(11) "185.35.50.4"
string(7) "51.4439"
string(7) "-0.1854"
string(2) "50"
string(13) "Europe/London"
string(3) "GBP"
string(2) "£"
string(2) "£"
答案 20 :(得分:0)
User Country API正是您所需要的。以下是使用file_get_contents()的示例代码:
$result = json_decode(file_get_contents('http://usercountry.com/v1.0/json/'.$cip), true);
$result['country']['name']; // this contains what you need
答案 21 :(得分:0)
您可以使用ipstack geo API获取访问者所在的国家和城市。您需要获取自己的ipstack API,然后使用以下代码:
<?php
$ip = $_SERVER['REMOTE_ADDR'];
$api_key = "YOUR_API_KEY";
$freegeoipjson = file_get_contents("http://api.ipstack.com/".$ip."?access_key=".$api_key."");
$jsondata = json_decode($freegeoipjson);
$countryfromip = $jsondata->country_name;
echo "Country: ". $countryfromip ."";
?>
答案 22 :(得分:0)
这只是关于get_client_ip()
功能的安全说明,此处的大多数答案已包含在get_geo_info_for_this_ip()
的主要功能中。
不要过分依赖请求标头中的IP数据,例如Client-IP
或X-Forwarded-For
,因为它们很容易被欺骗,但是您应该依赖TCP连接的源IP实际上是在我们的服务器和客户端$_SERVER['REMOTE_ADDR']
之间以it can't be spoofed
$_SERVER['HTTP_CLIENT_IP'] // can be spoofed
$_SERVER['HTTP_X_FORWARDED_FOR'] // can be spoofed
$_SERVER['REMOTE_ADDR']// can't be spoofed
可以获取欺骗性IP的国家/地区,但请记住,在任何安全模型中使用该IP(例如:禁止发送频繁请求的IP)会破坏整个安全模型。恕我直言,我喜欢使用实际的客户端IP,即使它是代理服务器的IP。
答案 23 :(得分:0)
我知道这很旧,但是我在这里尝试了其他一些解决方案,它们似乎已经过时或只是返回null。所以这就是我的方法。
使用var button = document.getElementsByClassName("square");
var clicked = [0, 0, 0, 0, 0, 0, 0, 0, 0];
for (let i = 0; i < button.length; i++) {
button[i].addEventListener("click", function() {
clicked[i] += 1;
console.log(clicked);
});
}
,不需要任何类型的注册或付款。
<div class='square'> [0] Click on me!</div><div class='square'>[1] Click on me!</div><div class='square'>[2] Click on me!</div><div class='square'>[3] Click on me!</div><div class='square'>[4] Click on me!</div><div class='square'>[5] Click on me!</div><div class='square'>[6] Click on me!</div><div class='square'>[7] Click on me!</div><div class='square'>[8] Click on me!</div>
如果您需要有关它的更多信息,这是Json的全部收益:
http://www.geoplugin.net/json.gp?ip=
答案 24 :(得分:0)
尝试
<?php
//gives you the IP address of the visitors
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 {
$ip = $_SERVER['REMOTE_ADDR'];
}
//return the country code
$url = "http://api.wipmania.com/$ip";
$country = file_get_contents($url);
echo $country;
?>
答案 25 :(得分:0)
您可以使用我的服务https://SmartIP.io,它提供任何IP地址的完整国家名称和城市名称。我们还公开了时区,货币,代理检测,TOR节点检测和加密检测。
您只需要注册并获得一个免费的API密钥,该密钥每月允许250,000个请求。
使用官方的PHP库,API调用变为:
$apiKey = "your API key";
$smartIp = new SmartIP($apiKey);
$response = $smartIp->requestIPData("8.8.8.8");
echo "\nstatus code: " . $response->{"status-code"};
echo "\ncountry name: " . $response->country->{"country-name"};
查看API文档以获取更多信息: https://smartip.io/docs
答案 26 :(得分:0)
截至2019年,MaxMind国家/地区数据库的使用方式如下:
<?php
require_once 'vendor/autoload.php';
use MaxMind\Db\Reader;
$databaseFile = 'GeoIP2-Country.mmdb';
$reader = new Reader($databaseFile);
$cc = $reader->get($_SERVER['REMOTE_ADDR'])['country']['iso_code'] # US/GB...
$reader->close();
答案 27 :(得分:0)
可以接受吗? 纯PHP
$country = geoip_country_code_by_name($_SERVER['REMOTE_ADDR']);
print $country;
ref:https://www.php.net/manual/en/function.geoip-country-code-by-name.php
答案 28 :(得分:0)
PHP代码获取国家,城市,
大陆等使用IP地址
$ip = $_SERVER["REMOTE_ADDR"];
// Use JSON encoded string and converts
// it into a PHP variable
$ipdat = @json_decode(file_get_contents(
"http://www.geoplugin.net/json.gp?ip=" . $ip));
$country = $ipdat->geoplugin_countryName;
$city = $ipdat->geoplugin_city;
$continent_name = $ipdat->geoplugin_continentName;
$latitude = $ipdat->geoplugin_latitude;
$longitude = $ipdat->geoplugin_longitude;
$currency_symbol = $ipdat->geoplugin_currencySymbol;
$currency_code = $ipdat->geoplugin_currencyCode;
$timezone = $ipdat->geoplugin_timezone;
答案 29 :(得分:0)
这是使用 guzzle 的已接受答案的更清晰且有效的版本:
您可以使用 curl 而不是 guzzle,这只是一个简单的获取请求。
function ip_info($ip = NULL, $purpose = "location", $deep_detect = TRUE) {
$output = NULL;
if (filter_var($ip, FILTER_VALIDATE_IP) === FALSE) {
$ip = $_SERVER["REMOTE_ADDR"];
if ($deep_detect) {
if (filter_var(@$_SERVER['HTTP_X_FORWARDED_FOR'], FILTER_VALIDATE_IP))
$ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
if (filter_var(@$_SERVER['HTTP_CLIENT_IP'], FILTER_VALIDATE_IP))
$ip = $_SERVER['HTTP_CLIENT_IP'];
}
}
$purpose = str_replace(array("name", "\n", "\t", " ", "-", "_"), NULL, strtolower(trim($purpose)));
$support = array("country", "countrycode", "state", "region", "city", "location", "address");
$continents = array(
"AF" => "Africa",
"AN" => "Antarctica",
"AS" => "Asia",
"EU" => "Europe",
"OC" => "Australia (Oceania)",
"NA" => "North America",
"SA" => "South America"
);
if (filter_var($ip, FILTER_VALIDATE_IP) && in_array($purpose, $support, true)) {
$client = New \GuzzleHttp\Client();
$ipdat = json_decode($client->request('GET','http://www.geoplugin.net/json.gp',$params = [
'query' => [
'ip' => $ip,
]
])->getBody()->getContents(),true);
if (strlen(trim($ipdat['geoplugin_countryCode'])) === 2) {
switch ($purpose) {
case "location":
$output = array(
"city" => $ipdat['geoplugin_city'],
"state" => $ipdat['geoplugin_regionName'],
"country" => $ipdat['geoplugin_countryName'],
"country_code" => $ipdat['geoplugin_countryCode'],
"continent" => $continents[strtoupper($ipdat['geoplugin_continentCode'])],
"continent_code" => $ipdat['geoplugin_continentCode']
);
break;
case "address":
$address = array($ipdat['geoplugin_countryName']);
if (@strlen($ipdat['geoplugin_regionName']) >= 1)
$address[] = $ipdat['geoplugin_regionName'];
if (@strlen($ipdat['geoplugin_city']) >= 1)
$address[] = $ipdat['geoplugin_city'];
$output = implode(", ", array_reverse($address));
break;
case "city":
$output = $ipdat['geoplugin_city'];
break;
case "region":
case "state":
$output = $ipdat['geoplugin_regionName'];
break;
case "country":
$output = $ipdat['geoplugin_countryName'];
break;
case "countrycode":
$output = $ipdat['geoplugin_countryCode'];
break;
}
}
}
return $output;
}
答案 30 :(得分:0)
如果您需要尽快获得国家/地区,我建议您的网络服务器使用 geoip 插件。
对于nginx here;
正确设置后,您将从 $_SERVER
变量中获取国家/地区代码。
我每秒执行大约 500(+-) 次,速度非常快。