Ich möchte Besucher über ihre IP-Adresse erreichen ... Im Moment verwende ich dieses ( http://api.hostip.info/country.php?ip= ......)
Hier ist mein Code:
<?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);
?>
Nun, es funktioniert einwandfrei, aber die Sache ist, dass der Ländercode wie US oder CA und nicht der ganze Ländername wie USA oder Kanada zurückgegeben wird.
Gibt es eine gute Alternative zu hostip.info, die dies anbietet?
Ich weiß, dass ich einfach einen Code schreiben kann, der diese beiden Buchstaben schließlich in ganze Ländernamen umwandeln wird, aber ich bin einfach zu faul, um einen Code zu schreiben, der alle Länder enthält ...
P.S: Aus irgendeinem Grund möchte ich keine vorgefertigten CSV-Dateien oder Codes verwenden, die diese Informationen für mich abrufen, z. B. ip2country-Code und CSV.
Probieren Sie diese einfache PHP - Funktion aus.
<?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;
}
?>
Wie benutzt man:
Beispiel1: IP-Adressdetails der Besucher abrufen
<?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 )
?>
Beispiel 2: Ermitteln Sie Details zu einer beliebigen IP-Adresse. [Unterstützt IPV4 und 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 )
?>
Sie können eine einfache API verwenden von http://www.geoplugin.net/
$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>";
Funktion verwendet
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;
}
Ausgabe
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
Sie haben so viele Optionen, mit denen Sie herumspielen können
Vielen Dank
:)
Ich habe Chandras Antwort versucht, aber meine Serverkonfiguration erlaubt nicht file_get_contents ()
PHP Warning: file_get_contents() URL file-access is disabled in the server configuration
Ich habe Chandras Code so geändert, dass er auch für Server wie diesen mit cURL funktioniert:
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
?>
Hoffentlich hilft das ;-)
Tatsächlich können Sie http://api.hostip.info/?ip=123.125.114.144 aufrufen, um die Informationen zu erhalten, die in XML angezeigt werden.
Verwenden Sie MaxMind GeoIP (oder GeoIPLite, wenn Sie nicht zur Bezahlung bereit sind).
$gi = geoip_open('GeoIP.dat', GEOIP_MEMORY_CACHE);
$country = geoip_country_code_by_addr($gi, $_SERVER['REMOTE_ADDR']);
geoip_close($gi);
Verwenden Sie folgende Dienste
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);
Wir können geobytes.com verwenden, um den Standort über die Benutzer-IP-Adresse abzurufen
$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);
es werden Daten wie folgt zurückgegeben
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
)
Funktion zum Abrufen der Benutzer-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;
}
Check out php-ip-2-country von code.google. Die von ihnen bereitgestellte Datenbank wird täglich aktualisiert, sodass für die Überprüfung, ob Sie Ihren eigenen SQL-Server hosten, keine Verbindung zu einem externen Server hergestellt werden muss. Mit dem Code müssten Sie also nur Folgendes eingeben:
<?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;
?>
Beispielcode _ (von der Ressource)
<?
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));
?>
Ausgabe
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
)
Probieren Sie diesen einfachen Code aus. Sie erhalten das Land und die Stadt der Besucher über ihre IP-Remote-Adresse.
$tags = get_meta_tags('http://www.geobytes.com/IpLocator.htm?GetLocation&template=php3.txt&IpAddress=' . $_SERVER['REMOTE_ADDR']);
echo $tags['country'];
echo $tags['city'];
Es gibt eine gut gewartete Flat-File-Version der ip-> country-Datenbank, die von der Perl-Community unter CPAN verwaltet wird
Für den Zugriff auf diese Dateien ist kein Datenserver erforderlich, und die Daten selbst betragen ungefähr 515 KB
Higemaru hat einen Wrapper PHP geschrieben, um mit diesen Daten zu sprechen: php-ip-country-fast
Sie können einen Web-Service von http://ip-api.com verwenden.
in Ihrem PHP-Code wie folgt vorgehen:
<?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';
}
?>
die Abfrage hat viele andere Informationen:
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',
)
Viele verschiedene Möglichkeiten, dies zu tun ...
Ein Drittanbieter-Service, den Sie verwenden könnten, ist http://ipinfodb.com . Sie enthalten den Hostnamen, die Geolocation und zusätzliche Informationen.
Registrieren Sie sich hier für einen API-Schlüssel: http://ipinfodb.com/register.php . Dadurch können Sie die Ergebnisse von ihrem Server abrufen, ohne dass dies nicht funktioniert.
Kopieren Sie den folgenden PHP - Code und fügen Sie ihn ein:
$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'];
Nachteil:
Zitieren von ihrer Website:
Unsere kostenlose API verwendet die Version IP2Location Lite, die niedrigere .__-Werte bietet. Richtigkeit.
Diese Funktion gibt den Ländernamen mithilfe des Dienstes http://www.netip.de/ zurück.
$ipaddress = $_SERVER['REMOTE_ADDR'];
function geoCheckIP($ip)
{
[email protected]_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));
Ausgabe:
Array ( [country] => DE - Germany ) // Full Country Name
Mein Service ipdata.co gibt den Ländernamen in 5 Sprachen an! Neben Organisation, Währung, Zeitzone, Anrufcode, Kennung, Mobile Carrier-Daten, Proxy-Daten und Statusdaten für den Tor Exit-Knoten von jeder IPv4- oder IPv6-Adresse.
Diese Antwort verwendet einen "Test" -API-Schlüssel, der sehr begrenzt ist und nur zum Testen einiger Aufrufe gedacht ist. Signup für Ihren eigenen Free API Key und erhalten Sie täglich bis zu 1500 Anfragen für die Entwicklung.
Mit 10 Regionen auf der ganzen Welt, die jeweils mehr als 10.000 Anfragen pro Sekunde verarbeiten können, ist sie äußerst skalierbar!
Die Optionen umfassen: Englisch (en), Deutsch (de), Japanisch (ja), Französisch (fr) und Vereinfachtes Chinesisch (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;
//美国
Nicht sicher, ob dies ein neuer Dienst ist, aber jetzt (2016) ist der einfachste Weg in PHP, den PHP-Webdienst von Geoplugin zu verwenden: http://www.geoplugin.net/php.gp :
Grundlegende Verwendung:
// 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));
Sie bieten auch eine fertige Klasse: http://www.geoplugin.com/_media/webservices/geoplugin.class.php.tgz?id=webservices%3Aphp&cache=cache
Ich verwende ipinfodb.com
api und erhalte genau das, wonach Sie suchen.
Es ist völlig kostenlos. Sie müssen sich nur bei ihnen registrieren, um Ihren API-Schlüssel zu erhalten. Sie können ihre PHP-Klasse einschließen, indem Sie von ihrer Website herunterladen, oder Sie können das URL-Format verwenden, um Informationen abzurufen.
Folgendes mache ich:
Ich habe ihre PHP-Klasse in mein Skript aufgenommen und den folgenden Code verwendet:
$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'];
Das ist es.
Ein Liner mit einer IP-Adresse nach Land API
echo file_get_contents('https://ipapi.co/8.8.8.8/country_name/');
> United States
Beispiel:
https://ipapi.co/country_name/ - Ihr Land
https://ipapi.co/8.8.8.8/country_name/ - country für IP 8.8.8.8
Ersetzen Sie 127.0.0.1
durch die IpAddress der Besucher.
$country = geoip_country_name_by_name('127.0.0.1');
Installationsanweisungen sind hier , und Lesen Sie diese Informationen, um zu erfahren, wie Sie Stadt, Bundesland, Land, Längengrad, Breitengrad usw. erhalten.
sie können http://ipinfo.io/ verwenden, um Informationen zur IP-Adresse zu erhalten.
<?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; /
?>
Ich habe eine kurze Antwort, die ich in einem Projekt verwendet habe ... In meiner Antwort denke ich, dass Sie die IP-Adresse des Besuchers haben.
$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;
}
Ich weiß, dass dies alt ist, aber ich habe hier ein paar andere Lösungen ausprobiert und sie scheinen veraltet zu sein oder geben einfach null zurück. So habe ich es gemacht.
Verwenden von http://www.geoplugin.net/json.gp?ip=
, für das keine Anmeldung oder Bezahlung für den Dienst erforderlich ist.
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);
Und wenn Sie zusätzliche Informationen dazu wünschen, ist dies eine vollständige Rückgabe von 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
}
Sie können meinen Dienst verwenden: https://SmartIP.io , der die vollständigen Länder- und Städtenamen aller IP-Adressen enthält. Wir stellen auch Zeitzonen, Währung, Proxy-Erkennung, TOR-Knotenerkennung und Krypto-Erkennung zur Verfügung.
Sie müssen sich nur anmelden und einen kostenlosen API-Schlüssel erhalten, der 250.000 Anfragen pro Monat ermöglicht.
Unter Verwendung der offiziellen Bibliothek PHP wird der API-Aufruf zu:
$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"};
Weitere Informationen finden Sie in der API-Dokumentation: https://smartip.io/docs
Versuchen
<?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;
?>
Die User Country-API hat genau das, was Sie brauchen. Hier ist ein Beispielcode, der file_get_contents () wie ursprünglich verwendet verwendet:
$result = json_decode(file_get_contents('http://usercountry.com/v1.0/json/'.$cip), true);
$result['country']['name']; // this contains what you need
Dies ist nur ein Sicherheitshinweis zur Funktionalität von get_client_ip()
, dass die meisten Antworten hier in die Hauptfunktion von get_geo_info_for_this_ip()
aufgenommen wurden.
Verlassen Sie sich nicht zu sehr auf die IP-Daten in den Request-Headern wie Client-IP
oder X-Forwarded-For
, da diese sehr leicht gefälscht werden können. Sie sollten sich jedoch auf die Quell-IP der TCP - Verbindung verlassen, die tatsächlich zwischen unserem Server und besteht der Client $_SERVER['REMOTE_ADDR']
als es kann nicht gefälscht werden
$_SERVER['HTTP_CLIENT_IP'] // can be spoofed
$_SERVER['HTTP_X_FORWARDED_FOR'] // can be spoofed
$_SERVER['REMOTE_ADDR']// can't be spoofed
Es ist in Ordnung, das Land der gefälschten IP zu ermitteln. Beachten Sie jedoch, dass die Verwendung dieser IP in einem Sicherheitsmodell (z. B. Verbot der IP, die häufige Anfragen sendet) das gesamte Sicherheitsmodell zerstören wird. Ich bevorzuge die eigentliche Client-IP, auch wenn es sich um die IP des Proxy-Servers handelt.
Sie können Besucher mit ipstack geo API Land und Stadt erhalten.
<?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 ."";
?>
Quelle: Besucherland und -stadt in PHP mithilfe der ipstack-API abrufen