PHP session for tracking unique page views - php

I want to use sessions to track unique page views. Not a very robust method, I know, but sufficient for what I want to do.
On the first page load the session variable is set and a field in the database increments. On subsequent page views it does not increment, because the increment is conditional on the session variable not being set.
This is my code:
$pagenumber = 1;
//other stuff here...
session_start();
if (!isset($_SESSION[$pagenumber])) {
$storeview = mysqli_query($dbconnect, "UPDATE tblcount SET views=views+1 WHERE id='$pagenumber'");
$_SESSION[$pagenumber] = $pagenumber;
}
echo $_SESSION[$pagenumber];
$Recordset1 = mysqli_query($dbconnect, "SELECT views FROM tblcount WHERE id = '$pagenumber'");
$row_Recordset1 = mysqli_fetch_assoc($Recordset1);
echo "Viewed ".$row_Recordset1['views']." times";
The first echo is only there for testing. It echoes the value just fine on page refresh and the increment works the first time, but the view count continues to increment on every page refresh, which it shouldn't. I can't see why.
I found a similar question:
PHP: Unique visits/hits to specific items using cookies/ip but I ran into a similar issue with the solution offered there.
Help appreciated!

Problems:
You are updating in tblCount EACH time, because your session is closed each time your script finishes.
SO: Put the session_start()call as the FIRST LINE in code.
It's not permitted to set an integer as $_SESSION variable. So if you set $_SESSION[$pagenumber] = 'something', then you gain the following notice:
( ! ) Notice: Unknown: Skipping numeric key 1 in Unknown on line 0
Quite... not understandable. For details see this answer.
Solution:
Add your $pagenumber as index in an array (here pagenumbers) and that array inside the $_SESSION variable. No notice anymore.
session_start();
$pagenumber = 1;
if (!isset($_SESSION['pagenumbers'])) {
$_SESSION['pagenumbers'] = array();
}
if (!isset($_SESSION['pagenumbers'][$pagenumber])) {
updateViews($pagenumber);
$_SESSION['pagenumbers'][$pagenumber] = $pagenumber;
}
echo 'Page number: ' . $_SESSION['pagenumbers'][$pagenumber] . '<br/>';
$views = getViews($pagenumber);
echo '<pre>Viewed ' . print_r($views, true) . ' times</pre>';
Note: I used my functions to test. They just replace your db-processing code.

Just tested. This also works.
session_start();
// Get page name
$page_url = $_SERVER['REQUEST_URI'];
// Create the session ID. Will act as visitor username
if(!isset($_SESSION['id'])){
$_SESSION['id'] = session_id();
// For the visit to the first page
$visit_id = $_SESSION['id'];
}else{
// For subsequent visits to any page
$visit_id = $_SESSION['id'];
}
/******************
Query DB. Insert only one visit per page per session.
It means we need a count for each page to get its total visits.
Or a count for all records to get site total visits.
************************************/
$query_visits_table = mysqli_query($db_connect, "SELECT * FROM tblcount WHERE (visit_id='$visit_id') AND (page_name='$page_url')");
if(mysqli_num_rows($query_visits_table) > 0){
// Do nothing if this page has been visited during this session
}else{
mysqli_query($db_connect, "INSERT INTO tblcount (visit_id, page_name, visit) VALUES('$visit_id', '$page_url', '1')");
}
// Get site total visits
$query_site_visits = mysqli_query($db_connect, "SELECT * FROM tblcount");
// For a specific page
$query_specific_page_visit = mysqli_query($db_connect, "SELECT * FROM tblcount WHERE page_name='$page_url'");
if(isset($query_site_visits) && isset($query_specific_page_visit)){
$site_total_visits = mysqli_num_rows($query_site_visits);
$specific_page_visit = mysqli_num_rows($query_specific_page_visit);
echo 'Site total visits is '. $site_total_visits . '<br />';
echo 'Total visits for ' . $page_url . ' is ' . $specific_page_visit;
exit();
}

Related

Mysql Pageviews update only per session

