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

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
Thank you for voting.
Rate this Materials:
Bad 
1 2 3 4 5 Excellent
print this page subscribe to newsletter subscribe to rss

Web programming � everything from the basics of visual design and architecture to the specifics of applications, graphics, and scripting. More Web Programming: Most Popular Materials | Fresh Materials | More PHP Tutorials at LearnPHP.org

Add comments to "Easy Flat File Hit Counter"

Only registered users can write comment

No comments yet...