PHP is open source scripting language. It\'s widely used to develop web applications.  Home Web Programming PHP Easy Flat File Hit Counter

Easy Flat File Hit Counter


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!



Author's URL: GreyCobra.com
PHP is open source scripting language. It\'s widely used to develop web applications. More PHP Tutorials: Featured Materials | Fresh Materials | More PHP Tutorials at LearnPHP.org


Like us to: