Hi,
I'm currently working on a counter to log the visitors location (country). I'm using the ip-to-country service from api.hostip.com.
I simply want to store the stats in a flat file in the following structure:
My current code is working fine to get the country but my piece of code to update the file is wrong and doesn't work.
Here's my current code (with comments)
I'm currently working on a counter to log the visitors location (country). I'm using the ip-to-country service from api.hostip.com.
I simply want to store the stats in a flat file in the following structure:
Code:
United States (US)|34
Canada (CA)|10
My current code is working fine to get the country but my piece of code to update the file is wrong and doesn't work.
Here's my current code (with comments)
Code:
<?php
// PROCESS
// Reset country variable
$country = '';
// Get visitor's IP address
$IP = $_SERVER['REMOTE_ADDR'];
// If IP address exists
// Get country (and City) via api.hostip.info
if (!empty($IP)) {
$country = file_get_contents('[URL unfurl="true"]http://api.hostip.info/get_html.php?ip='.$IP);[/URL]
// Reformat the data returned (Keep only country and country abbr.
list ($_country) = explode ("\n", $country);
$_country = str_replace("Country: ", "", $_country);
}
// The visitor's country is now stored in $_country
// UPDATE FILE
// Stats file ( Following stucture: COUNTRY|COUNTS )
$lines = file('stats.txt');
// Reset variables
$i = 0;
$found = 0;
// Loop through the stats.txt file
foreach ($lines as $thisline) {
$thisline = chop($thisline);
list($countryDB, $countDB) = explode("|",$thisline);
// If country is already in the stats.txt file; add a count
if ($countryDB == $_country) {
$count++;
$lines[$i] = $countryDB . "|" . $countDB+1 . "\n";
$found = 1;
break;
}
// If country doesn't exist in the stats.txt file; add the record
else {
$lines[$i] = $_country . "|" . "1" . "\n";
}
$i++;
}
// Write the file
$content = implode('', $lines);
$fp = fopen('stats.txt',"wb") or die(" !!! ");
fputs($fp,$content);
fclose($fp);
?>