How To Detect a page refresh or new page entered in PHP

Detect a page refresh or new page entered in PHP

Detect a page refresh or new page entered in PHP

To detect a whether a page is refresh or page is entrered i.e. accessed via some other page link clicked, I prefer to use $_SERVER. For me using this variable is a better choice rather than making loops and asigning extra variables, unless it is not needed. Loops and variable asignment may prove better in temporary visit counts.

What is $_SERVER?

$_SERVER is a array containing information such as headers, paths, and script locations. The entries in this array are created by the web server. So there is no guarantee that every web server will provide any of these. Some servers may omit some, or provide others which are not provided by your server or mine.

How to detect a page refresh with PHP?

While browing we usually refresh the page using:

  • Pressing “F5” key
  • Right click and chosing “Reload”
  • Pressing a key combination of Ctrl+R
  • And many other options avalable in different platforms

Sometimes we have need 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.

$is_page_refreshed = (isset($_SERVER['HTTP_CACHE_CONTROL']) && $_SERVER['HTTP_CACHE_CONTROL'] == 'max-age=0');

if($is_page_refreshed ) {
  echo 'This Page Is refreshed.';
} else {
  echo 'This page is freshly visited. Not refreshed.';
}

9 thoughts on “Detect a page refresh or new page entered in PHP

  1. this did not work for me, because I wanted to delete a recordset from a dbtable when a user mistakenly or intentionally refreshed his or her current page

    1. It works in most of the cases, though you should try to debug the situation for specific case.

  2. Wһеn sօmeone wгites аn piece of writing he/sһe keeps thе tһoսght of a
    useг in his/her brain tһat hoᴡ a user
    can қnow it. Ꭲherefore that’s why thiѕ piece ⲟf
    writing iѕ amazing. Thankѕ!

  3. Sorry to let you know but this is not working. I do get the idea behind your idea but maybe you have to find another way for getting this to work in every situation.

    Thanks anyway! Enjoy your day!

  4. What’s up to every single one, it’s really a good for me to
    pay a visit this web page, it consists of valuable Information.

Average 
 4.1 Based On 6

Leave a Reply