Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting location details from IP in PHP

Is it possible to get the location details from the users IP Address in PHP.

Any suggestions ??

Thanks

like image 541
Biranchi Avatar asked Dec 02 '09 05:12

Biranchi


3 Answers

$ip = '98.229.152.237';
$xml = simplexml_load_file("http://ipinfodb.com/ip_query.php?ip=$ip");
print_r($xml);

Output:

SimpleXMLElement Object
(
    [Ip] => 98.229.152.237
    [Status] => OK
    [CountryCode] => US
    [CountryName] => United States
    [RegionCode] => 33
    [RegionName] => New Hampshire
    [City] => Manchester
    [ZipPostalCode] => 03103
    [Latitude] => 42.9403
    [Longitude] => -71.4435
    [Timezone] => -5
    [Gmtoffset] => -5
    [Dstoffset] => -4
)
like image 96
David Barnes Avatar answered Sep 20 '22 20:09

David Barnes


You need to use some kine of Geo IP Service

One free service i found on google: geoplugin. They php snipplets to use their service: geoplugin/php

like image 30
Amirshk Avatar answered Sep 21 '22 20:09

Amirshk


You can take a look to the maxmind database, and the GeoIP PECL extension.

In my case :

  • I've installed the extension with "pecl install geoip"
  • And I've downloaded the geolitecity database and copied it to /usr/share/GeoIP/GeoIPCity.dat so it's found by the PECL extension.

Note there should also be some PEAR package (PEAR::Net_GeoIP) to help you, if you cannot install any PECL extension.


Once you have installed both of those, you can use this kind of code :

$ip = '82.229.x.y';     // replace with your IP address
var_dump(geoip_record_by_name($ip));

And you'll get this kind of output :

array
  'continent_code' => string 'EU' (length=2)
  'country_code' => string 'FR' (length=2)
  'country_code3' => string 'FRA' (length=3)
  'country_name' => string 'France' (length=6)
  'region' => string 'B9' (length=2)
  'city' => string 'Lyon' (length=4)
  'postal_code' => string '' (length=0)
  'latitude' => float 45.75
  'longitude' => float 4.84999990463
  'dma_code' => int 0
  'area_code' => int 0

Which, in my case, is true : I am indeed in the city of Lyon, FR.

like image 32
Pascal MARTIN Avatar answered Sep 20 '22 20:09

Pascal MARTIN