Llamasery.com Home  
 
Server-side Starter Tutorial: Text Files - Part 2 of 4
Alfie the alpha_geek: Llamasery guru-in-waiting Tutorials Purpose

Starter Tutorials

Tell-a-Friend
Tell-a-Friend +
The 'Contact Form'
php Includes
Simple Themes
MySQL database 101
Comments System
Text Files

Intermediate Material

Articles/Tutorials

Visit Counter

Our visit counter needs to do two things - add one to the number of visits previously, and [optionally] display that new total for your visitors to see. And to do that, you'll need to:

  • Open the file
  • Read a number
  • Add one to it
  • Write new count to file
  • Close the file

And once we've got that process coded, it's just a matter of 'including' the counter code on the page, and - if you choose - displaying the number of visitors. Sounds simple enough - this page has been viewed 54 times.

By way of example, we'll use pagecount.txt as the text file that holds the page visit count value. We need to open that file and be ready to read from it and write to it (the r+):

$fp = fopen("pagecount.txt", "r+");

Then we need to read data from the file, then add one to the count:

$count = fread($fp, 1024);
$count++;

Now we need to seek the start of the file (ready to write the new value of $count to it; then write to the file, and finally close it:

fseek($fp,0);
fwrite($fp, $count);
fclose($fp);

And that's all there is to it. Here's the complete script for pagecount.php:

<?php
$fp = fopen("pagecount.txt", "r+"); //open in reading and writing
$count = fread($fp, 1024); //read the file into variable count
$count++; //increment count
fseek($fp, 0); //reset file pointer to the start
fwrite($fp, $count); //write count
fclose($fp); //close the file
?>

How to use the script

Create an empty text file named pagecount.txt, copy it to your server in the same folder as the page whose visits you want to count, then change the file permissions on that text file to read/write (CHMOD to 777).

Save the script listed above as pagecount.php and copy it to your server in the same folder as the page whose visits you want to count.

For the page(s) that you want to count, add the following php snippet:

<?php  include("pagecount.php");  ?>

The script produces a php variable named $count that you can display anywhere on your page (after the script) with a simple php echo line like:

<?php  echo "You are visitor number". $count;  ?>

«  previous  |  next  »