PHP: Detect Page Refresh

梦想的初衷 提交于 2019-12-17 06:48:09

问题


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
}

回答1:


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;
}



回答2:


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.




回答3:


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";
}



回答4:


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;

?>



回答5:


    //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
    }



回答6:


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
?>



回答7:


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!




回答8:


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



来源:https://stackoverflow.com/questions/4290230/php-detect-page-refresh

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!