Visits counter without database with PHP

BackSlash picture BackSlash · Aug 14, 2013 · Viewed 17.7k times · Source

I have a single webpage and i would like to track how many times it's visited without using a database.

I thought about XML, updating a file every time a user visits the page:

<?xml version='1.0' encoding='utf-8'?>
<counter>8</counter>

Then i thought it could have been a better idea to declare a PHP counter in a separate file and then update it everytime a user visits the page.

counter.php

<?php
    $counter = 0;
?>

update_counter.php:

<?php
    include "counter.php";
    $counter += 1;
    $var = "<?php\n\t\$counter = $counter;\n?>";
    file_put_contents('counter.php', $var);
?>

With this, everytime update_counter.php is visited, the variable in the counter.php file is incremented.

Anyway, i noticed that if the counter.php file has $counter = 5 and the update_counter.php file is visited by i.e. 1000 users at the exact same time, the file gets read 1000 times at the same time (so the the value 5 gets read in all requests) the counter.php file will be updated with value 5+1 (=6) instead of 1005.

Is there a way to make it work without using database?

Answer

bitcodr picture bitcodr · Dec 12, 2013
<?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"); 

  fwrite($fp, $count); 

  // Close the file 
  fclose($fp); 

 ?>