5

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.

Cœur
  • 37,241
  • 25
  • 195
  • 267
naveen
  • 1,451
  • 6
  • 21
  • 27
  • If you want to prevent that request with side effects (in general POST requests) can be send several times, you should say this in your question. Because this will use a different approach than the answers used so far. – Gumbo Jan 19 '09 at 15:34
  • Agreed with Gumbo. If in fact your goal is to avoid side effects from POST requests, you should probably redirect using GET to a new page. – Wickethewok Jan 19 '09 at 17:40

6 Answers6

14

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';
Rototechno
  • 141
  • 1
  • 2
13

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.

Bell
  • 17,907
  • 4
  • 23
  • 25
  • 1
    @naveen what if the user has more than one tab open on your website, submits a form on the first tab, submits something else on another tab, closes that tab, then hits refresh on the first tab? last request may not always work. – dqhendricks Jan 23 '12 at 17:19
2
<?php

    session_start();
    if (!isset($_SESSION["visits"]))
        $_SESSION["visits"] = 0;
    $_SESSION["visits"] = $_SESSION["visits"] + 1;

    if ($_SESSION["visits"] > 1)
    {
        echo "You hit the refresh button!";
    }
    else
    {
        echo "This is my site";
    }

    // To clear out the visits session var:
    // unset($_SESSION["visits"]);

?>
  • 1
    This of course doesn't guarantee that they hit the refresh button. They might have navigated back to this page through (for example) one of your site's internal links. – Wickethewok Jan 19 '09 at 17:37
  • 1
    Down vote. This will only detect multiple visits to the site. Every reload or navigation to another URL that has this script will increment the counter. It's not useful for detecting page reloads. – six8 Aug 28 '12 at 05:42
1

If you mean that you want to distinguish between when a user first comes to the page from when they reload the page check the referrer. In php it is: $_SERVER["HTTP_REFERER"]. See if it is equal the page your script is running on. It may be the case that the client doesn't provide this information, if that happens you could set a cookie or session variable to track what the last requested page was.

Bjorn
  • 69,215
  • 39
  • 136
  • 164
1

To prevent duplicate form processing when a user hits the browser refresh or back button, you need to use a page instance id session variable, and a hidden form input that contains that variable. when the two don't match, then the user has refreshed the page, and you should not reprocess the form. for further details, see:

https://www.spotlesswebdesign.com/blog.php?id=11

dqhendricks
  • 19,030
  • 11
  • 50
  • 83
  • another method is to submit form requests to a completely separate page, then use a header to redirect server side back to the original page after a request is processed. this way the back button and refresh button will not affect anything, since the form processing page is never actually loaded client side. – dqhendricks Jan 23 '12 at 17:21
0

If someone refreshes a page, the same request will be sent as the previous one. So you should check whether the current request is the same as the last one. This can be done as follows:

session_start();

$pageRefreshed = false;
if (isset($_SESSION['LAST_REQUEST']) && $_SERVER['REQUEST_URI'] === $_SESSION['LAST_REQUEST']['REQUEST_URI']) {
    if (isset($_SERVER['HTTP_REFERER'])) {
         // check if the last request’s referrer is the same as the current
         $pageRefreshed = $_SERVER['HTTP_REFERER'] === $_SESSION['LAST_REQUEST']['HTTP_REFERER'];
    } else {
         // check if the last request didn’t have a referrer either
         $pageRefreshed = $_SERVER['HTTP_REFERER'] === null;
    }
}

// set current request as "last request"

$_SERVER['LAST_REQUEST'] = array(
    'REQUEST_URI'  => $_SERVER['REQUEST_URI'],
    'HTTP_REFERER' => isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : null
);

I haven’t tested it but it should work.

Ashwin Ramaswami
  • 873
  • 13
  • 22
Gumbo
  • 643,351
  • 109
  • 780
  • 844