21

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
}
Vijaya Pandey
  • 4,252
  • 5
  • 32
  • 57
Moon
  • 19,518
  • 56
  • 138
  • 200
  • 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 this – Moon Nov 27 '10 at 05:13
  • @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? – bob-the-destroyer Nov 27 '10 at 05:19
  • There is no change in $_SERVER array for page refresh so, May be done by Using Session – Naresh Nov 27 '10 at 05:20
  • no.. if i wanted to do that i would store some user identity with me and count the distinct identities... – Moon Nov 27 '10 at 05:22
  • thinking over it has made me realize this shouldn't be handled by PHP... – Moon Nov 27 '10 at 05:32
  • `@everybody :` i have posted the solution of this as answer to my own question.. look below – Moon Nov 27 '10 at 06:20

9 Answers9

39

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;
}
Gideon Rosenthal
  • 1,953
  • 2
  • 18
  • 16
  • 4
    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. @user1032531 – Hafenkranich Aug 07 '17 at 20:55
17

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";
}
Mesabloo
  • 337
  • 4
  • 13
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.

casablanca
  • 69,683
  • 7
  • 133
  • 150
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;

?>
Rutger
  • 96
  • 3
  • 1
    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 – Moon Nov 27 '10 at 05:29
  • i have solved it , i have posted the solution of this as answer to my own question.. – Moon Nov 27 '10 at 06:21
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
    }
jim
  • 3
  • 3
Jim
  • 361
  • 4
  • 16
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
?>
Moon
  • 19,518
  • 56
  • 138
  • 200
  • 4
    This assumes that the form values are retained after a refresh -- this is true in Firefox and IE but not in Chrome. – casablanca Nov 27 '10 at 06:31
  • 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 special` – Moon Nov 27 '10 at 06:35
  • 5
    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. – Ben Regenspan Nov 27 '10 at 06:54
  • 2
    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. – deceze Nov 27 '10 at 07:09
  • 5
    Looks like this does not work when javascript is not enabled. – Sairam Nov 27 '10 at 17:31
  • 3
    The answer by the questionnaire is wrong and is misleading to the SO users. – Jach Many May 28 '13 at 06:26
  • You may never trust client side code. Your js and ajax code runs at client side. – MERT DOĞAN May 25 '17 at 05:44
  • client side code can easily be manipulated so its not 100% perfect – Diego Feb 28 '18 at 03:10
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!

Pete
  • 333
  • 1
  • 12
iammark
  • 37
  • 5
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

Community
  • 1
  • 1
Sairam
  • 2,708
  • 1
  • 25
  • 34
  • 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. – deceze Nov 27 '10 at 07:11
0
if( $_SERVER['HTTP_CACHE_CONTROL'] == 'max-age=0')
{
    $_SESSION['status'] = null;<br>
}
TarangP
  • 2,711
  • 5
  • 20
  • 41
Froggy
  • 1
  • 1