Count the number of times post has been viewed - php

I am working on a project where only title of posts are shown on main page and on clicking the title, full post is loaded on another page posts.php code for this is:
<?php echo $row['title']; ?>
Now to count post views I have a column hits in my posts table ,initially value of hits is set to 0 and whenever a post is opened value of hits is increased by 1, for this my code is in posts.php
$id = $_GET['postId'];
$sql = "UPDATE posts SET hits = hits + 1 WHERE post_id = $id";
But this is not a good practice for tracking post views as views increase whenever page is refreshed. I want a clean system to track post views where, for every distinct user or visitor views increase by one irrespective of fact how many times the same user/visitor views same post (as in stackoverflow). Like tracking them by their IP address or something else, just an idea (how these guys do it) or how the stuff works would be enough to let me start my work.

You cannot solve your problem so simply. Your problem is counting unique users who view a page (with, perhaps a time component). You have several problems, as described in the comments. The first is determining what you are counting. For a prototype, IP address is good as anything else for getting started. However, it has many short-comings, and you will need to think hard about identifying a "visitor".
There is a way to solve your problem in SQL, sort of efficiently. But, it requires an additional table at the level of post/visitor. It will have one row per combination, and then you will need to count from there. To quickly get the unique counts, you then need an insert trigger on that table.
Here is a sketch of the code:
create unique index unq_postvisitors_post_visitor on postvisitors(postid, visitorid);
insert into PostVisitors (postid, visitorid)
select $postid, $visitorid
on duplicate key update set counter = counter + 1;
delimiter $$
create trigger trig_PostVisitors
after insert on PostVisitors
begin
update posts
set numvisitors = numvisitors + 1
where posts.post_id = new.post_id;
end;$$
delimiter ;

Simplest way I use to solve this problem is through cookies.
Whenever your page is opened, you check if there's set cookie_name cookie through isset($_COOKIE[$cookie_name]).
If isset returns false, you set a cookie through setcookie(cookie_name, value, expire);, maybe setting expire time to 24h (you have to set it in seconds, so 24h is 84600). Also, you trigger your counting systems with a +1 to your visitor counter.
If isset returns true, do nothing.
PHP Cookies Refs

Try this It'll Work
$refreshed = $_SERVER['HTTP_CACHE_CONTROL'];
if ($refreshed == 'max-age=0'){
$sql = "UPDATE posts SET hits = hits + 1 WHERE post_id = $id";
}
Try this script on the page $_SERVER['HTTP_CACHE_CONTROL'] get place when page is refreshed

Related

PHP page hit counters in database

I run a podcast network and I'm redoing my site from scratch. One of the features on my network is to listen to podcasts directly from the site in an HTML5 player. I have all that functionality working just fine, but I'd like some analytical data on those pages.
I'd like to make a hit counter in PHP and store it in a DB table. But, there's only one page. The player loads each show, dependent on the query string, then it pulls the latest episode from their RSS Feed, like so: http://tangentboundnetwork.com/new/show.php?id=1
I want to be able to put analytical data into a table and use it for the hosts of whatever show(s) are on the network.
I just need to know where to start. Any ideas, Links, and examples would be welcome.
First, create your database table VISITOR_COUNT. You will need at least two columns - SHOW_ID and COUNT.
The code in show.php could look something like this:
If you want to count unique (or sort of unique - you can never be completely sure) visitors, check if a specific cookie for the current $id is set. Read more about cookies in PHP here.
If the cookie is not set:
Set the cookie.
Check if there is a row in VISITOR_COUNT with SHOW_ID = :id where :id is the value of $id. Watch out for SQL injection!
If there is, run some SQL to update it: UPDATE VISITOR_COUNT SET COUNT = COUNT + 1 WHERE SHOW_ID = :id
If not, insert a row with the right ID and a count value of 1.

What is the way to count viewer on a post

i have a example table to store posts like
id|title|content|
now i want count view post like
What is the way to do that thanks
You should have a field in your table to store the views count, so you can update the count of viewers with something similar to:
UPDATE `table` SET `views` = `views` + 1 WHERE `id`= $post_id
You may want to avoid spamming by refreshing the page or make sure its a unique viewer. There are several ways you can do that.
If you want to be serious about it you will have to use a table to store IP addresses and relate them to viewed posts in order to not count again, like Gautam3164 suggested.
But creating new records every time a client view a post can be too computationally expensive and, unless its strictily necessary for the case, it should be avoided.
You can instead abuse the $_SESSION to store the IDs of the recently viewed posts, in order to not increment the counter if the same client view them again.
For instance:
if (!isset($_SESSION['recent_posts'][$post_id])) {
mysql_query("UPDATE `table` SET `views` = `views` + 1 WHERE `id`= $post_id");
$_SESSION['recent_posts'][$post_id] = 1;
}
It should solve the spam problem in a very simple and cheap way.
For that you have to add one column in your table.
For example lets say,
You have column name Views
You have to put update query on the top of the page like this
UPDATE table SET Views= Views+1 WHERE ID= 'current page id'
You can make a new table called Counter as example the table contains:
post_id|views
when ever the user visit the page you increment this counter
or you can add a field called views in the same posts table
if you want to count unique views you may store IP ADDRESS as will and check if the ip exists you don't increment that view.
You can get the ip address in php like this:
$_SERVER['REMOTE_ADDR'];
The best way doing that would be using cookies you can refer to this for it.
You may need to store the IPaddress of the viewer using $_SERVER['REMOTE_ADDR'] of the page was opened and store it in DB with that page id and each time you need to check for the maintaining the unique IP addresses.
Means you need to enable the increment of the page view count for the single IP address.
1) First Check for the DB that whether the page view with the current IP address($_SERVER['REMOTE_ADDR']).
2) If is already exists then do nothing.
3) If there is no ,then add a row into DB with the current page id and ip address.
4) Then extract/count the number of views as counting the rows from DB with that page id.
Every time you need to repeat these things.You can also use LOGIN system for mainting the page count.

