Return to the HTML Tips
PHP: Hit Counter
From: Lockergnome Webmaster Weekly Fri Jan 31 2003 http://www.lockergnome.com/ Note: In code examples I add a period after each left arrow bracket so the code can be viewed in all email programs. If you copy and paste, be sure to remove the periods or it won't work. PHP: Hit Counter Scripts like hit counters or guest books are a great way to break into coding for the web. The concepts are usually simple enough in small applications like these to allow you to put together some working code without bursting too many brain cells. Here's a nifty script that allows you to add a hit counter to your site using PHP without having to store anything to a database. In this example, we'll use a simple text file. To begin, create a text file called "hits.txt" with only a single zero, like this: 0 Now, let's do some code. I'm going to call this script "hits.php" and I'll include some code comments for each line, explaining the process as it happens. <.? // Open the hits.txt file for READ access $hitfile = fopen("hits.txt","r+"); // Read the file to grab the current hit count to a variable $hit = fread($hitfile,filesize("hits.txt")); // Close the hits.txt file fclose($hitfile); // Create a new variable to log the new hit $newhitcount = $hit + 1; // Open the hits.txt file for overwrite access $hitfile = fopen("hits.txt","w+"); // Write the new hit count value to the hits.txt file fputs($hitfile, $newhitcount); // Close the hits.txt file fclose($hitfile); ?> Now that you've got a PHP script that reads the current hit value, increments it by 1, and stores the new value back to the hits.txt file, you've got to implement it into your code. We'll make use of PHP includes to accomplish this. Create a simple web page, or use an existing one, making sure the page is saved with the .php extension. At the top of that web page (usually the index page of your website), include the following PHP snip: include("hits.php") ?> With that, your web page will execute the hits.php script on every page load, tracking hits to the text file. To display the contents of that text file on your web page, try the following line of code:We have had include("hits.txt") ?> hits!
This script is certainly not the most effective way to track hits on your site, but it's a clean and simple way to try a little PHP that may actually do something for you. Be sure all the files (hits.txt, hits.php, and your web page) are all in the same directory and give it a shot!
[report a broken link by clicking here]