Question

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?

Was it helpful?

Solution 2

    <?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

OTHER TIPS

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!

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top