Forgot Password / Register
Site Statistics
Total Members: 520
Total Tutorials: 242
Newsest User: 8884244477
Todays Unique Hits: 81
1 Users 2 Guests Online

Basic PHP Hit Counter

In this tutorial we will create a basic hits counter.
This will read a data file and increment the number on each hit.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
<?php
$hitsfile = "counter.dat"; // The file we will use to store the number of hits
if(file_exists($hitsfile)) { // See if the counter file exists already
    $exist_file = fopen($hitsfile, "r"); // File exists so lets open it
    $new_count = fgets($exist_file, 255); // Gets the current content of the file
    $new_count++; // Adds 1 to the variable
    fclose($exist_file); // Close the file
    print($new_count); // Display the number of hits
    $exist_count = fopen($hitsfile, "w"); // Open the file with the Write permission
    fputs($exist_count, $new_count); // Writes the new value (new number of hits_
    fclose($exist_count); // Close the file
} else {
    // The file doesn't exist, so lets make one
    $new_file = fopen($hitsfile, "w"); // Opening the file with the Write permission will create the file
    fputs($new_file, "1"); // The number of hits in this case will be 1
    print("1"); // Show the current hits
    fclose($new_file); // Close the file
}
?>



Then include this script using a PHP include in the location where you wish the hits to be shown.
NOTE: The script will not work unless the counter.dat file is writeable
DanielXP
Author:
Views:
2561
Rating:
Posted on Saturday 10th May 2008 at 01:21 PM
Alexwhin
Alexwhin
Nice. Simple. Effective. I like it.