我想使用cookie获取页数

时间:2015-06-09 02:23:54

标签: php cookies

我想在我的索引页面中使用cookie获取页面数量。到目前为止,我已经完成了类似的操作。现在我的问题是:如果我刷新页面,浏览器会显示计数2,并且下次刷新时不会增加。我不知道我的代码有什么问题。我还想知道如何在下一页处理cookie或者我可以在同一页面处理cookie吗?请任何人指导。但这是我的要求。

<?php
$cookie = 1;
setcookie("count", $cookie);
if (!isset($_COOKIE['count']))
{
}
else
{
$cookie = ++$_COOKIE['count'];
} 
echo "The Total visit is".$cookie;
?>

1 个答案:

答案 0 :(得分:0)

我决定使用本地存储,因为我真的不喜欢cookie,有些用户完全阻止它们。

您可以设置回声。使用此

以下是我提到的内容:http://jsfiddle.net/azrmno86/

// Check browser support
if (typeof(Storage) != "undefined") {

    //check if the user already has visited
    if (localStorage.getItem("count") === "undefined") {
        //set the first time if it dfoes not exisit yet
        localStorage.setItem("count", "1");
    }

    //get current count
    var count = localStorage.getItem("count");

    //increment count by 1
    count++;

    //set new value to storage
    localStorage.setItem("count", count);

    //display value
    document.getElementById("result").innerHTML = count

} else {

    document.getElementById("result").innerHTML = "Sorry, your browser does not support";
}

更新一点澄清之后

此样式使用存储在服务器上的.txt文件。 Cookies不可靠。如果有人清除它们,你就完成了。如果你使用变量,任何服务器重启都会杀死你的数量。使用数据库或这种方法。

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

// Check if a text file exists. If not create one and initialize it to zero.
if (!file_exists($counter_name)) {
  $f = fopen($counter_name, "w");
  fwrite($f,"0");
  fclose($f);
}

// Read the current value of our counter file
$f = fopen($counter_name,"r");
$counterVal = fread($f, filesize($counter_name));
fclose($f);

// Has visitor 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); 
}

echo "You are visitor number $counterVal to this site";