Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detect whether the browser is refreshed or not using PHP

Tags:

php

refresh

I want to detect whether the browser is refreshed or not using PHP, and if the browser is refreshed, what particular PHP code should execute.

like image 902
naveen Avatar asked Jan 19 '09 08:01

naveen


2 Answers

When the user hits the refresh button, the browser includes an extra header which appears in the $_SERVER array.

Test for the refresh button using the following:

    $refreshButtonPressed = isset($_SERVER['HTTP_CACHE_CONTROL']) && 
                            $_SERVER['HTTP_CACHE_CONTROL'] === 'max-age=0';
like image 192
Rototechno Avatar answered Nov 15 '22 12:11

Rototechno


If the page was refreshed then you'd expect two requests following each other to be for the same URL (path, filename, query string), and the same form content (if any) (POST data). This could be quite a lot of data, so it may be best to hash it. So ...


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

In an AJAX situation you'd have to be careful about which files you put this code into so as not to update the LastRequest signature for scripts which were called asynchronously.

like image 26
Bell Avatar answered Nov 15 '22 11:11

Bell