Page Counter

phool4fool

203.***.***.***
1,936 days ago

Page Counter

This is a class which can manage the counts for any page or unique identifier passed to it.

PHP Example: (!)

PHP code:

0<?php
1class Counter
2{
3 var $counter_file = '';
4
5 function Counter($counter_file = 'counter.txt')
6 {
7 if (!file_exists($counter_file)) {
8 touch($counter_file);
9 }
10
11 $this->counter_file = $counter_file;
12 }
13
14 function increment($my_identifier)
15 {
16 $my_identifier = str_replace(' ', '_', $my_identifier);
17
18 $file = file($this->counter_file);
19 foreach ($file as $index => $line) {
20 list($identifier, $count) = explode(' ', $line);
21
22 if ($identifier == $my_identifier) {
23 $new_count = $count + 1;
24 $file[$index] = $identifier.' '.$new_count."\n";
25 break;
26 }
27 }
28
29 if (!isset($new_count)) {
30 $new_count = 1;
31 $file[] = $my_identifier.' '.$new_count."\n";
32 }
33
34 $fh = @fopen($this->counter_file, 'w');
35 if ($fh === false) {
36 return false;
37 }
38
39 $bytes = fwrite($fh, implode('', $file));
40 fclose($fh);
41
42 if ($bytes === false) {
43 return false;
44 }
45
46 return $new_count;
47 }
48
49 function getCount($my_identifier)
50 {
51 $my_identifier = str_replace(' ', '_', $my_identifier);
52
53 $fh = @fopen($this->counter_file, 'r');
54 if ($fh === false) {
55 return false;
56 }
57
58 while (!feof($fh)) {
59 $buffer = fgets($fh);
60 list($identifier, $count) = explode(' ', $buffer);
61
62 if ($identifier == $my_identifier) {
63 fclose($fh);
64 return (int) $count;
65 }
66 }
67
68 fclose($fh);
69 return 0;
70 }
71}
72?>



Usage Example: (!)

PHP code:

0<?php
1require_once 'Counter.class.php';
2
3// Create the counter object and specify the counter file to use
4$counter = new Counter('counter.txt');
5
6// Increment the count for this identifier and display the new number
7echo $counter->increment('identifier 1')."\n";
8
9// Increment the count for the identifier
10$counter->increment('identifier 2');
11
12// Display the new count
13echo $counter->getCount('identifier 2')."\n";
14?>
15