【问题标题】:How to save page views to a text file in php?如何将页面浏览量保存到 php 中的文本文件?
【发布时间】:2015-05-27 03:54:09
【问题描述】:

我正在尝试将页面浏览量保存在 txt 文件中。所以当页面被访问时,脚本会更新txt文件,数字会增加+1。

我的page_views.txt 文件包含以下内容:

 [page_views]

[page_views] 是页面浏览次数,例如:[500],每次访问页面时都会更新。

save_hits.php

<?Php
$f=file("p.txt");
$getc=$f[0];
$addition=$getc. '+1';
$f_ope=fopen("p.txt","w");
fputs($f_ope,$addition);
fclose($f_ope);
?>

page_hits.php

<?Php 
$x=file("p.txt");
echo "+$x[0] views";?>

但问题是它没有按预期工作,

每当page_hits.php 脚本运行时,我都会得到结果:

1+1+1+1 views

预期的输出应该在哪里:

4 views

而且每次命中应该增加 +1。

你知道如何解决它吗?

【问题讨论】:

    标签: php file


    【解决方案1】:

    使用下面的代码:

    $fh = fopen('p.txt','r');
    $cont = '';
    while ($line = fgets($fh)) {
      $cont = $cont.$line;
    }
    fclose($fh);
    $addition = $cont+1;
    $f_ope=fopen("p.txt","w");
    fputs($f_ope,$addition);
    fclose($f_ope);
    

    【讨论】:

      【解决方案2】:

      $addition=$getc. '+1'; 表示appending

      . 代表连接运算符。

      所以,$addition 在执行结束时的值将类似于 1+1+1+1

      但如果您需要添加,则应该使用$addition = $getc + 1;,这将导致总和。

      因此,您应该将$addition = $getc. '+1' 替换为$addition = $getc + 1; 以获得总和。

      【讨论】:

        【解决方案3】:

        通过结果,您可以清楚地看到您正在追加“+1”,而不是在总和中加 1

        更改$addition = $getc. '+1';$addition = $getc + 1;

        【讨论】:

          【解决方案4】:
          $count = intval(file_get_contents("p.txt"));
          file_put_contents("p.txt",++$count);
          

          【讨论】:

            【解决方案5】:

            嘿,你犯了一个小错误。问题是您想要add,但您正在连接来自.txt file 的变量。这是对您的问题的快速修复,只需将包含字符串连接的行更正为+1$addition=$getc. '+1';以下。

            $addition=$getc + 1;
            

            这样就可以解决问题了。

            其他方法是使用++$getc,然后再次写入file!!!!

            【讨论】:

              【解决方案6】:

              也许这会起作用:

                  $fp = fopen("counter.txt", "r+");
              
              while(!flock($fp, LOCK_EX)) {  // acquire an exclusive lock
                  // waiting to lock the file
              }
              
              $count = intval(file_get_contents("counter.txt"));
              file_put_contents(".txt",++$count);
              
              ftruncate($fp, 0);      // truncate file
              fwrite($fp, $counter);  // set your data
              fflush($fp);            // flush output before releasing the lock
              flock($fp, LOCK_UN);    // release the lock
              
              fclose($fp);
              

              【讨论】:

                猜你喜欢
                • 1970-01-01
                • 2020-06-30
                • 1970-01-01
                • 2013-10-22
                • 1970-01-01
                • 1970-01-01
                • 1970-01-01
                • 1970-01-01
                相关资源
                最近更新 更多