I Want to get the page count using cookie

1.7k views Asked by At

I want to get the page count in my index page,using cookie.So far I have done like.Now My question is:If I refresh the page, The browser shows with count 2 and it doesnot increase for next refresh.I don't know what is wrong in my code.Further I want to know how to handle cookie in next page or shall I can handle cookie in same page? can any one guide please.but this is my requirement.

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

There are 1 answers

8
M H On BEST ANSWER

I decided to use local storage for this as I really dislike cookies, some users block them completely.

You can setup the echo. To work with this

Here is what I cam up with: 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";
}

UPDATE After a bit more clarification

This style uses a .txt file stored on the server. Cookies are not reliable. If someone clears them, your done. if you use variables any server restart will kill your count. Eith use database or this method.

<?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";