File IO - Counter

Introduction

To create a visitor counter, we need to store the count in a file (count.txt).
When the page is loaded, the count is read from the file and displayed.
When the page is refreshed, the count is incremented and stored in the file.

Prerequisite

- Create a file count.txt with the following content:
0
- Change the permission of the file to writable.
permission

Code


<?php
	// read count from file
	$filename = "count.txt";
	$fp = fopen($filename, "r");
	$count = fread($fp, filesize($filename));
	fclose($fp);

	// increment count
	$count++;
	$fp = fopen($filename, "w");
	fwrite($fp, $count);
	fclose($fp);

	echo "You are visitor number $count";
?>
	

Demo

Open in new window

Task

Create a reset counter button that resets the count to 0.

Reference

PHP File Handling - tutorialspoint.com
Linux File Permissions: What Does Chmod 777 Mean? - helpdeskgeek.com