Page 1 of 1

post-counter

Posted: Fri Jun 16, 2006 4:29 am
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.

Posted: Fri Jun 16, 2006 6:07 am
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

Posted: Fri Jun 16, 2006 6:56 am
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!

Posted: Fri Jun 16, 2006 10:44 pm
by tinny
so how would i go about actually doing that?

Posted: Sat Jun 17, 2006 12:39 am
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; 
?>

Posted: Sat Jun 17, 2006 12:42 am
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);

?>