Capture Visitors Location w/ PHP

Capturing your visitors location is great for many reasons while building statistical software, its also good just to know where people are that are visiting your website. Heres a quick and dirty way for capturing location data.

Download the IP2Country CSV File unzip it and fire it into your FTP dir, we need to gather all the data out of it and stick it into a MySQL database.

SQL Table
CREATE TABLE `country_ip` (
`ip_from` DOUBLE NOT NULL ,
`country` VARCHAR( 50 ) NOT NULL

Then we create the file that will import all the information.

$file_arr = file(‘ip-to-country.csv’);
foreach($file_arr as $line){
$clean_line = trim(str_replace(‘”‘, “‘”, str_replace(“‘”, “\'”, $line)));
$sql = mysql_query(“INSERT INTO `country_ip` (`ip_from`,`ip_to`,`country`) VALUES($clean_line)”);
echo ‘Finished :]’;

Once you have ran the above code, it should insert all the data into your mysql database, you can go ahead and delete the ip-to-country.csv file now.

Next all we are doing is querying the database to find out the current visitors location, you can then do whatever you like with the data.

$ip = ip2long($_SERVER[‘REMOTE_ADDR’]);
$ipc_q = mysql_query(“SELECT * FROM `country_ip` WHERE `ip_from` <= '".$ip."' AND `ip_to` >= ‘”.$ip.”‘”);
$ipc = mysql_fetch_array($ipc_q);

When someone visits quite a lot of details are being put into the database regarding each visitor, for example, I work out if the user has been on in the past 24 hours (unique), capture the users IP address, each page visited, visitors country and time/date of visit. From this information, I have created some nice analytical apps in the backend of to feast my eyes upon.