我正在为我的网站制作一个独特的访问者计数器,我去了很多教程,直到我发现这个简单的代码,但问题是该程序从未添加新的ips或计算新的访问。 ip.txt和count.txt的值永远不会改变:(
以下是整个代码:
<?php
function hit_count() {
$ip_address = $_SERVER ['REMOTE_ADDR'];
$ip_file = file ('ip.txt');
foreach($ip_file as $ip) {
$ip_single = ($ip);
if ($ip_address==$ip_single){
$found = true;
break;
} else {
$found = false;
}
}
if ($found==true){
$filename = 'count.txt';
$handle = fopen ($filename, 'r');
$current = fread($handle, filesize($filename));
fclose($handle);
$current_inc = $current = 1;
$handle = fopen($filename, 'w');
fwrite($handle, $current_inc);
fclose($handle);
$handle = fopen('ip.txt', 'a');
fwrite($handle, $ip_address."\n");
fclose($handle);
}
}
?>
答案 0 :(得分:2)
这段代码充满了错误。它永远不会奏效。
错误编号#1:
$ip_file = file('ip.txt');
$ip_file
上的每个元素都以换行符号结尾,因此即使您的IP在列表中,它也永远不会与$_SERVER ['REMOTE_ADDR']
匹配。必须使用file()
标记运行FILE_IGNORE_NEW_LINES
。
错误编号#2:
if ($found==true){
计数器只会增加并尝试在列表中添加IP(如果已在列表中找到)。如果列表为空,则永远不会执行插孔。颠倒这个逻辑!
错误编号#3:
$current_inc = $current = 1;
永远不会超过1。
除此之外,您必须确保PHP脚本有权更改这些文件。通常,出于安全原因,脚本无权编辑站点文件。
所有这一切,你的脚本应该更改为更像这样的东西:
if (!in_array($_SERVER['REMOTE_ADDR'], file('ip.txt', FILE_IGNORE_NEW_LINES)))
{
file_put_contents('ip.txt', $_SERVER['REMOTE_ADDR'] . "\n", FILE_APPEND);
$count = file_get_contents('count.txt');
$count++;
file_put_contents('count.txt', $count);
}
干净,简单,直接。但是你仍然需要确保PHP脚本有权编辑这些文件。