PHP -> Basics -> Simple PHP Hit Counter Script

Simple PHP Hit Counter Script - Apr 15 2006
This tutorial will show you how to create a very simple hit counter in PHP.
By Tutorial Monkey   ¦   in PHP » Basics   ¦   Hits: 79866

Tutorial Monkey is a database of technology-related tutorials. We write our own tutorials as well as linking to other ones in the web. If you would like to submit a link to your tutorial, feel free to do so. Just click on "submit" at the top of the page.

Note: Images may result in loss of quality due to the fact that we must resize them to fit the design. You can click resized images to see its original image in a new window.

Sponsors





Step 6

This part's the easiest -- output the number.

<?php
 $hits 
file_get_contents("hits.txt");
 
$hits $hits 1;
 
 
$handle fopen("hits.txt""w");
 
fwrite($handle$hits);
 
fclose($handle);

 print 
$hits;

?>


It's a no-brainer: "print $hits". It prints out whatever's in the variable $hits -- in this case, it's "1". But as time goes on, when we execute this script over and over again -- it will always add 1 and so -- this is a hit counter.

Completed

Now, assuming you saved this file as counter.php, in any other file you want to count hits -- put
<?php include "counter.php"?>

This will include the counter file -- which will only output a number, and nothing else. You can put something like
There are <?php include "counter.php"?> hits.

or something like that.

Or, if you want -- you can add text to counter.php, after "print $hits". It's up to you. If you found this tutorial confusing, contact us.

This tutorial is paginated, please navigate
[ Steps 1-2 ] [ Steps 3-4 ] [ Steps 5-6 ] [ Steps 7-8 ]

If you liked this tutorial, please help us expand by submitting links to your tutorial. This tutorial is an internal Tutorial Monkey tutorial. If you submit your tutorial, we will not claim any rights to it, and will simply link to it to help you gain more viewers.

« Back