How to limit number of searches per user in PHP

I am trying to develop an application where a guest user can see search results only 10 times after which he should be directed to payment page. I can use sessions on the search results page, but how can i put a counter on that. Can any please help me on that.
Every time a search request is created you just do
$_SESSION['counter']++
Altough he can just get rid of the limit by deleting cookies. An other approach would be, to store the number of search requests in a database table including the IP address, but this can also be bypassed, while it takes more work to do so.
If you should put search limit on current running session than you can use $_SESSION['count']++.
And if you should put search limit per day than you can use 'UPDATE users SET search_count = search_count+1'
It depends whether you would allow him to search again when he comes to your website or just those 10 times even after he visits after a year.
For temporary bases, you can use cookies (see setcookie function) but if you want to restrict him once and for all, you will have to ssave that information in database.
You would code something like:
<?php
session_start();
$_SESSION['counter'] += 1;
// more logic/code
Now you will have to save the value of $_SESSION['counter'].
If your users can search only while logged in, then I see no problem - you definitely have db table with users, so just add another column to it, say 'search_count' and increase it by one each time user attemps a search.
For example:
UPDATE `users` SET search_count = search_count+1
You can also use a counter in the table user of your db and call a function everytime the user looks for the result, that increments the value by one, so a simple UPDATE.
I think maintaining database will be much better then maintaining SESSION because may be due to some reason session removed or erased.
add a field within users table name for example visit with default value 0 and update this field on every visit of search result page..
"update usertablename set visitfield = visitfield + 1 where user_id = ".$current_user_id
thanks

Limiting activity via PHP

I have a social network that allows users to post blogs, ask questions, and message. We have had a slight issue with spamming. For example, we had users sign up, and write about 6 blogs a minute trying to sell stuff.
I am looking for a quick way to limit these activities by the id of the user, let's say only allowing them to post 3 blogs a day.
I have the users stored in a $auth variable and through OOP bring them up by $auth->id for example to be more specific.
Looking for a fast,simple way to do this via php.
thanks in advance /**EDIT*****/
this is what I have so far, and I know for sure $too many is counting as it should, but for some reason my if(statement is not stopping the 4th blog from posting. HERE is the code
Something like CAPTCHA would be appropriate. However, if they're being entered manually, it will do little to stop them. Regardless, no reason you can't implement both methods.
I'm assuming you have a created field in your blogs table. Simply query the table for the number of blogs with today's date before allowing another to be posted. Not sure what database/API you're using. In MySQL, you could do:
SELECT COUNT(*)
FROM blogs
WHERE user_id = USERID
AND DATE(created) = '2011-11-30'
When the user writes and submits a post, save the date they posted on the post's table. Select and count the amount of times they posted today. If they are under their limit, allow the post or else give them the error/warning message.
When a post is made, do something like:
// Get last post time and number of posts today from database
$query = "SELECT
last_post,
posts_today
FROM
users
WHERE
id = '$auth->id'";
$result = mysql_fetch_assoc(mysql_query($query));
// See if this is the first post today
$isNewDay = date('Y-m-d') != date('Y-m-d',strtotime($result['last_post']));
$postsToday = ($isNewDay) ? 0 : (int) $result['posts_today'];
// Only add post if user is allowed
if ($isNewDay || $postsToday < 3) {
/*
Add the post to the database here
*/
// Update the number of posts today in the database
$query = "UPDATE
users
SET
last_post = '".date('Y-m-d H:i:s')."',
posts_today = '".($postsToday + 1)."'
WHERE
id = '$auth->id'";
mysql_query($query);
} else {
echo "You have already made 3 posts today!";
}
...or you could just use a CAPTCHA (as mentioned by others). That's what they're for. Really, you should have one in the signup process...
I'll admit I know next to nothing on PHP programming, but another option (or addition to the CAPTCHA) would be to use a service such as StopForumSpam
There's an example of how to use it here (no idea how good it is, as I don't code PHP (yet)) :)

How to efficiently cache mysql query in php for this table

I have a Posts table containing the fields title, contents, rating, no_of_comments, author_id. When a user downvotes the post, the rating field is decremented and vice-versa. Also i am caching the display query, which shows the recent posts, and it's related to the table Authors. The problem is that the ratings field need to be updated often i.e. there are a lot of upvotes and downvotes. So i need to rebuild the cache every time a user up/down the post. I believe this is a waste, because only one field in the entire cached data is updated. So i want to know is there any workaround this issue. btw i am using file based caching.
If you normalised your data structure, you would be able to cache the static part - i.e. The "Post", have the "Post Attributes" or whatever you decide to use, being dynamic.
Number of comments should be derived by counting the number of comments in a "Comments" table.
A solid data structure will help you out alot here.
Alright. So your solution is to open an ajax request to a PHP that does the following:
UNTESTED
while (array_pop(mysql_fetch_array(mysql_query("SELECT count(*) FROM `posts` WHERE `ID` = '$latest_id_prediction'"))) == 0) {
sleep(10);
}
echo array_pop(mysql_fetch_array(mysql_query("SELECT * FROM `posts` WHERE `ID` = '$latest_id_prediction'");
This will check every 10 seconds if there is a new post, if there is, it will echo out the post information. what you do is make an ajax request to this page without a timeout, and update the page when you get a reply. When you get the reply, open a new connection.

Categories