计算网站访问者不工作

时间:2015-04-01 10:11:40

标签: php

我在我网站的主index.php中使用以下代码来获取访问者数量:

    <?php
$file = "counts.html";

    if ( is_file( $file )==false )  {touch($file);$open = fopen($file, "w");fwrite($open, "0");fclose($open);}

//read counts
$open = fopen($file, "r");
$count = fread($open, filesize($file));
fclose($open);

//if cookie isn't already set,then increase counts by one + save ip, and set a cookie to pc...
$cookie_namee='mycounterr-456';
    if (!isset($_COOKIE[$cookie_namee])) {
    $open = fopen($file, "w");
    $count++;
    fwrite($open, $count);
    fclose($open);
    setcookie($cookie_namee,"Checked",time()+111400);
    }

//uncomment the below line to see the visits number on page
echo $count;
?>

它有时有效,有时不起作用。我有什么方法以错误的方式做到这一点吗?

编辑:我发现了问题。似乎代码有效,但问题是该值不会覆盖counts.html

中的现有值

该文件第一次只写0并且根本不会改变0。

如何解决此问题?

任何帮助将不胜感激

提前致谢

3 个答案:

答案 0 :(得分:0)

如果使用file_get_contentsfile_put_contents函数,您的代码看起来会更清晰,运行更安全:

<?php

session_start();
$file = "counts.txt";
$count = 0;
$cookie_namee = 'mycounterr-456';

if ($content = @file_get_contents($file))
    $count = intval($content);

echo "count is $count at start<br />";

//if cookie isn't already set,then increase counts by one + save ip, and set a cookie to pc...
if (!isset($_COOKIE[$cookie_namee])) {
    $count++;
    file_put_contents($file, "$count");
    echo "updating $file with $count<br />";
    setcookie($cookie_namee,"Checked",time()+111400);
}

//uncomment the below line to see the visits number on page
echo $count;

?>

有更好的方法来实现计数器,但这可能有效:)

答案 1 :(得分:0)

这么多代码恕我直言

$file = "counts.html"; // Why html?
$cookie_namee = 'mycounterr-456';
$count = file_get_contents( $file );

if( !isset( $_COOKIE[ $cookie_namee ] ) ) {
  $count++;
  file_put_contents( $file, $count );

  setcookie( $cookie_namee, 1, time() + 111400 );
}

echo $count;

答案 2 :(得分:0)

首先,您必须在代码的第一行添加session_start();

最好将计数器号码保存到.txt文件而不是.html文件。

现在将您的代码更改为以下代码:

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

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

// Read the counter values
$f = fopen($counter_name,"r");
$counterVal = fread($f, filesize($counter_name));
fclose($f);

// Check if visitor has been counted in this session
// If not, increase counter value by one
if(!isset($_SESSION['hasVisited'])){
  $_SESSION['hasVisited']="yes";
  $counterVal++;
  $f = fopen($counter_name, "w");
  fwrite($f, $counterVal);
  fclose($f); 
}
?>