geoip zip code query

2019-08-02 11:28发布

I have downloaded the csv geoip lite from http://www.maxmind.com/app/geolitecountry. I imported that data into my db as the following tables:

Blocks: startIP, endIP, locid. Location: locid, country, region, city, postalcode, lat, long, met, areacode.

the code that creates the IPnum is:

<? $ip =$_SERVER['REMOTE_ADDR'];


        list($w, $x, $y, $z) = explode('.', $ip);

        $one = 16777216* $w;
        $two = 65536* $x ;
        $three = 256*$y;

        $ipnum = $one + $two+ $three + $z;
?>

then my query is:

SELECT postalcode FROM location WHERE locid =(SELECT locid FROM blocks WHERE startIP <= '$ipnum' AND endIP>= '$ipnum' LIMIT 1)

for a IP of 69.63.184.142, the ipnum is equal to 1161803918. the db does return a query, however, the location is from Australia, and that ip is definitely not in Australia.

those who are familiar with geoip, is it something I am doing wrong as far as formula goes?

标签: php mysql geoip
1条回答
神经病院院长
2楼-- · 2019-08-02 12:06

Here's one that I use. If it doesn't get a GET var it uses the user's remote address.

<?php
if(!empty($_GET['ip'])){
if(preg_match('!^([1-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])(\.([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])){3}$!',$_GET['ip'])){
    $ip_address=$_GET['ip'];    
} else {
    print ("invalid ip address");   
}
} else {
$ip_address=$_SERVER['REMOTE_ADDR'];    
}
$test = file_get_contents('http://www.geoplugin.net/php.gp?ip='.$ip_address);
$test = unserialize($test);
print "<html><pre>";
print_r ($test);
print "</pre></html>";
?>
查看更多
登录 后发表回答