Program code – Hit counter

A hit counter tells you about the number of visits on a particular page of your website. We build this hit counter with the help of cookies.

We create cookie and update it every time the page is loaded.

<html>
<head>
<title>Hit Counter</title>
<script type="text/javascript" language="javascript">
now = new Date
expireDate = new Date
expireDate.setMonth(expireDate.getMonth()+6)
hitCt = parseInt(cookieVal("pageHit"))
hitCt++
lastVisit = cookieVal("pageVisit")
if (lastVisit == 0) 
{
    lastVisit = ""
}
document.cookie = "pageHit="+hitCt+";expires=" + expireDate.toGMTString()
document.cookie = "pageVisit="+now+";expires=" + expireDate.toGMTString()
function cookieVal(cookieName) 
    {
     thisCookie = document.cookie.split("; ")
       for (i=0; i<thisCookie.length; i++) 
        {
	if (cookieName == thisCookie[i].split("=")[0]) 
            {
	      return thisCookie[i].split("=")[1]
	         }
        }
         return 0
    }
     </script>
    </head>
    <body>
        <h2>
         <script type="text/javascript" language="javascript">
         document.write("You have Visited this Page " + hitCt + " times.")
         if (lastVisit != "") 
         {
	document.write("<br />Your last Visit was " + lastVisit)
         }
         </script>
        </h2>
    </body>
 </html>



Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.