I’m trying to set up some basic Geo Targeting one of my sites. I have a database populated with Beginning and Ending IP numbers and the relevant countries.
What I’m trying to do is write a PHP script which will take a user’s IP address and the convert that into IP numbers in order for me to tell which country the user is from.
Can anyone point me in the rough direction of a blueprint that might help me out with this? I guess I just need to get an idea of the best way of going about this.
What I need to do is take a user’s IP address and match it up to a particular country in the database.
Now my understanding of the situation is that I need to convert a user’s IP address and convert it into an IP number to compare it to the “begin_num” and “end_num” columns shown above.
Is that correct? Or am I over complicating things?
Sorry to keep pushing this instead of helping you with the solution that you seem to have set your mind on. The “binary database” is just an ordinary file like any other. As long as your server allows the fopen/fread family of functions, you can use it. The plain-PHP API is available on PEAR as Net_GeoIP.
So, if I go down the binary database route, is it just a case of uploading the relevant .dat and .inc files on to the server? I was under the impression that I had to run several linux commands to install these files properly, which obviously wasn’t possible on a shared server.
<?php
$sql = sprintf(
"SELECT country FROM table WHERE begin_num >= INET_ATON('%$1s') AND end_num <= INET_ATON('%$1s');",
mysql_escape_string($_SERVER['REMOTE_ADDR'])
);
?>
Oh right, well I’ll certainly give it a go this evening.
I think I was just put off by these instructions on the MaxMind
First, download the database, and transfer the file to your server. Once you have uploaded the GeoIP tarball to your server, open a ssh session and run the following commands:
$ tar xvfz GeoIP-106_20051201.tar.gz
$ mv GeoIP-106_20051201/GeoIP-106_20051201.dat /usr/local/share/GeoIP/GeoIP.dat
I think Sterling has the answer. I was going to suggest similar using BETWEEN in the SQL and ip2long($_SERVER[‘REMOTE_ADDR’]), but I see MySQL has it’s own equivalent.
Simon are the begin_num and end_num columns numeric? They should be.
Using Maxmind’s goodies means everything can live on your server; YQL, not so much the case. The “pure PHP” api is really nice and simple to use, and will save you cooking up your own functions to do the same job.
I dev on a PC but live server is *nix, and to the best of my memory I downloaded the windows version of .dat to my pc and SFTP’d it onto the server, 'cause I find many *nix commands to be scary too, I am getting over it though.