Skip to content

Instantly share code, notes, and snippets.

@MikeRogers0
Created June 10, 2012 22:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save MikeRogers0/2907482 to your computer and use it in GitHub Desktop.
Save MikeRogers0/2907482 to your computer and use it in GitHub Desktop.
Simple PHP Page View Counter
<?php # File created on 11th February 2009 by Mike Rogers (http://www.fullondesign.co.uk/).
## Start defining constants ##
define(RUN_ERRORS, TRUE); // Do you want the script to display errors? TRUE = yes you do.
define(LOG_URL, '/home/user/logs/'); // Put the location of where you want to put the logs. Make sure this is absolute
$filename = rawurlencode(base64_encode($_SERVER['PHP_SELF'])); // Takes the filename then makes it network safe.
## End defining constants ##
## Parse filename ##
$filename = LOG_URL.$filename.'.log.txt';
##
// Check that the file exists, encase of the logs being removed or being invalid.
if(is_writable($filename) && is_readable($filename)){
// We should be able to read and write it
$file_contents = file_get_contents($filename);
// Check its a number, the logs could have been hacked at some point.
if(is_numeric($file_contents)){
$file_contents = $file_contents + 1; // Adds 1 to the current number in the log. $file_contents++; would also work.
file_put_contents($filename, $file_contents);
}else{
if(RUN_ERRORS === TRUE){
echo 'File ('.$filename.') contents is not numeric';
}
}
} else {
// We should create the file if we can.
if(is_dir(LOG_URL) && is_writable(LOG_URL) && !file_exists($filename)){ // Checks that the LOG_URL is a wriable directory, and the file does not already exist.
// lets create the file.
file_put_contents($filename, '1');
}else{
if(RUN_ERRORS === TRUE){
echo 'Cannot/write find directory/file ('.$filename.')';
}
}
}
/* Here is how to show how many people have view the file */
echo ('This file has been view by '.file_get_contents($filename).' please');
/*
You are free to share, modify and use this code for commerical uses. Please give a link back (to http://www.fullondesign.co.uk/ ) if you can, but you don't have you.
I claim no liability in this code, you use it at your own risk.
*/
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment