Making Usage Statistics in PHP – Storing the Data

Let’s start with the database part. We’ll need only one table that stores each click (page impression) of each visitor. The name of the table will be “hits”. What should we store here?

1. The hostname is very important to identify the client. PHP gives us the IP address that I like to convert to hostname with gethostbyaddr(). I think it’s better to see a string.
2. The time of visit can be stored easily by using the NOW() function of MySQL.
3. The visited page on your site should be stored. In most cases, you should store the URL of the visited page and the HTML title in two separated fields, eg. URL and Title fields, so that you’ll be able to see your most visited sites simply by looking through the list of their titles.

Now we’re going to write the piece of code that will save the hit. It will be called at the beginning of the program. To save the requested URL in the database you can use $_SERVER[‘PHP_SELF’] that gives you the URL without the domain name or $_SERVER[‘QUERY_STRING’] that gives you the parameters in the URL after the question mark.

Warning: $_SERVER[‘PHP_SELF’] doesn’t contain the query string, only the path related to the server root and the filename. For instance if you call then PHP_SELF is /folder1/personal/main.php.

I prefer $_SERVER[‘QUERY_STRING’].  This can be especially useful if you use only one PHP to all functions, for example, you call “/index.php?op=forum&topicid=768” if you’d like to show a given forum topic or for showing articles /index.php?op=articles&id=25. Using QUERY_STRING, You will get “op=articles&id=25” that will be enough to identify the requested page.


Published by

Bhavya Web Technologies

We are team of young, energetic and dynamic members, focused on providing high quality website designing, website development and Internet Marketing services. With a team of such Bhavya member we always try and deliver high quality of project, exceeding client’s expectation.