PHP: Detect Page Refresh
Asked Answered
I

10

23

I have a page action.php on which I run an SQL query through the code, so that whenever the page is viewed the query runs like its like counting page views

<?php
mysqli_query("UPDATE ****");
?>

The problem is when the page is refreshed, the query is run & PAGE REFRESH is counted as a PAGE VIEW which I want to avoid.

   Question: How to avoid it ?

What I am looking for is a simple solution so that I can check

if( page was refresh ) //some condition
{
 do
}
Izettaizhevsk answered 27/11, 2010 at 5:9 Comment(6)
is there any $_SERVER[''] attribute which would be different when a page is directed from a link & the page is refreshed.. if that is so then there is no problem solving thisIzettaizhevsk
@Junaid Saeed: just to be clear, do you also wish to not count when a user browses away from the page and then browses back?Trapeziform
There is no change in $_SERVER array for page refresh so, May be done by Using SessionCupboard
no.. if i wanted to do that i would store some user identity with me and count the distinct identities...Izettaizhevsk
thinking over it has made me realize this shouldn't be handled by PHP...Izettaizhevsk
@everybody : i have posted the solution of this as answer to my own question.. look belowIzettaizhevsk
I
3

i have solved the problem ... HURRAHHH with no session & no cookies

the solution is a combination of PHP : AJAX : JavaScript

the query that you want to run on Page Load & not on page Refresh run it as via AJAX call lets say my function for doing that is

function runQUERY()
{
    xmlhttp=new XMLHttpRequest();
    xmlhttp.open("POST","doIT.php",false);
    xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
    xmlhttp.send();
}

and i can simply check with Javascript that the page is a fresh load or its a refresh by doing the following

<head>
<script type="text/javascript">
function checkRefresh()
{
    if( document.refreshForm.visited.value == "" )
    {           
        // This is a fresh page load
            alert ( 'Fresh Load' );
        document.refreshForm.visited.value = "1";
            ..call you AJAX function here
    }
    else
    {
        // This is a page refresh
        alert ( 'Page has been Refreshed, The AJAX call was not made');

    }
}
</script>    
</head>

<body onLoad="checkRefresh()">

<form name="refreshForm">
<input type="hidden" name="visited" value="" />
</form>

</body>
</html>

and in your doIT.php simple add your PHP code which you were going to put in the normal page

<?php
mysql_query("UPDATE---------");
//put any code here, i won't run on any page refresh
?>
Izettaizhevsk answered 27/11, 2010 at 6:19 Comment(8)
This assumes that the form values are retained after a refresh -- this is true in Firefox and IE but not in Chrome.Ettie
well then i think its Google's problem to match the steps while walking... and not going on doing a catwalk.. thinking oh i can do this because now i am very specialIzettaizhevsk
I don't think this behavior you're seeing in FF and IE is part of any standard, and it could be subject to change, inconsistent between versions of those browsers, non-future-proof, etc. Cookie seems like a far more reliable solution.Theomania
Indeed, Chrome is not doing anything wrong, because there's no specified behavior for retaining form values on page refreshes/back/forward navigation. The correct way would be to present the page as intended (usually blank); retaining form values is something that some browsers may or may not do. Very interesting hack that works at least partly though.Somersault
Looks like this does not work when javascript is not enabled.Uphold
The answer by the questionnaire is wrong and is misleading to the SO users.Latoshalatouche
You may never trust client side code. Your js and ajax code runs at client side.Scorpaenid
client side code can easily be manipulated so its not 100% perfectHornswoggle
G
40

I found this snippet here, and it worked perfectly for me:

$pageWasRefreshed = isset($_SERVER['HTTP_CACHE_CONTROL']) && $_SERVER['HTTP_CACHE_CONTROL'] === 'max-age=0';

if($pageWasRefreshed ) {
   //do something because page was refreshed;
} else {
   //do nothing;
}
Grandam answered 15/7, 2014 at 20:16 Comment(1)
A POST request cant get "refreshed". It can only be send again. Thus chrome does this the right way and does not send the equivalent cache headers. @user1032531Scholasticate
S
18

Best way to Detect Page Refresh. or Not ?(Ctrl+F5,F5,Ctrl+R, Enter)

$pageRefreshed = isset($_SERVER['HTTP_CACHE_CONTROL']) &&($_SERVER['HTTP_CACHE_CONTROL'] === 'max-age=0' ||  $_SERVER['HTTP_CACHE_CONTROL'] == 'no-cache'); 
if($pageRefreshed == 1){
    echo "Yes page Refreshed";
}else{
    //enter code here
    echo "No";
}
Sunday answered 17/5, 2016 at 9:12 Comment(1)
Did not work for me using PHP 7.4.12 CGI server local dev machine, and Google Chrome Nov-2020Concubine
E
11

You can't directly detect a page refresh, but you can use a cookie to simulate what you want:

if (isset($_COOKIE['action'])) {
  // action already done
} else {
  setcookie('action');
  // run query
}

Depending on your requirements, you also need to decide when to remove the cookie and/or perform the action again.

Ettie answered 27/11, 2010 at 5:17 Comment(0)
K
6

If you just want to run it once for a user, I would set a session cookie and then use an if() statement.

<?php
session_start();

if (!$_SESSION['loaded'])
{
    // insert query here
}

$_SESSION['loaded'] = true;

?>
Keyway answered 27/11, 2010 at 5:16 Comment(2)
once the $_SESSION['loaded'] is set i won't be able to make this check on any other page or on the same page with different parameters like you have the leech pages...unless the session is destroyed and i i destroy the session it means if my user is logged in, he\she will be logged out... and this syntax that you have given above will not work.... correct syntax is <?php session_start(); if (!isset($_SESSION['load']) ) { echo ("Go"); } $_SESSION['load'] = 1; ?>Izettaizhevsk
i have solved it , i have posted the solution of this as answer to my own question..Izettaizhevsk
I
3

