post-counter

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
tinny
Forum Newbie
Posts: 3
Joined: Sat Jun 10, 2006 12:48 am

post-counter

Post by tinny »

For my guestbook, how do I make a counter which counts the number of posts? It uses a text file, not a database.
User avatar
twigletmac
Her Royal Site Adminness
Posts: 5371
Joined: Tue Apr 23, 2002 2:21 am
Location: Essex, UK

Post by twigletmac »

Probably will depend on the format of the text file if you want to do it on the fly. Alternatively, you could have another file that just contains the counter that you increment each time an entry is added.

Mac
printf
Forum Contributor
Posts: 173
Joined: Wed Jan 12, 2005 5:24 pm

Post by printf »

A good idea when using text files as a database is to use preset defined column widths so you can read and write on a single IO handle.

pif!
tinny
Forum Newbie
Posts: 3
Joined: Sat Jun 10, 2006 12:48 am

Post by tinny »

so how would i go about actually doing that?
User avatar
dibyendrah
Forum Contributor
Posts: 491
Joined: Wed Oct 19, 2005 5:14 am
Location: Nepal
Contact:

Post by dibyendrah »

Simple solution using text file :

Code: Select all

<?
function hitcount()
{
$file = "counter.txt";
if ( !file_exists($file)){
       touch ($file);
       $handle = fopen ($file, 'r+'); // Let's open for read and write
       $count = 0;

}
else{
       $handle = fopen ($file, 'r+'); // Let's open for read and write
       $count = fread ($handle, filesize ($file));
       settype ($count,"integer");
}
rewind ($handle); // Go back to the beginning
fwrite ($handle, ++$count); // Don't forget to increment the counter
fclose ($handle); // Done

return $count;
}     

$count = hitcount();
print $count; 
?>
User avatar
dibyendrah
Forum Contributor
Posts: 491
Joined: Wed Oct 19, 2005 5:14 am
Location: Nepal
Contact:

Post by dibyendrah »

Easy solution using text file :

Code: Select all

<?php

/**
 * Create an empty text file called counterlog.txt and 
 * upload to the same directory as the page you want to 
 * count hits for.
 * 
 * Add this line of code on your page:
 * <?php include "text_file_hit_counter.php"; ?>
 */

// Open the file for reading
$fp = fopen("counterlog.txt", "r");

// Get the existing count
$count = fread($fp, 1024);

// Close the file
fclose($fp);

// Add 1 to the existing count
$count = $count + 1;

// Display the number of hits
// If you don't want to display it, comment out this line
echo "<p>Page views:" . $count . "</p>";

// Reopen the file and erase the contents
$fp = fopen("counterlog.txt", "w");

// Write the new count to the file
fwrite($fp, $count);

// Close the file
fclose($fp);

?>
Post Reply