A simple hit counter using PHP and Cookies
I like to think I’m a pretty damn good programmer (and that’s the kind of line that gets me the ladies, oh yeah). I need to be. It’s my job, and that’s what I sit here and do all day. I figure out how to engineer a problem into submission, and then I floor it with the awesome power of code and rock n’ roll.
Yet, in the 5 or so years that I’ve been coding in PHP, I have never once used cookies. Never. Never ever. I just haven’t ever had a reason to. Until last week. Cue ominous music.
My friends Christi & Mike needed a counter for the bottom of their wedding website powered by Wordpress. I tried looking for some open source solutions but they were all too complicated (in the sense that I didn’t care for all the crap being reported) so I decided to write one myself. It’s pretty simple– it checks to see if a cookie is set indicating that you’ve already been counted, and if not, it increments a counter and writes it to a flat file. Since this is Wordpress, this section of code goes in header.php before any headers have been output (cookies must always be set before any headers are output):
5 // open the counter log, get the existing count and close the file
6 $data = file('counterlog.txt');
7 $total_visits = $data[0];
8 $unique_visits = $data[1];
9
10 // check to see if we’ve already set a cookie for this user
11 if(!isset($_COOKIE['counted'])){
12 // reopen the file, overwrite the counts and close the file
13 $fp = fopen(’counterlog.txt’, ‘w’);
14 fwrite($fp, (($total_visits + 1) . “\n” . ($unique_visits + 1)));
15 fclose($fp);
16
17 // set a cookie marking that we’ve counted this user
18 setcookie(’counted’, 1, time()+64281600, ‘/’, ‘.christiandmike.com’, false);
19 }else{
20 // we want to track visits only to the frontpage
21 if($_SERVER['REQUEST_URI'] == ‘/’){
22 // reopen the file, overwrite the total count and close the file
23 $fp = fopen(’counterlog.txt’, ‘w’);
24 fwrite($fp, (($total_visits + 1) . “\n” . ($unique_visits)));
25 fclose($fp);
26 }
27 }
And this chunk of code goes in footer.php:
10 // get the current count from the counterlog and print it out
11 $data = file('counterlog.txt');
12 $total_visits = $data[0];
13 $unique_visits = $data[1];
14 ?>
15 We have had <strong><?= $total_visits ?></strong> visits and <strong><?= $unique_visits ?></strong> unique visits[...]
counterlog.txt is a blank file that needs to be writable by the web server. And there we go, a really simple, yet useful application made possible thanks to cookies.
You’re currently reading “A simple hit counter using PHP and Cookies”, an entry on sudo make me a sandwich
- Published:
- 11.16.07 / 5pm
- Category:
- PHP, Programming
- Post Navigation:
- « Pineapple Salsa
Thanksgiving with the folks »
