Home » Tutorials » Web Development » PHP » Counters » How to create a File-based Counter..

How to create a File-based Counter

Added February 20, 2008, read 58 times

Complete a text file based counter in 4 easy steps.

Step One: In the same directory as you plan on putting the PHP file for this counter, create a file 'counter.txt' and CHMOD it to 0777.

Step Two: Create a file called 'counter.php' and place the following PHP code into it.

PHP Code
<?php

// Change this if you rename your counter.txt file
$counter_file = "counter.txt";

// Get the contents of the current counter file
if ($f = @fopen($counter_file, "r"))
{
	@$contents = fread($f, @filesize($counter_file));

	@fclose($f);
}

// File is empty
if ($contents == "")
{
	$contents = 0;
}

// File contents is not a number
if (!is_numeric($contents))
{
	print "Counter contents is not a number.";
	define('ERROR', 1);
}

// Bump the count
if (ERROR <> 1)
{
	$contents++;

	// Add contents back to file
	if ($f = @fopen($counter_file, "w"))
	{
		@fwrite($f, $contents);
		@fclose($f);
	}

	// Print the contents
	print $contents;
}

?>
Select all

Step Three: Upload PHP file into your server

Step Four: Place the following code (setting the same url as if you were to go to it in the browser) where you want to place your counter. You call the file from the http:// location so it processes, and then you get the contents of the file without worrying about file location or any of that.

PHP Code
<?php include("http://location.to.your/new/counter.php"); ?>
Select all

 


Web Development Services

DirSphere

Football Tutorials

Business Listings

Free Online Games

Cheapest Car Insurance

Dish Network Deals

Best Web Hosting Reviews

Web Design Company

Discuss







Nobody posted any comments regarding this story. Be the first!