website promotion banner
eturnkeys
Your Ad Here
Web Programming  Home Web Programming PHP Easy Flat File Hit Counter
rss

Easy Flat File Hit Counter

Author: GreyCobra.com More by this author


Easy Flat File Hit CounterCreate a very simple hit page view counter without any database!  Use flat file scripting to make an easy counter! 

For this tutorial, I assume you have basic knowledge of PHP (if, echo, die, variables, etc).

Here is our code, I'll explain this piece by piece:

<?php
    $file = 'hits.txt';
    if (!is_writable($file)) die('not writable');
    $current = trim(file_get_contents($file)) + 1;
    fwrite(fopen($file, 'w'), $current);
    echo $current;
?>

This is our hit file variable, make sure this file exists, and make it contain "0".

$file = 'hits.txt';

This checks to see if we can write to $file, which is "hits.txt".

if (!is_writable($file)) die('not writable');

This we use two functions, trim and file_get_contents.

$current = trim(file_get_contents($file)) + 1;

trim will remove all whitespace in a string, and our string will be determined by file_get_contents.

file_get_contents will return the contents of a file into a string.

Then we use + 1 at the end, which will add 1 to the string, which would be the number inside of $file.

Now we're going to use fwrite and fopen to write the new hit count to $file.

fwrite will write a string into a file, controlled by a file handler (fopen).

fopen will create a file handler, pointed at a specified file and mode, we'll use "w" as the mode (write).

Then we just use echo $current to display our total hits.

That's all there is for this tutorial, enjoy it everyone!



Rate this Material: Bad 1 2 3 4 5 Excellent
print this page tell a friend subscribe to newsletter subscribe to rss

Add comments to "Easy Flat File Hit Counter"