avoid page counting when click refresh button - php

I made a php script to counts the number of users have viewed my website's pages. This is my code
<?php
require_once ('test.php');
$institute_id = 14;
$q = "INSERT INTO page_views2 ( institute_id, views) VALUES ( $institute_id, 1)
ON DUPLICATE KEY UPDATE views=views+1"
;
$r = mysqli_query ($dbc, $q);
?>
I added this to top of my webpages and this is working (views incrementing) properly when I open the pages. But my problem is When I refresh the page, page views is incrementing by 1. It is okey when it is open first time. But I want to avoid from this when someone is refreshing the page.
so can any body tell me how can I do this?

Use sessions?
require_once ('test.php');
$institute_id = 14;
//if no such session exists, assume that its their first time viewing.
if(!isset($_SESSION[$institute_id.'_v'])){
//insert
$q = "INSERT INTO page_views2 ( institute_id, views) VALUES ( $institute_id, 1)
ON DUPLICATE KEY UPDATE views=views+1"
;
$r = mysqli_query ($dbc, $q);
//set session variable saying they've viewed this institutions page.
$_SESSION[$institute_id.'_v'] = 1;
}

Refreshing a page results in a new page request, so it obviously triggers your script on the server side. There's no way to alter this behaviour. What you can do is to implement some kind of checking, if the user requested the same page again (refresh) or not. You can store some info in your session/cookies and then just compare the values.

You could use cookies or sessions for that, I guess. Make a session variable that holds a timestamp of the latest visit. If the same page gets loaded again within an hour or so, the counter does not increase.

You can try to use 2 variables, one to define the name of each page you are visiting and one $_SESSION variable. You can set the $_SESSION with the name of the page you are viewing after you increment a counter with the query. Make the control variable each time before making the increment query and if the session variable has the same name as the page you are viewing skip the increment operation. Hope that helps.

Related

Avoiding people to refresh page?

i have some problem, i create a page to read news and if the page open it will be update in my database field for news_read +1 but i want if page refresh by user isn't +1
this is my query in page
$q="SELECT*FROM t_news WHERE news_id=$b_id";
$dataJ=mysql_query($q);
$a=mysql_fetch_array($dataJ);
$plus=$a['news_read']+1;
mysql_query("UPDATE t_news set news_read=$plus WHERE news_id=$a[news_id]");
anyone know, how to disable $plus=$a['berita_dibaca']+1; after refreshing the page?
UPDATE
UPDATE
thanks all ,i have solved my problem with session
i put
if ($_SESSION['load']==1){
$_SESSION['load']=0;
}
in all of my page except read.php and i put
if ($_SESSION['load']==0)
{
//QUERY
}
$_SESSION['load'] = 1;
in read.php
Method 1.
Save cookie, if user has cookie don't update database.
Method 2. (better)
Save users who have already viewed this article, and if user is in list do not update database.
Tip:
UPDATE t_news set news_read = news_read + 1 WHERE news_id = $a[news_id]
to avoid useless queries.
That's not a question to solve with sql, but with HTTP.
There is basically no difference between a refresh of a page and the inital request. There both just HTTP commands. There may be a difference in the headers of both requests but you can't always be sure they are present. So using the referer is probaly not a great idea.
Beside Valdas answer with the cookie you may also use the session of your user and set a flag there. (Although most session implementations do also use cookies, but in another way)
This method doesn't require a user to be logged in:
session_start(); // ignore if you're already using sessions
if( !isset($_SESSION['has_read_news'])) $_SESSION['has_read_news'] = array();
if( !isset($_SESSION['has_read_news'][$b_id])) {
mysql_query("UPDATE `t_news` SET `news_read`=`news_read`+1 WHERE `news_id`=".$b_id);
$_SESSION['has_read_news'][$b_id] = true;
}
Note that it's not completely foolproof (clearing the session cookie will allow the user to be counted again) but overall it should be plenty good enough.

Using Cookies to check if someone has visited a page

