Simple page counter

Small, short code snippets that other people may find useful. Do you have a good regex that you would like to share? Share it! Even better, the code can be commented on, and improved.

Moderator: General Moderators

Post Reply
User avatar
cerpher
Forum Newbie
Posts: 1
Joined: Sun Dec 04, 2005 4:40 pm

Simple page counter

Post by cerpher »

Jcart | Please use

Code: Select all

and

Code: Select all

tags where appropriate when posting code. Read:  [url=http://forums.devnetwork.net/viewtopic.php?t=21171]Posting Code in the Forums[/url][/color]


Here is a simple counter for your index.php home page using a counter.txt file to keep the numbers.

Code: Select all

<?

if (file_exists('count_file.txt'))
{
     $fil = fopen('count_file.txt',r);
     $dat = fread($fil, filesize('count_file.txt'));
     echo $dat+1;
     fclose($fil);
     $fil = fopen('count_file.txt',w);
     fwrite($fil, $dat+1);
}
else
{
     $fil = fopen('count_file.txt',w);
     fwrite($fil, 1);
     echo "1";
     fclose($fil);
}
?>

Jcart | Please use

Code: Select all

and

Code: Select all

tags where appropriate when posting code. Read:  [url=http://forums.devnetwork.net/viewtopic.php?t=21171]Posting Code in the Forums[/url][/color]
User avatar
John Cartwright
Site Admin
Posts: 11470
Joined: Tue Dec 23, 2003 2:10 am
Location: Toronto
Contact:

Post by John Cartwright »

Moved to Code Snipplets.
User avatar
onion2k
Jedi Mod
Posts: 5263
Joined: Tue Dec 21, 2004 5:03 pm
Location: usrlab.com

Post by onion2k »

Onion "optimised" version:

Code: Select all

<?php
	
	$filename = "count_file.txt";
	echo $data = (file_exists($filename)) ? file_get_contents($filename)+1 : 1;
	$file = fopen($filename,w); fwrite($file, $data); fclose($file);

?>
;)
Post Reply