从其IP创建用户国家/地区的日志

时间:2014-07-09 05:11:03

标签: php function logging geolocation 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

任何帮助将不胜感激。

1 个答案:

答案 0 :(得分: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