Detect if user refreshed page - php

How can I detect if user refreshed the page with PHP?
I tried $pageWasRefreshed = isset($_SERVER['HTTP_CACHE_CONTROL']) && $_SERVER['HTTP_CACHE_CONTROL'] === 'max-age=0';
But it didn't work for me because i have no-cache.
Here's What worked for me:
$pageWasRefreshed = isset($_SERVER['HTTP_CACHE_CONTROL']);
if($pageWasRefreshed ) {
// Page was refreshed
}
else {
// Page wasn't refresh
}
Any water stones in this method?

Set a cookie for the first time when someone visits the page. So, when refresh check whether cookie exists or not, if yes the page is refreshed.
if (isset($_COOKIE['token']))
{
//The page is refeshed,
}
else
{
//first time user, set cookie.
setcookie('token');
}

You can do this multiple ways:
Set a session on the first time then check if the session is set or not.
Insert the client IP address in the MySQL database and check on every request if the user has visited before or not.
Now you have created your own logic and Google it how to implement this way
I suggest you use 2nd solution.

Related

One button that cycles through URL's that can work with HTML/Wordpress

I have a button that I would like to cycle through multiple URL's when clicked.
Example: Person comes to website -> Clicks button.
Button checks to see which URL is next in a sequence, and sends user to the next url in a sequence.
Thus creating a button that can serve multiple URL's, one for each click.
Something like this:
?php
$link[1] = "http://www.site1.com";
$link[2] = "http://www.site2.com";
$link[3] = "http://www.site3.com";
if(!isset($HTTP_cookie_VARS['link'])){ $n=count($link);
$rand=rand(1,$n); setcookie("link",$rand,time()+3600);
header('location:'.$link[$rand]); }else{ $go=$link[$_COOKIE['link']]; header('location:'.$go); }
?>
Though, something that would work in HTML?
If you want to do this per person, then cookies is the way to go. Make an array of the links, and store the pointer number in the cookie. Check if cookie, if no cookie, make cookie and send to first link, else increment number in cookie, click that link. Don't forget to also check if its the last link stored in the cookie so you can set it can go back to the first one.
I won't code it for you, but here is the structure for your code:
make an array of links
if (cookie exists) {
if (lastNum) {
set cookie to 0
send to link 0
}
else {
set cookie to num+1
sent to link num+1
}
}
else {
set cookie to 0
send to link 0
}

Detecting if cookies are enabled with PHP, header redirection

I am really suffering here trying to get this ajax call to work, sorry for the massiveness of this question.
The user clicks a button, this initiated an ajax call to add a vote to the database. Here is the file called "addvote.php":
<?php
session_start();
/* COOKIECHECK START */
setcookie('test', 1, time()+3600);
if(!isset($_GET['cookies'])){
header("Location:/thought/addvote.php?cookies=true&id=".$_GET['id']."&ans=".$_GET['ans']);
}
if(count($_COOKIE) > 0){
$cookies=1;
} else {
$cookies=0;
}
/* COOKIECHECK END */
if($cookies==1) {
$id=$_GET["id"];
$vId="v".$id;
if (((isset($_SESSION[$vId]) && ((time() - $_SESSION[$vId]) > 180))) || (!isset($_SESSION[$vId]))) {
// last vote was more than 3 minutes ago
$_SESSION[$vId] = time(); // update/create vote time stamp
//ADD VOTE TO DATABASE
}
else {
echo "You've voted on this already";
}
}
else {
echo "Please enable cookies to make your vote count";
}
?>
What is supposed to happen: The user is checked to see if they have cookies enabled. If so, they are allowed to add a vote, if not tell them to enable cookies. If they have cookies enabled, and they havn't voted already - add a vote, if they have voted already, tell them.
What actually happens: A user who hasn't voted yet clicks the button, this initiates the ajax call and the vote is successfully added, no message is sent to the user. They then move onto another question and click the vote button, "addvote.php" is initiated, but this time it returns "You've voted on this already" AND adds a vote! This makes me thing that the page call is running twice, first it adds the vote, then it tries again (and returns the error).
Maybe it has something to do with the header()??
Every question then returns this same message and adds a vote - unless I wait a while and then it works on the first question and the same thing happens again.
Point of note is:
The GET variables are passed along with the header so that I know which question they're talking about and whether they clicked no or yes.
Again, apologies, this question is a horrible one.
This will not prevent cheating with voting anyway. To test if user has cookies enabled, you can, for example, set cookie using JavaScript on voting page and check it in PHP. But, obviously, if someone wants to cheat, he or she will remove your cookies manually.
Furthemore, you need to add exit after header() call to make your code work:
setcookie('test', 1, time()+3600);
if(!isset($_GET['cookies'])){
header("Location:/thought/addvote.php?cookies=true&id=".$_GET['id']."&ans=".$_GET['ans']);
exit;
}

php redirect check

Is there anyway to determine if a page has come from a php redirect?
I have a session saved of the last time the page was refreshed, but i dont want it to set if the page has come from an instantly referred one.
To give some idea of what i'm doing, i have this code on my site to stop users refreshing more than once per second:
$now = time();
if ($_SESSION['click'] > ($now-1)) {
exit("Woah, you're clicking too fast!") ;
}
$_SESSION['click'] = $now;
However, I don't want the click session to set if the page has from from a php redirect, or a form post, etc. Any solutions?
How about using referer?
if( $_SERVER['HTTP_REFERER'] == "http://mydomain.com/formmail.php" )