When a user visits one page I have:
setcookie("firstvisit", time()+3600);
In a functions file which is included in the header of every page I have:
if(isset($_COOKIE['firstvisit'])) {
$run = mysql_query("UPDATE `table` SET `firstvisit` = 1 WHERE `id` = '".$_SESSION['uid']."'");
setcookie("firstvisit", time()-3600);
If I do it like this (and it works) it means the script will run every time the user clicks on that page. Is there any other way to accomplish this?
Your code will only set firstvisit to 1 in the database on the second visit. This is because isset($_COOKIE['firstvisit']) must evaluate to true for the query to run, and cookies are only available in the next request - setcookie() doesn't add to the $_COOKIE array.
// assumes $_SESSION['uid'] is always set
if(!isset($_COOKIE['firstvisit'])) {
setcookie('firstvisit', time()); //set a cookie containing the timestamp of when this user first visited the page
$run = mysql_query("UPDATE `table` SET `firstvisit` = 1 WHERE `id` = '".$_SESSION['uid']."'");
}
else {
//it's not their first visit because the cookie already exists
}
Be aware that this logic won't work on multiple pages - the cookies will overwrite each other and the code will become unreliable.
You can check to see if the cookie is previously set or not before setting it.
if( !isset($_COOKIE['firstvisit']) ){ //if the cookie is not set
//set your cookie
} //skip otherwise
If you don't want to update the value every time. check that value in database whether it's already exist or not?

Session value doesnt pass on to the next page

Basically I want to grab an id send via the url (ex. www.website.com/?id=432432) and take it accross my website till the user hits the contact page. I created a variable and a session variable
session_start();
$getId = $_GET["id"];
$_SESSION['session_browser_test'] = $getId;
$adv_id = $_SESSION['session_browser_test'];
and used
echo $adv_id;
on my index.php Joomla template so it applies to all the pages.
But the issue is when i go to www.website.com/?id=432432 it echos the id on my web page, but if I click on the next link to go to another page (ex. www.website.com/nextPage) it doesnt hold the session value from the previous page. Why is that? and how can I carry the ID through out the site?
you will not get an id from URL on next page, likely
echo $getId;
instead you need to use id from session like,
$_SESSION['session_browser_test']; // your id stored in session
Start the session in each page
session_start();
In order to access the variable in a session, you have to call the $_SESSION variable.
echo $_SESSION['session_browser_test'];
HTTP is stateless, so you have to do something to remember your variable throughout the website .
make sure you correctly use session , like session_start();
when you send your id through get method ,it works, but when you go to any other page ,it doesn't make any sense to remember this.
use this for send id through pages:
<?php echo get_permalink(910); ?>?userid=<?php echo $value['userId'];?>
send this in url and use on next page as:
$sql = "select * from `wp_pelleresuser` where userId =".$_GET['userid'];
using this approach you can use a single variable on every page you want without using session. try google to how wordpress manage variable through all pages without using session. it will help you.
happy coding!
Start
session_start();
(if not started) in the index.php in root of your app (session probably will start on every pages) and then call (when desired):
$_SESSION['session_browser_test'];
instead of assi8gning this sess var to your own variable and then calling it in different places.
if(isset($_GET["adv_id"])){
$_SESSION['session_browser_test2'] = $_GET["adv_id"];
$adv_id = $_SESSION['session_browser_test2'];
}
else {
$adv_id = $_SESSION['session_browser_test2'];
}

How to save current url ID to a session and then update it upon viewing the next submission

Upon refreshing http://mydomain.com, it will generate a random ID to display on the page.
For example, http://mydomain.com generates 54 the first time, and upon reloading, 112, etc.
I'd like to save each of the randomly generated IDs to a session, so each time it reloads, I can go back to the last one. For example, the first time it saves 54 to a session, and when http://mydomain.com reloads and generates 112, I can link back to the 54.
I can't use HTTP_REFERER or REQUEST_URI, so I tried to work on my own version, but it's only saving it once. I can't figure out how to update it upon viewing the next ID.
if(empty($_SESSION['lastURL'])) {
$_SESSION['lastURL'] = $submissionId; // $submissionId is randomly generated
} else {
echo $_SESSION['lastURL'];
}
Is my current code. Where should I update the session to store the next ID?
Turns out the reason it kept misfiring was because it kept firing an additional ajax request, so I was getting a randomly generated id each time.
I (with the help of a friend) figured out by using the following code, and setting it before it randomly fires each time:
if(!isset($_SERVER['HTTP_X_REQUESTED_WITH']) || strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) != 'xmlhttprequest'){
// Not an ajax request - just a normal page load
$_SESSION['lastid'] = $_SESSION['currentid'];
$_SESSION['currentid'] = $submissionId;
}
You're only setting $_SESSION['lastURL'] once because it is only empty() once. You'll need to update this value whenever you generate a new ID (thus making it the new "old" one).
Remember to have session_start() at the top of the file where the sessions are being stored and read so that you have full access to them
If you want to save all ID's, you need to put them in an array:
if (!isset($_SESSION['url_list']))
{
$_SESSION['url_list'] = array();
}
$_SESSION['url_list'][] = $submissionId;
// see all entries
var_dump($_SESSION['url_list']);
Now you have a history of all ID's since the session started.

