# How to make hit counters?

1. Dec 14, 2003

### Alamino

I want to make a hit counter for a webpage. There are a lot of sites that "give" free counters, but I'm interested in knowing how to programm them.

Does anyone knows how to make one?

2. Dec 14, 2003

### dduardo

Staff Emeritus
Here is a simple script in php

Code (Text):

<?php
$file=fopen("Counter.txt", "r+");$hits=fread($file,filesize("Counter.txt")); fclose($file) ;
$hits+=1;$file=fopen("Counter.txt", "w");
fwrite($file,$hits);
fclose($file); // Print$hits in some nice fashion
?>

Basically, everytime someone accesses the page it opens a file, reads the last number, increaments the number, writes that number to a file, and displays that number on the webpage. I've never written a hit counter for a webpage before, so I don't know how effecient this method is, it just seems logical. Perhaps there is a way for apache to keep a log of all the people that go to your website, then all you have to do is read in the file and output it to the webpage.

3. Dec 16, 2003

### Alamino

Thanks for the script. I must confess I'm new in constructing webpages, so I don't know much php (well, I know almost nothing...). I will try to make the counter this way.

Thanks again.