php程序无法更改文本文件的值

php程序无法更改文本文件的值,php,Php,我正在为我的网站制作一个独特的访问者计数器,我学习了很多教程,直到我找到了这段简单的代码,但问题是该程序从未添加新的IP或统计新的访问量。ip.txt和count.txt的值永远不会更改:( 以下是全部代码: <?php function hit_count() { $ip_address = $_SERVER ['REMOTE_ADDR']; $ip_file = file ('ip.txt'); foreach($ip_file as $ip) {

我正在为我的网站制作一个独特的访问者计数器,我学习了很多教程,直到我找到了这段简单的代码,但问题是该程序从未添加新的IP或统计新的访问量。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);


    }
  }
?> 


此代码充满错误。它永远不会工作

错误编号#1:

$ip\u文件
上的每个元素都以换行符结尾,因此即使您的ip在列表中,它也永远不会匹配
$\u服务器['REMOTE\u ADDR']
文件()
必须使用
文件忽略新行
标志运行

错误编号#2:

如果在列表中已经找到IP,计数器只会增加并尝试将其添加到列表中。如果列表为空,它将永远不会执行jack操作。反转此逻辑

错误编号#3:

它永远不会超过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脚本有权编辑这些文件。

此代码充满错误。它永远不会工作。您需要
文件\u忽略\u新行
标记
文件()
而不是编写自己的循环。为什么在找到IP.txt时要将IP添加到
IP.txt
文件中?应该在找不到IP时添加IP。
if ($found==true){
$current_inc = $current = 1;
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);
}