1

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?

Community
  • 1
  • 1
Michael Antonius
  • 942
  • 2
  • 11
  • 20

2 Answers2

7

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!

Community
  • 1
  • 1
Daniel Fanica
  • 433
  • 1
  • 4
  • 11
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

Kelley Lewis
  • 127
  • 7
  • Kelley can you edit your answer and add some local solution of it, i don't want to use external solution I will accept you if you can do it – Michael Antonius Jan 19 '13 at 13:19
  • Hi Michael, Check here, the info is available to also download the js file so you can host the solution yourself, hope that helps :) http://www.easyjquery.com/2012/11/geo-api-detect-clients-ip-country-city-with-javascript-php/ – Kelley Lewis Jan 19 '13 at 13:23
  • type 2 -- fopen(./cache/72.193.132.49): failed to open stream: No such file or directory -- at line 9 – Michael d Apr 12 '17 at 18:50