My Dumb PHP Counter Script

My Dumb PHP Counter Script

Saving this code snippet so I don’t have to look this up again. Move along! Nothing to see!

No, it won’t work as is. It keeps track of two counts in a text file on the web server, which is assumed to be writable. It doesn’t do anything to check whether the file is already open, which makes me nervous, but that will be a topic of future investigation.

function Cache_count() {
 global $cache_path;
 if(file_exists("$cache_path/counter.dat")) {
   $exist_file = fopen("$cache_path/counter.dat", "r");
   $total_count = rtrim(fgets($exist_file));
   $cache_count = rtrim(fgets($exist_file));
   $cache_count++;
   $total_count++;
   fclose($exist_file);
   $exist_count = fopen("$cache_path/counter.dat", "w");
   fputs($exist_count, $total_count . "n");
   fputs($exist_count, $cache_count . "n");
   fclose($exist_count);
 } else {
  $cache_count = 1;
  $total_count = 1;
  $new_file = fopen("$cache_path/counter.dat", "w");
  fputs($new_file, $total_count . "n");
  fputs($new_file, $cache_count . "n");
  fclose($new_file);
 }
 return $cache_count . "/" . $total_count;
}

0 Comments