0 comments :: 509 views
Making Your Views Counter More Accurate
In developing your webpage, you may find that you want to keep track of how many people have viewed a post, which means you need to create a counter. Once made, you'll probably want to lock it down so a simple page refresh doesn't increase the views; this could mess up the accuracy of page statistics. Using sessions, we can thwart these types of actions.
* Before continuing, it is assumed that you have a way of updating your post counter and that you have a unique way of identifying each post (i.e. a post ID). In the example below I will use a function called update_views( );
Sessions are a great tool that PHP provides. As the PHP website puts it, "Session support in PHP consists of a way to preserve certain data across subsequent accesses." It's soft of like the cookies of PHP. Here's how you store and access a value using sessions
<?php
$_SESSION['var1'] = 'value1';
echo $_SESSION['var1']; // displays value 1
?>
So how can we use sessions to maintain post views? It's very simple, really. Since we only want each person recording 1 view per post, we can set up an array of post IDs and a record that they've been viewed.
The structure is like this:
<?php
Array(
[4] => 1,
[9] => 1,
[26] => 1
)
?>
Each key represents a post ID and the value of 1 says the post has been viewed by this person.
The old pseudo code:
The new pseudo code:
if the key doesn't exist, update the views, then create a key to log that the post has been viewed
The PHP code:
<?php
$post_id = <replace with however you get the post id>;
if(!isset($_SESSION['posts_viewed']['$post_id']))
{
update_views($post_id); // update views for post
$_SESSION['posts_viewed']['$post_id'] = 1; // create new key
}
?>
TAGS: views counter, counter, view, php, programming


Comments
no comments posted yet