banner Hi, this is Shiva Kumar. You can call me Shiva. I'm a developer like you. Earlier I used to write articles for Computers Today. Now I started this web site to help each other ( or ) atleast contribute some thing from my end. I'm always a student, if you need any articles or help which is not there in this web site, please send me a mail. I will try to update them in this web site if possible.
May
6th

PHP - Counting user hits using cookies

Author: admin | Files under Cookies, php


Cookies

Cookies are a mechanism to store the data at the client or browser’s machine. These cookies are stored as a small files. When a browser send a request to web

server, it sends the cookies along with it.

On the server, Cookies can accessed using the $_COOKIE array. This array is an asscotive array where the contents are stored as name, value pairs. The name

of the cookie is set by the setcookie function when it is creating the cookie as follows:

  1.  
  2. <?php
  3.  
  4. setcookie("example_cookie", "HI");
  5.  
  6. ?>
  7.  

The above script creates a cookie at the client machine with the name “example_cookie” and value as “HI”.

Counting user Hits

Counting how many times the user visted our sites using cookies is simple.First if you look at the script that do this, then you can understand easily:

  1.  
  2. <?PHP
  3.  
  4. if(!isset($_COOKIE[‘user_hits’]))
  5. {
  6. setcookie("user_hits", 0, time()*60*60*24, "/", "yourdomain.com", 0);
  7.  
  8. echo " Hi, You are Most welcome to our web site";
  9. }
  10. else
  11. {
  12.  
  13. $_COOKIE[‘user_hits’] = $_COOKIE[‘user_hits’] + 1;
  14.  
  15. echo "Number of Hits on this web siteĀ  " . $_COOKIE[‘user_hits’];
  16.  
  17. }
  18.  
  19. ?>
  20.  

We save the count of user hits in a cookie on the client machine and the cookie is namedĀ  as user_hits ( as shown above).

When the script executes for the first time, the cookie (named user_hits) is not set at the client machine. So, the isset function in the ‘if’ statment

returns false, ,so, we are setting a new cookie at the client machine using the function called setcookie.

when the user visits second time, the if statement got failed to execute becuase, the cookie exists at tyhe client machine and else part executes. In the

else part, increating the value of cookie.

Similar Posts - 90% of Users have seen these posts also

Post a Comment