Full On Design

Berkshire Based Web Development

 

PHP

Simple PHP Page View Counter

This is a really quick & easy piece of PHP code to count the page views. It’s not fantastic (It lacks any real tracking abilities), but for some things it does the trick.

The Theory

Every time someone views a page, PHP will increase a number stored in a file by 1. If we want to see how many people have view that page, we just check the file.

The Code

<?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).'  people');

/*

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 for this code, you use it at your own risk.

*/

?>

Download the Code

Useful Links

PHP’s Offical Website – It has a fantastic documentation section. Well worth a look.
PHP 6 and MySQL 5 for Dynamic Web Sites: Visual QuickPro Guide – The book I learnt PHP from, it’s really good for beginners and reference guide.