Home > PHP > A basic PHP hit counter

A basic PHP hit counter

The following is a very basic PHP hit counter I wrote some time ago. It uses a browser cookie to prevent the count from increasing by the same user over a short period of time.

<!-- change this style to personalize the counter display -->       

<strong style="font: bold italic 18px/18px
sans-serif;color:#A7C6E4">
<?php
    /* filename: hitcounter.php
     * author: Christopher Huyler
     * data: November 4, 2003       

     * Description:
     * Use $counter_file to track visitors of a web page.
     * This script will set a cookie on       

     * the visitor's computer that times out after an hour.
     * This makes sure each visit is
     * only counted once. $counter_file must be writable by the
     * web server.  Change the permissions       

     * accordingly.
     *
     * USE AT YOUR OWN RISK
     */
    $counter_file = "hitcount.txt";       

    // read the contents of the file       

    $file_line = file($counter_file);       

    // check for the cookie
    $cookiename='visited'.dirname($_SERVER['PHP_SELF']);       

    if(!$_COOKIE[$cookiename])
    {
        // set the cookie if it doesn't exist
        setcookie($cookiename,1,time()+3600,'/',
            $_SERVER['SERVER_NAME']);        

        // update the counter
        $file_line[0]=$file_line[0]+1;
        $fptr = fopen($counter_file, "w");       

        fputs($fptr, "$file_line[0]");
        fclose($fptr);
    }
    // print the count using at least 5 digits       

    $num_str = $file_line[0];
    while(strlen($num_str) < 5)
        $num_str = "0$num_str";       

    echo $num_str;
?></strong>
Categories: PHP Tags:
  1. No comments yet.
  1. No trackbacks yet.
You must be logged in to post a comment.