Learn how to use PHP to add a counter to your site.

On today's episode I'll explore using PHP as a page counter on your Linux system. First, download the PHP file, which I've zipped up for you.



This is not the fanciest counter out there, but it does the job reliably. You can use this file either by including it in your pages directly or by "requiring it" as we demonstrated last week during our PHP introduction. This counter only dumps out a number to the screen corresponding to the number of times a page has been accessed. (I added it to my personal website to test it out. You can see it on the bottom of the page.)

Before we begin, go to the directory in which your counter will be located, create the file "techtvcounter.dat," and change its permissions to 777. This is not the most secure thing in the world, as it means anyone can mess with it. Preferably you'd want to change its ownership to match that of the Web server. But that means that anyone able to write a PHP file could read it. This isn't a big deal for this program as it's just an example, but if you want to deploy this for some reason (dropped on the head too much?), then you'll want to tighten it up a bit.

After you've downloaded the file, open it. You'll see that I've commented it liberally to explain what it does and when. Take a look at the source code and we'll just walk though it.

The most important thing to notice is the file-locking code -- it is core. Forgetting to take note of the code will ruin the data file and make your numbers wrong. People forget file-locking code all the time and it causes no end of troubles. Remember that you're running this in a shared environment. You want a lot of people hitting your website at once. You have to account for this with smartly designed scripts.

Chris DiBona is the director of special projects for OSDN. DiBona has posted a frequently asked questions list on the Web.