just got help with making my code for pageviews work... and now i would like the pageviews only count 1 for each session / ip.
In my users (news.users) table i have these cells available for use: (tried to set up something earlier that didnt work out so these are not in use)
ip_reg, ip_visit, dtreg, dtvisit, visits, pass
The code i have that is now working looks like this :
//Adds one to the counter
mysql_query("UPDATE news SET posts = posts + 1, published=published, last_edit=last_edit WHERE id=$id");
//Retreives the current count
$count = mysql_fetch_row(mysql_query("SELECT posts FROM news WHERE id=$id"));
//Displays the count on your site print
echo "<label>Viewed: ";
echo $count[0];
echo " times</label>";
?>
Can i use some of the unused cells in users to stop a user from reloading the page to get higher views on a page? And how do i do it :P
Like I suggested I would put the read news articles in the user's session. Try this:
if (!isset($_SESSION['read_news']) || !is_array($_SESSION['read_news'])) {
$_SESSION['read_news'] = array();
}
if (!in_array($id, $_SESSION['read_news'])) {
$_SESSION['read_news'][] = $id;
mysql_query("UPDATE news SET posts = posts + 1 WHERE id=$id");
}
If this doesn't work, you don't have sessions enabled and you should put session_start(); somewhere in the top of your project. Make sure that line is called in each request.

Storing and retrieving _SESSION variables

I am working on a function that allows a user to up vote a post no more than one time. There are multiple posts on a page so I need to keep track of which posts the user has voted on.
I do that by keeping a total sum of the votes casts. For instance, if a user up votes a post, they should be remove their vote by down voting once, or change their original up vote to a down vote by down voting twice.
The first time a vote is cast, I initialize the $_SESSION variable to 0. A down vote takes it to -1 and an up vote takes it to 1.
Here is the PHP function for up vote (the down vote function is similar):
function upVote($post_id) {
global $databaseController;
if(!isset($_SESSION[$post_id])) {
$_SESSION[$post_id] = 0;
}
if($_SESSION[$post_id] <= 0) {
$sql = "SELECT likes FROM posts WHERE id='" . $post_id . "'";
$results = $databaseController->select($sql);
if($results && $results->num_rows == 1) {
$results = $results->fetch_assoc();
$new_likes = ++$results['likes'];
try {
$databaseController->startTransaction();
$sql = "UPDATE posts SET likes=" . $new_likes . " WHERE id=" . $post_id;
$databaseController->update($sql);
if($databaseController->commit()) {
$_SESSION[$post_id] = ++$_SESSION[$post_id];
return true;
}
} catch (Exception $e) {
$databaseController->rollback();
return false;
}
}
}
return false;
}
The $_SESSION[$post_id] is always being reset to 0 each time the function is called allowing the user to vote as many times as they want.
Why is this happening? It seems to me that the variable should only be set to 0 if the user has never voted on the post, else it just pulls up the variable, sees that it exists, and modifies it.
Is there anything wrong with my logic? Or am I not using $_SESSION variables in the correct way?

Why is my php/mysql update not accurate?

I have a webpage with a button on it. When the button it clicked it sends a request to a page with this code on it
$userName = "tdscott";
$url = "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
$divID = explode('?', $url);
$id = 0;
$id = explode('#',$divID[1])[1];
$func = $divID[2];
$find = mysqli_fetch_array(mysqli_query($con,"SELECT likes FROM status WHERE id='$id'"))['likes'];
if ($func == "addLike")
{
$promoted = $userName . "-";
mysqli_query($con, "UPDATE status SET promotedBy = CONCAT(promotedBy,'$promoted') WHERE id='$id'");
$find++;
mysqli_query($con,"UPDATE status SET likes = '$find' WHERE id='$id'");
echo $find;
}//end if addLike
elseif($func === "removeLike")
{
echo "ERROR";
}//end if removeLike
elseif ($func === "getLikes")
{
echo $find;
}//end if getLikes
mysqli_close($con);
I left of the database connection information. But for some reason when this is called it produces inaccurate results. For example... Sometimes it will put multiple instances of $promoted in the promotedBy field in my table and sometimes it will update other rows in the table that the id does not equal the current $id. I am wondering if somehow it is getting the $id variable mixed up from when I submitted it with a different value before. Is there a way to reset the variables before I call it each time?
Please note: In the if statement, we are only looking at the addLike portion. I included the other just in case it was causing the problem.
unset($id);
Sorry should have done more research.

