AdSense

Thursday, 11 July 2013

Visitor counter with PHP

(Deutsche Version) A visitor counter in PHP is pretty simple to implement. The basic principle is: Everytime when your page is opened, a PHP script is executed which opens a file containing the old visitor number, increments this number and saves the file. For my example, the file "counter.dat" has to be in the same directory as the PHP file. The code for the visitor counter is the following:

$fileName="counter.dat";
$fileHandle=fopen($fileName, 'r') or die("can't open file");
$count = 0;
if(!feof($fileHandle))
{
  $input = fgets($fileHandle, 4096);
  $count = intval($input);
  $count++;
}
fclose($fileHandle);

if ($count != 0)
{
  $fileHandle = fopen($fileName, 'w') or die ("can't open file");
  fwrite($fileHandle, $count);
  fclose($fileHandle);
}
echo('Visitors: '.$count);


Of course you can have a much nicer way of displaying the number of visitors but for the moment, only the basic idea is relevant.

No comments:

Post a Comment