How can you work around the re-sending of the http referrer data on refresh in php?

I have a IN/OUT ratio hit counting system on my site. When a user is sent to my site, I grab the referrer, strip the domain, look up the domain and +1 to hits_in. Very simple. What I discovered thou is, if a user refreshes the page, the referrer is resent to the site, and it counts it as another +1. Whats even worse is that if user clicks on some link on the site, and then hits BACK to go to the original page, the referrer is resent, and it counts as another +1. So if a foreign site sends me 1 user, who clicks on a video link, views the video, hits BACK in his browser, and then does this 3 times, it will count as if a site sent me 4 users when in fact its just 1.
Any way I could prevent the 2 examples from happening without actually logging all IPs and checking access times for each IP before doing the +1.
I am not expert in this, but can't you just use sessions. temporarily store referred url into session, so if user clicks back than check if users session contains referral site. if it contains don't count.
Do something like,
If the user doesn't have the cookie 'referer_logged' set, log their referer and set the cookie.
This would make it log only one referer per user.
Here's a referer script i use sometimes.
Put this in your functions file.
function referer()
{
if(isset($_SERVER["HTTP_REFERER"]) && substr($_SERVER["HTTP_REFERER"], 0, 22) != "http://www.example.com" && substr($_SERVER["HTTP_REFERER"], 0, 18) != "http://example.com")
{
$result = sprintf("INSERT INTO referer (referer, ip, date) VALUES ('%s', '%s', '%d')", mysql_real_escape_string($_SERVER["HTTP_REFERER"]), mysql_real_escape_string($_SERVER["REMOTE_ADDR"]), time());
$query = mysql_query($result);
if($query)
{
return true;
}
else
{
return false;
}
}
}
And somewhere in your index file
session_start();
if(!isset($_SESSION["referer"]))
{
if(referer())
{
$_SESSION["referer"] = 1;
}
}

Detect whether the browser is refreshed or not using PHP

I want to detect whether the browser is refreshed or not using PHP, and if the browser is refreshed, what particular PHP code should execute.
When the user hits the refresh button, the browser includes an extra header which appears in the $_SERVER array.
Test for the refresh button using the following:
$refreshButtonPressed = isset($_SERVER['HTTP_CACHE_CONTROL']) &&
$_SERVER['HTTP_CACHE_CONTROL'] === 'max-age=0';
If the page was refreshed then you'd expect two requests following each other to be for the same URL (path, filename, query string), and the same form content (if any) (POST data). This could be quite a lot of data, so it may be best to hash it. So ...
<?php
session_start();
//The second parameter on print_r returns the result to a variable rather than displaying it
$RequestSignature = md5($_SERVER['REQUEST_URI'].$_SERVER['QUERY_STRING'].print_r($_POST, true));
if ($_SESSION['LastRequest'] == $RequestSignature)
{
echo 'This is a refresh.';
}
else
{
echo 'This is a new request.';
$_SESSION['LastRequest'] = $RequestSignature;
}
In an AJAX situation you'd have to be careful about which files you put this code into so as not to update the LastRequest signature for scripts which were called asynchronously.
<?php
session_start();
if (!isset($_SESSION["visits"]))
$_SESSION["visits"] = 0;
$_SESSION["visits"] = $_SESSION["visits"] + 1;
if ($_SESSION["visits"] > 1)
{
echo "You hit the refresh button!";
}
else
{
echo "This is my site";
}
// To clear out the visits session var:
// unset($_SESSION["visits"]);
?>
If you mean that you want to distinguish between when a user first comes to the page from when they reload the page check the referrer. In php it is: $_SERVER["HTTP_REFERER"]. See if it is equal the page your script is running on. It may be the case that the client doesn't provide this information, if that happens you could set a cookie or session variable to track what the last requested page was.
To prevent duplicate form processing when a user hits the browser refresh or back button, you need to use a page instance id session variable, and a hidden form input that contains that variable. when the two don't match, then the user has refreshed the page, and you should not reprocess the form. for further details, see:
https://www.spotlesswebdesign.com/blog.php?id=11
If someone refreshes a page, the same request will be sent as the previous one. So you should check whether the current request is the same as the last one. This can be done as follows:
session_start();
$pageRefreshed = false;
if (isset($_SESSION['LAST_REQUEST']) && $_SERVER['REQUEST_URI'] === $_SESSION['LAST_REQUEST']['REQUEST_URI']) {
if (isset($_SERVER['HTTP_REFERER'])) {
// check if the last request’s referrer is the same as the current
$pageRefreshed = $_SERVER['HTTP_REFERER'] === $_SESSION['LAST_REQUEST']['HTTP_REFERER'];
} else {
// check if the last request didn’t have a referrer either
$pageRefreshed = $_SERVER['HTTP_REFERER'] === null;
}
}
// set current request as "last request"
$_SERVER['LAST_REQUEST'] = array(
'REQUEST_URI' => $_SERVER['REQUEST_URI'],
'HTTP_REFERER' => isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : null
);
I haven’t tested it but it should work.

Categories