How to detect a page refresh with PHP?

→ Are you a new visitor? Please visit the page guidance for new visitors ←

How to detect a page refresh with PHP?

Sometimes you want to detect if the page was refreshed using “F5” key, or right click and “Reload” or any other method available. Either way, this can be detected somehow from server side. In this snippet, I will show you how to do this with PHP.

Method one

 Method two

You can do this also based on the session, but if you go away from the site and return later in the same browser, the counter will be the same since the session didn’t changed.

 

  • Nabhaa

    First method is not working with chrome as $_SERVER[‘HTTP_CACHE_CONTROL’] from the beginning(in my application just after login).

  • Nabhaa

    Method one does not work in google chrome as $_SERVER[‘HTTP_CACHE_CONTROL’] get set from the beginning of application.

  • Jim Geersinga

    this is a better approach


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

  • asfaq

    Method is working perfectly

Request an article ←