[英]Getting visitors country from their IP
我想通過他們的 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 提供這個之外,還有什么好的選擇嗎?
我知道我可以編寫一些代碼,最終將這兩個字母變成整個國家/地區名稱,但是我懶得編寫包含所有國家/地區的代碼...
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
它讓你有很多可以玩的選擇
謝謝
:)
我嘗試了 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
?>
希望有幫助;-)
使用 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的網絡服務
在您的 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);
我們可以使用 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'];
有一個維護良好的平面文件版本的 ip->country 數據庫,由CPAN的 Perl 社區維護
訪問這些文件不需要數據服務器,數據本身大約為 515k
Higemaru 編寫了一個 PHP 包裝器來處理該數據: php-ip-country-fast
許多不同的方法來做到這一點...
您可以使用的一項第三方服務是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
我的服務ipdata.co提供 5 種語言的國家名稱! 以及來自任何 IPv4 或 IPv6 地址的組織、貨幣、時區、呼叫代碼、標志、移動運營商數據、代理數據和 Tor 出口節點狀態數據。
此答案使用非常有限的“測試”API 密鑰,僅用於測試幾個調用。 注冊您自己的免費 API 密鑰並每天收到多達 1500 個開發請求。
它還具有極強的可擴展性,全球 10 個區域,每個區域每秒能夠處理超過 10,000 個請求!
選項包括; 英語 (en)、德語 (de)、日語 (ja)、法語 (fr) 和簡體中文 (za-CH)
$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 網絡服務: 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
那可以接受嗎? 純PHP
$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; /
?>
具有IP 地址到國家/地區 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 的國家
我正在使用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;
}
我知道這很舊,但我在這里嘗試了其他一些解決方案,它們似乎已經過時或者只是返回 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
}
截至 2022 年,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();
來源: https ://github.com/maxmind/MaxMind-DB-Reader-php
我寫了一個基於“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) "£"
您可以使用此代碼片段。
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;
}
}
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
您可以使用 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 ."";
?>
這只是關於get_client_ip()
功能的安全說明,這里的大多數答案都包含在get_geo_info_for_this_ip()
的主要功能中。
不要過分依賴Client-IP
或X-Forwarded-For
等請求標頭中的 IP 數據,因為它們很容易被欺騙,但是您應該依賴於我們之間實際建立的 TCP 連接的源 IP服務器和客戶端$_SERVER['REMOTE_ADDR']
因為它不能被欺騙
$_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;
我想通過他們的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。
這是使用 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;
}
如果您需要盡快獲得國家/地區,我建議您的網絡服務器使用 geoip 插件。
對於這里的 nginx ;
正確設置后,您將從$_SERVER
變量中獲取國家代碼。
我每秒執行大約 500(+-) 次,非常快。
只需 4 行代碼即可實現這一目標!
$user_ip = '0.0.0.0';
$user_ip = $_SERVER['REMOTE_ADDR'];
$close_url = stream_context_create(array('http' => array('header'=>'Connection: close\r\n')));
$user_country = json_decode(file_get_contents("https://ipinfo.io/$user_ip/json",false,$close_url));
echo "Yes! we ship to your country: <b>" . $user_country->country . "</b>";
//輸出是的! 我們運送到您的國家美國
注意: $close_url用於在獲取內容后盡快結束 file_get_contents,它提高了請求的速度 x5。
如果您想顯示完整的國家/地區名稱,您可以點擊下方查看如何操作。
//echo "世界和平";
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.