Manage an unlimited amount of hit counters with a text file

Shaffer 0 Tallied Votes 82 Views Share

Hello,
this code snippet is a function used to manage an unlimited amount of hit counters with a text file.
It is crucial that each page will only be displayed once.

The text file syntax:

page_name.php:0
page_name.php:0

An example of a text file that was just set-up (not used by code, yet):

index.php:0
login.php:0
logout.php:0
register.php:0
news.php:0
mailinglist.php:0

An example of a text file in-use:

index.php:12045
login.php:9765
logout.php:2054
register.php:3628
news.php:7895
mailinglist.php:4512

As for the function parameters:
$file : the file of which the function is being executed from.
$txtfile : the text file in-which the hitcounter stats are stored.
$action : the specific action that the function will execute; either "display" for the amount of hits from the $file, "files_amount" for the amount of all listed files, "all_hits" for the total amount of hits recorded, "increment" for incrementing the $file, or "returnall" for the file array so that you can do whatever you want with it.

<?php
function hitcounters($file,$txtfile,$action) {
  if($action=="display") { 
    foreach(file($txtfile) as $key => $value) {
      if($data=explode(":",$value)) {
        if($data[0]==$file) return $data[1]; 
      }
    }
  }
  elseif($action=="files_amount") {
    return sizeof(file($txtfile));
  }
  elseif($action=="all_hits") {
    $i=0;
    foreach(file($txtfile) as $key => $value) {
      if($data=explode(":",$value) {
        $i+=$data[1];
      }
    }
    return $i;
  }
  elseif($action=="increment") {
    $filestr = implode($txtfile);
    foreach(file($txtfile) as $key => $value) {
      if($data=explode(":",$value) {
        if($data[0]==$file) {
if(@file_put_contents($file,str_replace($data[0].":".$data[1],$data[0].":".($data[1]+1),implode(file($txtfile))))) {
            return true;
          }
          else {
            return false;
          }
        }
      }
    }  
  }
  else {
    return false;
  }  
}
?>