使用PHP检测浏览器是否刷新

nav*_*een 5 php refresh

我想检测是否使用PHP刷新浏览器,如果刷新浏览器,应该执行哪些特定的PHP代码.

小智 13

当用户点击刷新按钮时,浏览器包含一个额外的标题,该标题出现在$ _SERVER数组中.

使用以下方法测试刷新按钮:

    $refreshButtonPressed = isset($_SERVER['HTTP_CACHE_CONTROL']) && 
                            $_SERVER['HTTP_CACHE_CONTROL'] === 'max-age=0';
Run Code Online (Sandbox Code Playgroud)


Bel*_*ell 12

如果页面被刷新,那么您希望两个请求彼此跟随相同的URL(路径,文件名,查询字符串)和相同的表单内容(如果有的话)(POST数据).这可能是相当多的数据,因此最好将其哈希.所以......


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

Run Code Online (Sandbox Code Playgroud)

在AJAX情况下,您必须小心将此代码放入哪些文件,以便不为异步调用的脚本更新LastRequest签名.