Created
November 25, 2012 12:51
-
-
Save jameshibbard/4143381 to your computer and use it in GitHub Desktop.
A session-based visitor counter
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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"; |
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
I can't get the output sir..the counter was not incremented