Basic PHP Hit Counter


In this tutorial we will create a basic hits counter.
This will store, read and increment a number stored in a .dat file on each hit.

hits.php
  1. <?php
  2. $hitsFile = "counter.dat"; // File to store the hit count
  3.  
  4. if (file_exists($hitsFile)) {
  5. // File exists, read the current hit count
  6. $fileHandle = fopen($hitsFile, "r+"); // Open file for both reading and writing
  7. if ($fileHandle) {
  8. $hitCount = (int)fgets($fileHandle); // Read the current hit count and cast to integer
  9. $hitCount++; // Increment the hit count
  10.  
  11. rewind($fileHandle); // Move file pointer back to the start
  12. fputs($fileHandle, $hitCount); // Write the updated hit count
  13. fclose($fileHandle); // Close the file
  14.  
  15. echo $hitCount; // Display the updated hit count
  16. } else {
  17. // Handle error opening file
  18. echo "Error: Unable to read the counter file.";
  19. }
  20. } else {
  21. // File doesn't exist, create it and initialise hit count to 1
  22. $fileHandle = fopen($hitsFile, "w");
  23. if ($fileHandle) {
  24. $hitCount = 1; // Initial hit count
  25. fputs($fileHandle, $hitCount); // Write the initial hit count
  26. fclose($fileHandle); // Close the file
  27.  
  28. echo $hitCount; // Display the initial hit count
  29. } else {
  30. // Handle error creating file
  31. echo "Error: Unable to create the counter file.";
  32. }
  33. }
  34. ?>



Then include this script using a PHP include in the location where you wish the hits to be shown.

You must ensure the counter.dat file is writeable

DanielXP's Avatar
Author:
Views:
2,827
Rating:
Posted on Saturday 10th May 2008 at 01:21 PM
Alexwhin
Alexwhin's Avatar
Nice. Simple. Effective. I like it.