post-counter
Posted: Fri Jun 16, 2006 4:29 am
For my guestbook, how do I make a counter which counts the number of posts? It uses a text file, not a database.
A community of PHP developers offering assistance, advice, discussion, and friendship.
http://forums.devnetwork.net/
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;
?>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);
?>