How to do a geoip lookup in php?

|▌冷眼眸甩不掉的悲伤 提交于 2019-12-01 08:12:05

If you have MySQL server, there are IP databases that you can use and install for free, then do a $_SERVER['REMOTE_ADDR'] and run it against the database data.

i.e. (based on some arbitrary db)

<?php

    $result = mysql_query("SELECT *
                          FROM ips
                          WHERE ip = {$_SERVER['REMOTE_ADDR']}
                          LIMIT 1") or die(mysql_error());

    $row = mysql_fetch_assoc($result);

    $city = $row['city'];
    $state = $row['state'];
    $country = $row['country'];

?>

Some databases(Or just google it): http://www.ipinfodb.com/ip_database.php

EDIT

You can also do JSON/XML requests from other APIs and parse the data:

i.e. (Using ipinfodb.com again)

$doc->loadXML(file_get_contents("http://api.ipinfodb.com/v2/ip_query.php?key=your_key&ip=" . $_SERVER['REMOTE_ADDR'] . "&timezone=false")); 

$country = $doc->getElementsByTagName('CountryName')->item(0)->nodeValue;

You can try hostip.info, Maxmind or ip2location to name a few. These are easy to use with PHP and can be used on shared hosting. Some of them have offline options as well.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!