i have solved the problem ... HURRAHHH with no session & no cookies

the solution is a combination of PHP : AJAX : JavaScript

the query that you want to run on Page Load & not on page Refresh run it as via AJAX call lets say my function for doing that is

function runQUERY()
{
    xmlhttp=new XMLHttpRequest();
    xmlhttp.open("POST","doIT.php",false);
    xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
    xmlhttp.send();
}

and i can simply check with Javascript that the page is a fresh load or its a refresh by doing the following

<head>
<script type="text/javascript">
function checkRefresh()
{
    if( document.refreshForm.visited.value == "" )
    {           
        // This is a fresh page load
            alert ( 'Fresh Load' );
        document.refreshForm.visited.value = "1";
            ..call you AJAX function here
    }
    else
    {
        // This is a page refresh
        alert ( 'Page has been Refreshed, The AJAX call was not made');

    }
}
</script>    
</head>

<body onLoad="checkRefresh()">

<form name="refreshForm">
<input type="hidden" name="visited" value="" />
</form>

</body>
</html>

and in your doIT.php simple add your PHP code which you were going to put in the normal page

<?php
mysql_query("UPDATE---------");
//put any code here, i won't run on any page refresh
?>
Izettaizhevsk answered 27/11, 2010 at 6:19 Comment(8)
This assumes that the form values are retained after a refresh -- this is true in Firefox and IE but not in Chrome.Ettie
well then i think its Google's problem to match the steps while walking... and not going on doing a catwalk.. thinking oh i can do this because now i am very specialIzettaizhevsk
I don't think this behavior you're seeing in FF and IE is part of any standard, and it could be subject to change, inconsistent between versions of those browsers, non-future-proof, etc. Cookie seems like a far more reliable solution.Theomania
Indeed, Chrome is not doing anything wrong, because there's no specified behavior for retaining form values on page refreshes/back/forward navigation. The correct way would be to present the page as intended (usually blank); retaining form values is something that some browsers may or may not do. Very interesting hack that works at least partly though.Somersault
Looks like this does not work when javascript is not enabled.Uphold
The answer by the questionnaire is wrong and is misleading to the SO users.Latoshalatouche
You may never trust client side code. Your js and ajax code runs at client side.Scorpaenid
client side code can easily be manipulated so its not 100% perfectHornswoggle
D
3
    //here you get the url behind the domain.
    $currentPage = $_SERVER['REQUEST_URI']; 

    //if the session current page is not set.
    if(!isset($_SESSION['currentPage'])){ 

      //set the session to the current page.
      $_SESSION['currentPage'] = $currentPage;     
    }

    //check if the session is not equal to the current page
    if($_SESSION['currentPage'] != $currentPage){

       // if it's not equal you set the session again to the current page.
       $_SESSION['currentPage'] = $currentPage;

       //set the query you want to use
    }
Deceive answered 18/6, 2014 at 7:28 Comment(0)
W
2

This can work in your scenario:

if(isset($_GET["token"])) {
    $view_token = $_GET["token"];
} else {
    $new_views = $views + 1;
    // UPDATE VIEWS
    $view_token = substr(str_shuffle(str_repeat("0123456789abcdefghijklmnopqrstuvwxyz", 5)), 0, 5);
    header("Location: ?token=$view_token");
}

If the user has a token in the URL, the view count will not update. Therefore, if the user tries to refresh, it will not update the view count. When the user does not have a token in the URL, the view count updates and refreshes the page WITH a token. It is thinking outside of the box but it works!

Wily answered 22/5, 2018 at 21:38 Comment(0)
U
1

You can save a cookie that will be associated with the present page and if any link is clicked, update the cookie with the new page name. Assuming the above is done in Javascript, you can send this updateCookie information to the server to notify about a new page hit.

Or another approach could be, you can specify a HTTP HEADER that specifies after how much time the cache expires on a page and that way, the browser wont even send you a request about page load/refresh.

See http://www.mnot.net/cache_docs/#IMP-SCRIPT for information about CACHING

Also , check out Etag vs Expires in HTTP - ETag vs Header Expires

Uphold answered 27/11, 2010 at 6:10 Comment(1)
Agreed on the cookie, but when expressly refreshing a page, a browser will usually request the page from the server again regardless of cache settings.Somersault
B
0

My own solution is like this:

Add Form field, ex: 'refresh', which value will always increase unless it's a Page-Refresh. Because Page-Refresh only submit old value. Then compare to same value kept in PHP's SESSION var. If a new page, just initiate both values different each other.

in the PHP:

$pageWasRefreshed = false;
if (isset($_POST['refresh']) && isset($_SESSION['refreshdetect']))
    $pageWasRefreshed = ($_SESSION['refreshdetect'] == $_POST['refresh']);
                                                                    
if(!$pageWasRefreshed ) 
{
   //.....change status
}

if (isset($_POST['refresh']))
{
    $_SESSION['refreshdetect'] = $_POST['refresh'];                                 
    $row['refreshdetect'] = ((int)$_POST['refresh'])+1;                             
}
else //if new page
{
    $_SESSION['refreshdetect'] = 0;
    $row['refreshdetect'] = 1;                              
}

in the PHP->HTML (if using Twig. change to PHP code to display variable's value):

<input type="hidden" id="refresh" name="refresh" value="{{ row.refreshdetect }}" />
Boost answered 10/5 at 0:37 Comment(0)
R
-1
if( $_SERVER['HTTP_CACHE_CONTROL'] == 'max-age=0')
{
    $_SESSION['status'] = null;<br>
}
Rovner answered 10/9, 2020 at 9:37 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.