/************************************************************\
*
* ip2country Copyright 2005 Howard Yeend
* www.puremango.co.uk
*
* This file is part of ip2country.
*
* ip2country is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* ip2country is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with ip2country; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
*
\************************************************************/
$local_db = "./countrydb.txt";
$remote_db = "http://ip.ludost.net/raw/country.db.gz";
if(!empty($_GET['ip']))
{
$ip = $_GET['ip'];
// it's big, so only get it if the current database is a week or more old.
// or if there is no local database (for whatever reason)
$last_db_update = (time() - filemtime($local_db))/60/60/24;
if(($last_db_update >= 7) || !file_exists($local_db))
{
// try to get new db from web
echo "Updating database, please wait a while.
";
flush();
// get contents of a gz-file into an array
$array_gz_contents = gzfile($remote_db);
if(is_array($array_gz_contents) && sizeof($array_gz_contents)>0)
{
// convert to string
$gz_contents = "";
foreach ($array_gz_contents as $gz_line)
{
$gz_contents .= $gz_line;
}
// silently backup local version
if(file_exists($local_db))
{
// (overwrites the previous backup)
// (but TBH, there's no reason to back it up anyway...)
// (unless the live one gets corrupted/dissappears)
copy($local_db,$local_db.".old");
}
// write to local version
$handle = fopen($local_db, 'w');
if($handle && !empty($gz_contents))
{
fwrite($handle,$gz_contents);
}
fclose($handle);
$last_db_update = 0;
echo "Updated OK.
";
} else {
echo "Update failed. Using old database.
";
}
}
// load database
$ip_list = file($local_db);
$found = false;
foreach($ip_list as $ip_record)
{
$ip_record = explode(" ",$ip_record);
if(ip2long($ip)>=ip2long($ip_record[0]) && ip2long($ip)<=ip2long($ip_record[1]))
{
echo "Country: ".$ip_record[2]." (range: ".$ip_record[0]." - ".$ip_record[1].")
";
$found = true;
break;
}
}
if(!$found)
{
echo "Cannot find that IP in database.
";
}
echo "Database last updated ~".round($last_db_update)." days ago.";
} else {
$ip = $_SERVER['REMOTE_ADDR'];
}
?>