PHP - Detect country [duplicate]

孤街浪徒 提交于 2019-11-30 09:55:36

问题


Possible Duplicate:
package for detecting users contry in php?
Geo Location based on IP Address - PHP

I want to detect my visitor's country.

And I have found the solution at Google, but the result is nothing.

Can you help me?


回答1:


    <?php 
// Author: www.easyjquery.com 
$ip = $_SERVER['REMOTE_ADDR']; 
// remember chmod 0777 for folder 'cache' 
$file = "./cache/".$ip; 
if(!file_exists($file)) { 
    // request 
    $json = file_get_contents("http://api.easyjquery.com/ips/?ip=".$ip."&full=true"); 
    $f = fopen($file,"w+"); 
    fwrite($f,$json); 
    fclose($f); 
} else { 
    $json = file_get_contents($file); 
} 

$json = json_decode($json,true); 
echo "<pre>"; 
print_r($json); 

?>

Demo Link




回答2:


Here is my way of getting the country along with the ip of the person visiting.

// this is where you get the ip
$ip = $_SERVER['REMOTE_ADDR'];

// this is where you include the code that gets the country
// you can find the code for this file on the link below    
include("geoiploc.php");

// this is where you create the variable that get you the name of the country
$country = getCountryFromIP($ip, " NamE ");

php geo ip loc does not work

Hope this helps.

May the code be with you!

Update:

Here is another method I've been using

    $json = file_get_contents('http://ipinfo.io/' . $this->getIP());
    $data = json_decode($json);
    return $data->country;

There is also this service, but I found the one above much better...

    'http://getcitydetails.geobytes.com/GetCityDetails?fqcn=' . $this->getIP()

Here is a good way to get the ip:

private function getIP() {
    $server_keys = [
        'HTTP_CLIENT_IP',
        'HTTP_X_FORWARDED_FOR',
        'HTTP_X_FORWARDED',
        'HTTP_X_CLUSTER_CLIENT_IP',
        'HTTP_FORWARDED_FOR',
        'HTTP_FORWARDED',
        'REMOTE_ADDR'
    ];

    foreach ($server_keys as $key) {
        if (array_key_exists($key, $_SERVER) === true) {
            foreach (explode(',', $_SERVER[$key]) as $ip) {
                if (filter_var($ip, FILTER_VALIDATE_IP) !== false) {
                    return $ip;
                }
            }
        }
    }
}

Hope it helps someone!



来源:https://stackoverflow.com/questions/14414705/php-detect-country

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!