我想通过他们的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);
?>
嗯,它工作正常,但问题是,这返回的国家/地区代码,如美国或加拿大,而不是像美国或加拿大这样的整个国家/地区名称。
那么,除了hostip.info 提供这个之外,有什么好的选择吗?
我知道我可以写一些代码,最终将这两个字母变成整个国家名称,但我懒得写一个包含所有国家的代码......
PS:出于某种原因,我不想使用任何现成的CSV文件或任何可以为我获取此信息的代码,例如ip2country现成的代码和CSV。
试试这个简单的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 和 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 )
?>
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
它让你有很多选择,你可以玩
谢谢
:)
我尝试了钱德拉的答案,但我的服务器配置不允许file_get_contents()
PHP Warning: file_get_contents() URL file-access is disabled in the server configuration
我修改了钱德拉的代码,使其也适用于使用 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
?>
希望有帮助;-)
使用MaxMind GeoIP(如果您还没有准备好付款,也可以使用GeoIPLite)。
$gi = geoip_open('GeoIP.dat', GEOIP_MEMORY_CACHE);
$country = geoip_country_code_by_addr($gi, $_SERVER['REMOTE_ADDR']);
geoip_close($gi);
您可以使用 http://ip-api.com
的 Web 服务在你的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',
)
实际上,您可以调用 http://api.hostip.info/?ip=123.125.114.144 来获取以 XML 形式呈现的信息。
从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
)
使用以下服务
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);
3) http://ipinfodb.com/ip_location_api.php
我们可以使用 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;
}
试试这个简单的一行代码,您将从他们的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'];
<</div>
div class="one_answers"> 有一个维护良好的 ip->country 数据库的平面文件版本,由 Perl 社区在 CPAN 维护
访问这些文件不需要数据服务器,数据本身大约是515k
Higemaru编写了一个PHP包装器来与这些数据进行对话:php-ip-country-fast
许多不同的方法...
解决方案#1:
您可以使用的一项第三方服务是 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版本,该版本提供较低的 准确性。
解决方案#2:
此函数将使用 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
我的服务 ipdata.co 提供5种语言的国家名称!以及来自任何 IPv4 或 IPv6 地址的组织、货币、时区、呼叫代码、标志、移动运营商数据、代理数据和 Tor 出口节点状态数据。
此答案使用非常有限的"测试"API 密钥,仅用于测试几个调用。注册您自己的免费 API 密钥,每天最多可获得 1500 个开发请求。
它还具有极强的可扩展性,全球 10 个区域每个区域每秒能够处理>10,000 个请求!
选项包括;英语、德语、日语、法语和简体中文
$ip = '74.125.230.195';
$details = json_decode(file_get_contents("https://api.ipdata.co/{$ip}?api-key=test"));
echo $details->country_name;
//United States
echo $details->city;
//Mountain View
$details = json_decode(file_get_contents("https://api.ipdata.co/{$ip}?api-key=test/zh-CN"));
echo $details->country_name;
//美国
不确定这是否是一项新服务,但现在(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
这是可以接受的吗?纯菲律宾比索
$country = geoip_country_code_by_name($_SERVER['REMOTE_ADDR']);
print $country;
参考: https://www.php.net/manual/en/function.geoip-country-code-by-name.php
您可以使用 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; /
?>
国家/地区 API 的 IP 地址的单行
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 的国家/地区
我正在使用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'];
就是这样。
将127.0.0.1
替换为访问者 IpAddress。
$country = geoip_country_name_by_name('127.0.0.1');
安装说明在这里,阅读此内容以了解如何获取城市,州,国家,经度,纬度等...
我有一个简短的答案,我已经在一个项目中使用了。在我的回答中,我认为您有访问者IP地址。
$ip = "202.142.178.220";
$ipdat = @json_decode(file_get_contents("http://www.geoplugin.net/json.gp?ip=" . $ip));
//get ISO2 country code
if(property_exists($ipdat, 'geoplugin_countryCode')) {
echo $ipdat->geoplugin_countryCode;
}
//get country full name
if(property_exists($ipdat, 'geoplugin_countryName')) {
echo $ipdat->geoplugin_countryName;
}
我根据"Chandra Nakka"的答案写了一个类。希望它可以帮助人们将信息从地理插件保存到会话中,以便在调用信息时加载速度更快。它还将值保存到私有数组中,因此在同一代码中调用是最快的。
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) "£"
这很旧,但我在这里尝试了其他一些解决方案,它们似乎已经过时或只是返回 null。所以我就是这样做的。
使用不需要任何类型的注册或支付服务费用的http://www.geoplugin.net/json.gp?ip=
。
function get_client_ip_server() {
$ipaddress = '';
if (isset($_SERVER['HTTP_CLIENT_IP']))
$ipaddress = $_SERVER['HTTP_CLIENT_IP'];
else if(isset($_SERVER['HTTP_X_FORWARDED_FOR']))
$ipaddress = $_SERVER['HTTP_X_FORWARDED_FOR'];
else if(isset($_SERVER['HTTP_X_FORWARDED']))
$ipaddress = $_SERVER['HTTP_X_FORWARDED'];
else if(isset($_SERVER['HTTP_FORWARDED_FOR']))
$ipaddress = $_SERVER['HTTP_FORWARDED_FOR'];
else if(isset($_SERVER['HTTP_FORWARDED']))
$ipaddress = $_SERVER['HTTP_FORWARDED'];
else if(isset($_SERVER['REMOTE_ADDR']))
$ipaddress = $_SERVER['REMOTE_ADDR'];
else
$ipaddress = 'UNKNOWN';
return $ipaddress;
}
$ipaddress = get_client_ip_server();
function getCountry($ip){
$curlSession = curl_init();
curl_setopt($curlSession, CURLOPT_URL, 'http://www.geoplugin.net/json.gp?ip='.$ip);
curl_setopt($curlSession, CURLOPT_BINARYTRANSFER, true);
curl_setopt($curlSession, CURLOPT_RETURNTRANSFER, true);
$jsonData = json_decode(curl_exec($curlSession));
curl_close($curlSession);
return $jsonData->geoplugin_countryCode;
}
echo "County: " .getCountry($ipaddress);
如果你想要关于它的额外信息,这是 Json 的完整回报:
{
"geoplugin_request":"IP_ADDRESS",
"geoplugin_status":200,
"geoplugin_delay":"2ms",
"geoplugin_credit":"Some of the returned data includes GeoLite data created by MaxMind, available from <a href='http://www.maxmind.com'>http://www.maxmind.com</a>.",
"geoplugin_city":"Current City",
"geoplugin_region":"Region",
"geoplugin_regionCode":"Region Code",
"geoplugin_regionName":"Region Name",
"geoplugin_areaCode":"",
"geoplugin_dmaCode":"650",
"geoplugin_countryCode":"US",
"geoplugin_countryName":"United States",
"geoplugin_inEU":0,
"geoplugin_euVATrate":false,
"geoplugin_continentCode":"NA",
"geoplugin_continentName":"North America",
"geoplugin_latitude":"37.5563",
"geoplugin_longitude":"-99.9413",
"geoplugin_locationAccuracyRadius":"5",
"geoplugin_timezone":"America/Chicago",
"geoplugin_currencyCode":"USD",
"geoplugin_currencySymbol":"$",
"geoplugin_currencySymbol_UTF8":"$",
"geoplugin_currencyConverter":1
}
您可以使用此代码截图。
if($a = unserialize(file_get_contents('http://www.geoplugin.net/php.gp?ip='.$_SERVER['REMOTE_ADDR']))){
$countrycode= $a['geoplugin_countryCode'];
if ($countrycode=='UK' ){
header( 'Location: https://www.example.co.uk/' ) ;exit;
}
}
> 截至 2022 年,MaxMind 国家数据库的使用方式如下:
<?php
require_once 'vendor/autoload.php';
use MaxMindDbReader;
$databaseFile = 'GeoIP2-Country.mmdb';
$reader = new Reader($databaseFile);
$cc = $reader->get($_SERVER['REMOTE_ADDR'])['country']['iso_code'] # US/GB...
$reader->close();
<小时 />源:https://github.com/maxmind/MaxMind-DB-Reader-php
用户国家/地区 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
您可以使用ipstack地理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 ."";
?>
来源:使用 ipstack API 在 PHP 中获取访问者的国家和城市
关于get_client_ip()
功能的安全说明,这里的大多数答案都包含在get_geo_info_for_this_ip()
的主要功能中。
不要过分依赖请求标头中的 IP 数据,如 Client-IP
或 X-Forwarded-For
,因为它们很容易被欺骗,但是您应该依赖在我们的服务器和$_SERVER['REMOTE_ADDR']
客户端之间实际建立的 TCP 连接的源 IP,因为它不能被欺骗
$_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。
尝试
<?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;
?>
我的服务: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
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;