使用php的网站点击计数器无效

时间:2014-11-05 10:31:09

标签: php

我使用php创建了一个网站点击计数器,这个计数器在本地主机上工作正常。

但是当我把它放在我的网站上时没有工作。假设我用100开始couunter.txt然后它将显示101次,并且对于下一次命中保持相同的101。

<?php
    $handle = fopen("counter.txt" , "r");
    $counter = (int) fread($handle , 10);
    fclose ($handle);
    $counter++;
    echo "<span style='color:white; font-size:12px;'> $counter </span>";
    $handle = fopen ("counter.txt" , "w");
    fwrite($handle, $counter);
    fclose ($handle);
?>

1 个答案:

答案 0 :(得分:0)

更好的方法是为访问该网站的每个用户启动会话,并为他开始的每个会话增加计数器值。

    <?php
session_start();
$counter_name = "counter.txt";


if (!file_exists($counter_name)) {
  $f = fopen($counter_name, "w");
  fwrite($f,"0");
  fclose($f);
}


$f = fopen($counter_name,"r");
$counterVal = fread($f, filesize($counter_name));
fclose($f);

// Check if he has visited

if(!isset($_SESSION['hasVisited'])){
  $_SESSION['hasVisited']="yes";
  $counterVal++;
  $f = fopen($counter_name, "w");
  fwrite($f, $counterVal);
  fclose($f); 
}

echo "You are number $counterVal";

?>