Doubt with retrieving values

I have created a page with name edit.php. I have moved on this page from action.php using a edit button. I have successfully retrieved the values in the respective text boxes and other form items. I have problem that if by mistake this edit.php page is refreshed all values are gone. What is other way to maintain the values? Though thing are going well if page is not refreshed. If session variable is created than how values are retrieved of both that is of session variable and from database?
What I have did with problem.. I have requested "albumid" on action.php page..
session_start();
$aid = mysql_real_escape_string($_REQUEST['albumid']);
Now if action.php page is requested through edit.php page using edit button. than I have created a session variable. and destroyed it after successful update query.
if (isset($_POST["edit"])) {
$_SESSION["aid"]=$aid;
$result= mysql_query("SELECT * FROM table WHERE a_id =".$_SESSION["aid"]) or die(mysql_error());
$row=mysql_fetch_array($result); }
It means now session is created.. if page is refreshed than also session values remains and accordingly values are selected from this variable.
if($_POST['update']!="") {
Update query
session destroyed }
Than also my problem is not solved that is if page is refreshed before hitting update button I am loosing all values.
session variables are just data you put into the $_SESSION superglobal. Accessing them is no different than accessing any other array, except that the session array is saved for you automatically. All you need to remember is to do a session_start() before doing anything with the session.
$_SESSION['formfield1'] = $_POST['formfield1'];
$_SESSION['formfield2'] = $_POST['formfield2'];
etc...
<input type="text" name="formfield1" value="<?php echo htmlspecialchars($_SESSION['formfield1']) ?>" />
By default, PHP uses file-based sessions. To put it into a database, you'd have to write your own session handlers and point PHP to them using session_set_save_handler().
When you submit, save the values in appropriately named $_SESSION members. Then on your page, if you can't find the members in $_GET/$_POST, you can choose to look them up in $_SESSION. Or vice versa. Every time the user submits a form though, you should always update $_SESSION so that the values are the most current. (in case they backtrack, or resubmit, or whatnot).
session_start();
if (!empty($_POST)) {
$_SESSION['post'] = $_POST;
}
elseif (empty($_POST) && !empty($_SESSION['post'])) {
$_POST = $_SESSION['post'];
}
just don't forget to unset($_SESSION['post']); when you're done with it.
If I have understood your question correctly, I think you need some variables from database as well as from the session.
Simply put the key of your database tuple (or keys in case of multiple values) along with other stuff. Page, upon loading will check for the session variables and when it finds the key, it can use it to retrieve the data from the database.
In your previous page, the code will look like this :
$_SESSION["player_key"] = 56;
$_SESSION["tournament_key"] = 100;
And current page, start processing like this :
<?php
session_start();
$player = $_SESSION["player_key"];
$tournament = $_SESSION["tournament_key"];
/*
* your database connection steps
*/
$query = "select * from player where pid=".$player;
$res = mysql_query($query);
/*
Now assign values for your forms/components here or anywhere in the page. You don't have to read anything from the querystring.
*/
?>

Categories