date:1st May, 16 | by: Joe Karanka | views:
blog website ideas

I believe in the power of choice. Choice not only compels us to make better decisions but it offers us the power to act on situations which may have affected us either directly or indirectly.


What does the Power of choice have to do with Php Counters? Well, bare with me!

Isn’t it fascinating to know how many people have visited your website? Or how many people have read that cool blog post that you posted a few days ago?


Why do I need a Viewer Counter?

The knowledge of that offers you some sort of numerical figure that discloses the speed at which you as a blogger, or web store, etc., are gaining progress and reputation amongst your competitors in this vile World Wide Web. Additionally, it offers you the power to act. Do you need to increase your web presence by hiring a SEO expert? Do you start buying keywords? Your choices are infinite.

In this article, I will delve on creating a simple php page viewer counter that does not require a database. To repharse my words, we will be using a flat text file to keep track of our page view values.

First, make two simple files: count.php and count_data.txt. Save both files in your parent directory.

Count.php // paste the following code

 $handle = fopen("count_data.txt", "r")
    echo "could not open the file" ;
    } else {
	  $counter = (int ) fread($handle,20);
	  fclose ($handle); 
	  echo $counter ;
	  $handle = fopen("count_data.txt", "w" );
	  fwrite($handle,$counter) ;
	  fclose ($handle) ;


What just happened?

As is a common rule in PHP, three important steps need to be followed:

  1. Open a file and define a file handler – in our case; $handle = fopen
  2. Assign read or write privileges to the variables – 'r' or 'w'
  3. Close the file – fclose ($handle)


What's Fopen() function in PHP?

Fopen () function is used to open a file. It takes three arguments but in our case, we are only using two parameters:
These are:  Fopen (“file_name”, “mode”);
In this case, the file name that needs to be open is count_data.txt

Mode specifies what argument should be parsed onto count_data.txt. it can either take up reading or writing modes. Below are arguments that can be parsed in the "mode" variable.

  • read = read mode i.e. reading from a file
  • write = write mode i.e. writing to a file
  • r+ = read and write mode
  • w+ = write and read mode
  • a = appending i.e. whatever data we had written to a file will be appended to the second file
  • a+ = reading and appending


Proceeding with our code; this is what the other entries do:

The ++ in $counter++ annotates an increment of the page views to the variable.

Echo $counter should display the data collected within the variable.

Finally, type the numeral 1 to the count_data.txt. This should give the counter a head start in terms of count value.

And, that's all!

Good design is obvious. Great design is transparent..