Detect whether the browser is refreshed or not using PHP

前端 未结 6 1387
慢半拍i
慢半拍i 2021-01-01 02:51

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.

6条回答
  •  情话喂你
    2021-01-01 03:32

    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.

提交回复
热议问题