1. Home
  2. Computing & Technology
  3. PHP / MySQL

PHP Flat File Counter

By , About.com Guide

4 of 4

The Full Code

<?php
$File = "counter.txt";
//This is the text file we keep our count in, that we just made

$handle = fopen($File, 'r+') ;
//Here we set the file, and the permissions to read plus write

$data = fread($handle, 512) ;
//Actully get the count from the file

$count = $data + 1;
//Add the new visitor to the count

print "You are visitor number ".$count;
//Prints the count on the page

fseek($handle, 0) ;
//Puts the pointer back to the begining of the file

fwrite($handle, $count) ;
//saves the new count to the file

fclose($handle) ;
//closes the file
?>
This code can be put directly on your PHP page, or could be held in a separate file called with an include. It does not track unique users, but rather clicks up each time a page is loaded. If you have MySQL you should also consider using a MySQL backed counter.
Explore PHP / MySQL
About.com Special Features

Holiday Central

What to eat, where to go, fun things to do and how to save money on the perfect gifts. More >

Family Tech Center

Stay connected and entertained with reviews on tips on the latest HDTVs, cellphones and more. More >

  1. Home
  2. Computing & Technology
  3. PHP / MySQL
  4. Step By Steps
  5. PHP Flat File Counter - PHP Counter No MySQL - PHP Count Text File

©2009 About.com, a part of The New York Times Company.

All rights reserved.