Skip to content

Instantly share code, notes, and snippets.

@jameshibbard
Created November 25, 2012 12:51
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jameshibbard/4143381 to your computer and use it in GitHub Desktop.
Save jameshibbard/4143381 to your computer and use it in GitHub Desktop.
A session-based visitor counter
<?php
session_start();
$counter_name = "counter.txt";
// Check if a text file exists. If not create one and initialize it to zero.
if (!file_exists($counter_name)) {
$f = fopen($counter_name, "w");
fwrite($f,"0");
fclose($f);
}
// Read the current value of our counter file
$f = fopen($counter_name,"r");
$counterVal = fread($f, filesize($counter_name));
fclose($f);
// Has visitor been counted in this session?
// If not, increase counter value by one
if(!isset($_SESSION['hasVisited'])){
$_SESSION['hasVisited']="yes";
$counterVal++;
$f = fopen($counter_name, "w");
fwrite($f, $counterVal);
fclose($f);
}
echo "You are visitor number $counterVal to this site";
@hemahensa12
Copy link

I can't get the output sir..the counter was not incremented

@jameshibbard
Copy link
Author

Oh dear. Is a file being created? If not then it's probably a permissions issue.
Try changing the owner of the folder to www-data, e.g. sudo chown -R www-data:www-data /var/www/html/counter
Other than that, remember that the counter is only meant to increment once per session, not per page load.
If that's the case, try opening the page in two different browsers.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment