Getting location details from IP in PHP

前端 未结 7 1633
傲寒
傲寒 2021-02-03 14:30

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

Any suggestions ??

Thanks

7条回答
  •  不要未来只要你来
    2021-02-03 14:57

    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.

提交回复
热议问题