从用户的IP创建用户国家日志


Create a log of users country from their IP

我使用这个函数来获取两个字母的国家代码:

$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;
输出:

US // Two-letter Country Code

要在文件中创建日志,我正在考虑使用这样的东西:

$file = 'visitors.txt';
file_put_contents($file, $ipaddress . PHP_EOL, FILE_APPEND);
输出:

xxx.xxx.xxx.xx // with a line break after

我想循环遍历国家代码,并显示来自每个国家的游客数量。例如:

如果两个来自美国的IP地址和一个来自加拿大的IP地址进入页面…我想显示:

US: 2
CA: 1

虽然我不喜欢在这里处理文本文件的想法-这里有一个简单的解决方案(未经测试):

<?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>');
?>

我假设您已经有一个文件,其内容如下:

US
US
US
DE
DE
IR
AT
US