Reputation: 6411
I am using this function to get the two-letter country code:
$ipaddress = $_SERVER['REMOTE_ADDR'];
function ip_details($ip) {
$json = file_get_contents("http://ipinfo.io/{$ip}");
$details = json_decode($json);
return $details;
}
$details = ip_details($ipaddress);
echo $details->country;
Output:
US // Two-letter Country Code
And to make a log in a file, I was thinking of using something like this:
$file = 'visitors.txt';
file_put_contents($file, $ipaddress . PHP_EOL, FILE_APPEND);
Output:
xxx.xxx.xxx.xx // with a line break after
I want to loop through the country codes and display them with the number of visitors from each country. For example:
If two IP Addresses from US and 1 IP Address from Canada went on the page... I want to display:
US: 2
CA: 1
Any help will be appreciated.
Upvotes: 1
Views: 249
Reputation: 2518
Although I don't like the idea of working with text files here - here is an easy solution for that task (untested):
<?php
// Setup.
$pathVisitorsFile = 'visitors.txt';
// Execution.
if(!file_exists($pathVisitorsFile)) {
die('File "'. $pathVisitorsFile .'" not found');
}
// Read entries.
$visitorsCountry = file($pathVisitorsFile, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
// Count entries.
$foundCountries = array();
foreach($visitorsCountry as $visitorCountry) {
if(!isset($foundCountries[$visitorCountry])) {
$foundCountries[$visitorCountry] = 1;
} else {
$foundCountries[$visitorCountry]++;
}
}
// Display entries.
echo('<ul>');
foreach($foundCountries as $countryCode => $visitors) {
echo('<li>'. $countryCode .': '. $visitors .'</li>');
}
echo('</ul>');
?>
I assumed that you already have a file with contents like:
US
US
US
DE
DE
IR
AT
US
Upvotes: 1