Latest Articles related to all categories. Microsoft, Twitter, Xbox, Autos and much more

Full width home advertisement

Post Page Advertisement [Top]

Create The Count File

In our previous tutorial we show you how to create a simple website counter using PHP and MySQL. Not everyone has access to MySQL, or wants to use it. We can also create a simple counter with just PHP, using a flat file to store our count.

Create a file, containing just the number 0 (or whatever number you want to start your count at) and save it as counter.txt. Upload it to your server, and CHMOD it to 777. The contents of the file will just be 0, it will look like this:

 0

It is very important to set the permissions to 777, or we won't be able to update the count when new people visit the site.




Printing the Current Count

<?php 
$File = "counter.txt";
//This is the text file we keep our count in, that we just made

$handle = fopen($File, 'r+') ;
//Here we set the file, and the permissions to read plus write

$data = fread($handle, 512) ;
//Actully get the count from the file

$count = $data + 1;
//Add the new visitor to the count

print "You are visitor number ".$count;
//Prints the count on the page

The comments in the code above tell us what it does. It opens up the file, reads the current count, and then adds 1 more. It then prints this number to the site visitor.


Updating the Text File With The New Count

 fseek($handle, 0) ; 
//Puts the pointer back to the begining of the file

fwrite($handle, $count) ;
//saves the new count to the file

fclose($handle) ;
//closes the file

?>
This code starts by returning the pointer to the start of our file. If we don't do this, we'll just be tacking numbers onto the end of our current number, and not actually overwriting the count. Once we are at the start of the file, we use fwrite () to overwrite the old count with the new one, so it is ready for the next visitor.

The Full Code

<?php 
$File = "counter.txt";
//This is the text file we keep our count in, that we just made

$handle = fopen($File, 'r+') ;
//Here we set the file, and the permissions to read plus write

$data = fread($handle, 512) ;
//Actully get the count from the file

$count = $data + 1;
//Add the new visitor to the count

print "You are visitor number ".$count;
//Prints the count on the page

fseek($handle, 0) ;
//Puts the pointer back to the begining of the file

fwrite($handle, $count) ;
//saves the new count to the file

fclose($handle) ;
//closes the file
?>
This code can be put directly on your PHP page, or could be held in a separate file called with an include. It does not track unique users, but rather clicks up each time a page is loaded. If you have MySQL you should also consider using a MySQL backed counter.

No comments:

Post a Comment

Bottom Ad [Post Page]