Click here to Skip to main content
15,886,199 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
I was looking forward to add a feature to my project which can tell us how many times the post has been viewed, but just can't get how is it done. I am not a programming expert but still have good knowledge of php, mysql so if anybody can just give me idea how it is done. Currently I display all posts on main page and on clicking title of post user gets redirected to post page were full post is displayed so surely something is to be done on post page but what I have to count their?
Posted

1 solution

First thing to understand: HTTP is stateless. If cannot "remember" anything between HTTP requests and responses. Therefore, you need to persist the number of, say, HTTP requests to a certain page, in an external data storage, which can be database or even plain file of the file system of the server's host.

Now, "how many times the post has been viewed" can be something undefined. If the post was a separate URL, you could count HTTP requests with this URL. As far as I understand, you mentioned a separate "post page". It means that you can count the number of requests directly on the post's page. Naturally, the PHP code should be automatically added to all such pages. But does it mean that you add a file for each post? It might be inefficient. Rather, you could store all posts in a database and generate the page on the fly, which is the main task for PHP and other server-side technologies.

If you want to count some clicks instead (which might be required, in particular, if the posts are stored on the same page, so you may need to detect an event when a user expands some tree node, or something like that), you would need to handle appropriate event (say, "click") of corresponding HTML element in JavaScript and inform the server side through Ajax:
http://en.wikipedia.org/wiki/Ajax_(programming)[^],
http://api.jquery.com/jquery.ajax[^].

By the way, I remember that some companies offered some external Web services designed to count visits of some Web pages of their clients, for a fee or free of charge. I personally doubt their value, but some sites used them. If you are interested, you can do your own search.

—SA
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900