By now you’ve got your geoip data in the database. I know many people would hate the idea of the duplicated rows of the country codes and country names, and would set up a link to a country table instead with a foreign key. But I can’t be bothered with all that. If you’re interested in doing that read: HOW-TO Import the MaxMind GeoIP Free Country CSV file into MySQL and save diskspace.
Anyways, enough gibbering on. This simple script will take your own IP Address and should hopefully tell you what country you’re in (unless you’re in Europe on AOL and then it could get it all wrong, but anyway).
Two things to note.
- 1 - Yes, I am using mysql_real_escape_string() on a server variable you can’t trust anyone
- 2 - I’m just checking the REMOTE_ADDR variable, wheras on a real system HTTP_X_FORWARDED_FOR should probably be checked first in case the visitor is behind a proxy
<?php
/*
* test_geoip.php - Test of the geoip database
* - Chris Andrews (http://www.toxicbyte.com/)
*
* History:
* 01/09/2006
* - Not very complicated this.
*/
$db_host = "xxxxxx";
$db_user = "xxxxxx";
$db_pass = "xxxxxx";
$db_name = "xxxxxx";
$sql_select_country_from_ip = <<<SQL
SELECT * FROM geo_ip WHERE begin_num <= %s AND end_num >= %s;
SQL;
$dbh = mysql_connect($db_host, $db_user, $db_pass)
or die(‘I cannot connect to the database because: ‘ . mysql_error());
mysql_select_db($db_name);
?>
Testing Database:<br />
<?php
$remote_ip = mysql_real_escape_string($_SERVER[‘REMOTE_ADDR’]);
$remote_ip_as_long = sprintf("%u", ip2long($remote_ip));
print "Your IP is: $remote_ip <br />n";
print "This as a long is: $remote_ip_as_long <br />n";
if (! $result = mysql_query(sprintf($sql_select_country_from_ip,
$remote_ip_as_long,
$remote_ip_as_long)))
{
print "No way pedro";
exit;
}
else
{
if ($row = mysql_fetch_assoc($result))
{
print "<br />";
print "<br />";
print $row["country_code"];
print "<br />";
print $row["country_name"];
print "<br />";
}
else
{
print "-1";
}
}
?>
Technorati Tags: geotargetting, php, maxmind, geoip
Home > About This Post
This entry was posted by Chris Andrews on Friday, September 1st, 2006, at 10:52 pm, and was filed in Databases.
Subscribe to the
RSS 2.0 feed for all comments to this post.
Post a Comment