Simple Hit Counter Script in PHP
Friday, May 9th, 2008This is a very basic text file based hit counter script created in php. It uses a text file named “counter.txt” to store the counter value. Everytime the script is loaded the counter is incremented by 1 and is displayed on the webpage and stored in the file. The script is pretty basic and can be easily changed to more complex hit counter script.
<?php
$counter = 0;
$filename = "counter.txt";
$handle = fopen($filename, "r");
$counter = fread($handle, filesize($filename));
fclose($handle);
$counter = $counter + 1;
if (is_writable($filename))
{
if (!$handle = fopen($filename, 'w'))
{
echo "Cannot open file ($filename)";
exit;
}
if (fwrite($handle, $counter) === FALSE)
{
echo "Cannot write to file ($filename)";
exit;
}
fclose($handle);
}
else
{
echo "The file $filename is not writable";
}
echo "Total Visits: " . $counter;
?>
You can download the complete source code with sample counter.txt file: Download Now