开发者

How to do a geoip lookup in php?

开发者 https://www.devze.com 2023-03-15 15:17 出处:网络
All tutoria开发者_如何学运维ls I have seen have pointed towards functions like geoip_record_by_name. I always get this error: Fatal error: Call to undefined function geoip_record_by_name() in /home/&l

All tutoria开发者_如何学运维ls I have seen have pointed towards functions like geoip_record_by_name. I always get this error: Fatal error: Call to undefined function geoip_record_by_name() in /home/<acct>/public_html/geoip.php on line <line>

I'm on "shared" hosting, meaning I don't have access to install the PECL geoip extension.

What are other (free!) ways to perform geoip lookups? Preferably ones which don't depend on an external service?


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消