John Doe
John Doe

Reputation: 3671

How can I get the location of a user?

I'm trying to figure out how I can get the city and state of where a user is located. How can I do this? Should I use JavaScript, PHP?

Upvotes: 1

Views: 7641

Answers (5)

nileshkardate
nileshkardate

Reputation: 21

$country=file_get_contents('http://api.hostip.info/get_html.php?ip=');
echo $country;

// Reformat the data returned (Keep only country and country abbr.)
$only_country=explode (" ", $country);

echo "Country : ".$only_country[1]." ".substr($only_country[2],0,4);

Upvotes: 0

Alan
Alan

Reputation: 46813

Depends, on how cross platform you wish to be. In HTML5, there is the Geolocation api. I would recommend using that, if you don't need to support all IE browsers, and are looking for an HTML5 solution.

Edited to add a much more developer friendly link.

Upvotes: 4

Paul
Paul

Reputation: 141829

Probably PHP in case you want to store it or something. I found this on some forum after a google search and modified it. I'm not sure how accurate it is, but it find my location to within a one hour drive.

<?

    $ip = $_SERVER['REMOTE_ADDR'];

    if (!empty($IP)) {
        $location=file_get_contents('http://api.hostip.info/get_html.php?ip='.$ip);

        list($country, $city) = explode("\n", $location);
        list($country, $code) = explode(' (', $country);
        list($city, $state) = explode(', ', $city);
        $code = substr($code, 0, 2);
        $country = ucfirst(strtolower(str_replace("Country: ", "", $country)));
        $city = ucfirst(strtolower(str_replace("City: ", "", $city)));
    }

echo 'Country: '.$country.'<br />';
echo 'City: '.$city.'<br />';
echo 'State: '.$state.'<br />';
echo 'Country Code: '.$code.'<br />';

?>

Not sure if it's up to date.

Upvotes: 0

joakimdahlstrom
joakimdahlstrom

Reputation: 1595

I normally use ipinfodb for PHP, where you get the user information based on the IP. I'm located in Sweden, and I find it very accurate even here. Though there is always a problem when the ISPs are hiding their customers location, but it has nothing to do with the API accuracy.

Upvotes: 1

Rodaine
Rodaine

Reputation: 1024

You will need to use the javascript geolocation API to locate the user, then make an AJAX call to a PHP or other server-side script to store the location information.

Upvotes: 0

Related Questions