Tuesday, December 18, 2012

A Simple PHP Visitor Counter



Design a simple PHP counter without using MySQL database, only using an external file 'visitorcounter.txt'. PHP functions used here: file_exists, fopen, fwrite,fgetc,fclose.
 visitorcounter.php
<?php
//A simple PHP counter
//Using external file visitorcounter.txt
//to store counter instead using MySQl database
function visitorcounter()
{
    $file='visitorcounter.txt';
    if(!file_exists($file)){
        $counter = 0;
        $cf=fopen($file,"w");
        fwrite($cf,$counter);
        fclose($cf);
    }else{
        $cf=fopen($file,"rw");
        $counter=fgetc($cf);
        fclose($cf);}
    $counter++;
    $cf=fopen($file,"w");
    fwrite($cf,$counter);
    fclose($cf);
    return $counter;   
}
?>

index.php, call visitorcounter.php
 <?php
      require("visitorcounter.php");
?>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
        <title>Visitor Counter</title>
        <meta name="author" content="Jiansen" />
        <!-- Date: 2012-12-18 -->
    </head>
    <body>

    <h1>Welcome to visit  My Homepage</h1>
    <br /> <hr />
    <font size=7 color=red>
    You are  visitor <?php echo visitorcounter(); ?>.
    </font>
    </body>
</html>

Video for this demo:

1 comment: