PHP - Creating a Hit Counter using file

Description

Creating a Hit Counter using file

Demo

<html>
  <head>//from  w  w  w  .jav a  2 s  .  co  m
    <title>Hit counter</title>
  </head>
  <body>
    A simple hit counter
<?php

$counterFile ="./count.dat";

if (!file_exists($counterFile)) {
  if (!($handle = fopen($counterFile,"w" ))) {
    die(" Cannot create the counter file." );
  } else {
    fwrite($handle, 0);
    fclose($handle);
  }
 }

if (!($handle = fopen($counterFile,"r" ))) {
  die(" Cannot read the counter file." );
 }

$counter = (int) fread($handle, 20);
fclose($handle);

$counter++;

echo "<p>You're visitor No. $counter.</p>" ;

if (!($handle = fopen($counterFile,"w" ))){
  die(" Cannot open the counter file for writing." );
}

fwrite($handle, $counter);
fclose($handle);

?>
  </body>
</html>

Result

Related Topic