DaniWeb IT Discussion Community

Code Snippets (http://www.daniweb.com/code/)
-   php (http://www.daniweb.com/code/php.html)
-   -   Manage an unlimited amount of hit counters with a text file (http://www.daniweb.com/code/snippet765.html)

Shaffer php syntax
Oct 3rd, 2007
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.

  1. <?php
  2. function hitcounters($file,$txtfile,$action) {
  3. if($action=="display") {
  4. foreach(file($txtfile) as $key => $value) {
  5. if($data=explode(":",$value)) {
  6. if($data[0]==$file) return $data[1];
  7. }
  8. }
  9. }
  10. elseif($action=="files_amount") {
  11. return sizeof(file($txtfile));
  12. }
  13. elseif($action=="all_hits") {
  14. $i=0;
  15. foreach(file($txtfile) as $key => $value) {
  16. if($data=explode(":",$value) {
  17. $i+=$data[1];
  18. }
  19. }
  20. return $i;
  21. }
  22. elseif($action=="increment") {
  23. $filestr = implode($txtfile);
  24. foreach(file($txtfile) as $key => $value) {
  25. if($data=explode(":",$value) {
  26. if($data[0]==$file) {
  27. if(@file_put_contents($file,str_replace($data[0].":".$data[1],$data[0].":".($data[1]+1),implode(file($txtfile))))) {
  28. return true;
  29. }
  30. else {
  31. return false;
  32. }
  33. }
  34. }
  35. }
  36. }
  37. else {
  38. return false;
  39. }
  40. }
  41. ?>