How to increment count using session and id of a file using php

Below shows my coding to increment the number of publication view for my website. Right now it increments whenever I click refresh. I have used session command on some part of the code however it doesn't work, it increments whenever I click refresh. I want to understand how can I not make user to increment the session if they are in same session.
It will be very grateful if you can help me.
<?php
session_start();
$_SESSION['counted'] = true;
if (isset($_GET['id'])) {
$file_id = ($_GET['id']); //$id is a new vairable given value to the id selected in publication.php
if ($file_id <= 0) { //check if id is less than or equal to 0
die('The ID is invalid, please check the technical process!');
} else {
mysql_query("SELECT * FROM files WHERE id='$file_id'");
if (!isset($_SESSION['id'])) {
$_SESSION['id'] = 0;
$query = "UPDATE files SET visitors=visitors+1 WHERE id='$file_id'";
mysql_query($query);
mysql_close();
session_destroy();
}
}
}
?>
The reason it is incrementing each time you refresh is because of the following line of code:
session_destroy();
What it's doing is (as the name depicts) destroying your session after each increment, so next time the page loads, $_SESSION['id'] is no longer instantiated, so your if(!isset($_SESSION['id'])) always returns true.
You can try the following:
<?php
session_start();
$_SESSION['counted'] = true;
if (isset($_GET['id'])) {
$file_id = ($_GET['id']); //$id is a new variable given value to the id selected in publication.php
if ($file_id <= 0) { //check if id is less than or equal to 0
die('The ID is invalid, please check the technical process!');
} else {
mysql_query("SELECT * FROM files WHERE id='$file_id'");
if (!isset($_SESSION['id'][strval($_GET['id'])])) {
$_SESSION['id'][strval($_GET['id'])] = true;
$query = "UPDATE files SET visitors=visitors+1 WHERE id='$file_id'";
mysql_query($query);
mysql_close();
}
}
}
?>
I've used an array $_SESSION['id'] to store a key for each different page ID, then each time we test if we need to increment your counter, we check if an array key exists for that page, if it does, we don't increment.
Hope this helps! :)

Issue setting PHP cookie with included files

I have the following script which creates a cookie and updates a site counter in a database record if the user hasn't visited the website in a day, else, it will just display the current count of visits. Currently the cookie is displaying NULL every time I reload the index page and therefore the table keeps getting updated more than it should. How do I maintain the cookie value on the index page when this script is included?
if (empty($_COOKIE["visits"])) {
// increment the counter in the database
mysql_query("UPDATE visit_counter ".
" SET counter = counter + 1 ".
" WHERE id = 1");
/* Query visit_counter table and assign counter
value to the $visitors variable */
$QueryResult = mysql_query("SELECT counter ".
" FROM visit_counter WHERE id = 1");
// Place query results into an associative array if there are any
if (($row = mysql_fetch_assoc($QueryResult)) !== FALSE) {
$visitors = $row['counter'];
} else {
// else if this is the first visitor set variable to 1
$visitors = 1;
}
// Set cookie value
setcookie("visits", $visitors, time()+(60*60*24));
} else {
$visitors = $_COOKIE["visits"];
}
The cookie script is included in an index file, so the following would be the index file...
<?php include("Includes/cookie.php"); ?>
var_dump($_COOKIE["visits"]); /* Always returns NULL on this page but
returns the cookies real value if
run straight from cookie.php script */
/* Some main page content goes here */
/* The cookie value is echoed in the footer file that is included by
creating a statement that says echo "total visitors: ".$visitors; */
<?php include("Includes/footer.php"); ?>
The problem is on set_cookie
set it from:
<?php
// Set cookie value
setcookie("visits", $visitors, time()+(60*60*24));
?>
to
<?php
// Set cookie value
setcookie("visits", $visitors, time()+(60*60*24),'/'); // Define the cookie path to be used on this domain
?>
Good luck

Categories