PHP:检测页面刷新

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4290230/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 12:33:23  来源:igfitidea点击:

PHP: Detect Page Refresh

phprefresh

提问by Moon

I have a page action.phpon 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

我有一个页面action.php,我通过代码在该页面上运行 SQL 查询,这样无论何时查看页面,查询都会像计算页面浏览量一样运行

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

问题是当页面刷新时,查询运行& PAGE REFRESH 被算作我想避免的PAGE VIEW。

   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
}

采纳答案by Moon

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

我已经解决了这个问题...... HURRAHHH 没有会话和没有 cookie

the solution is a combination of PHP : AJAX : JavaScript

解决方案是 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

您想要在页面加载而不是在页面刷新上运行的查询通过 AJAX 调用运行它可以说我的功能是

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

我可以通过执行以下操作简单地使用 Javascript 检查页面是新加载还是刷新

<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.phpsimple add your PHP code which you were going to put in the normal page

并在您的doIT.php 中简单地添加您要放在普通页面中的 PHP 代码

<?php
mysql_query("UPDATE---------");
//put any code here, i won't run on any page refresh
?>

回答by Gideon Rosenthal

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

回答by Rizwan Siddiquee

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

检测页面刷新的最佳方法。或不?( 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";
}

回答by casablanca

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

您无法直接检测页面刷新,但您可以使用 cookie 来模拟您想要的内容:

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.

根据您的要求,您还需要决定何时删除 cookie 和/或再次执行该操作。

回答by Rutger

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

如果您只想为用户运行一次,我会设置一个会话 cookie,然后使用 if() 语句。

<?php
session_start();

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

$_SESSION['loaded'] = true;

?>

回答by Jim

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

回答by iammark

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!

如果用户在 URL 中有令牌,则视图计数不会更新。因此,如果用户尝试刷新,则不会更新查看计数。当用户在 URL 中没有令牌时,查看计数会更新并使用令牌刷新页面。它跳出框框思考,但它有效!

回答by Sairam

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.

您可以保存将与当前页面关联的 cookie,如果单击任何链接,则使用新页面名称更新 cookie。假设以上是在Javascript 中完成的,您可以将此 updateCookie 信息发送到服务器以通知新页面命中。

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

或者另一种方法是,您可以指定一个HTTP HEADER,它指定缓存在页面上过期多长时间,浏览器甚至不会向您发送有关页面加载/刷新的请求。

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

有关缓存的信息,请参阅http://www.mnot.net/cache_docs/#IMP-SCRIPT

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

另外,请查看 HTTP 中的 Etag vs Expires - ETag vs Header Expires