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
1 2 3 4 5 6 7 |
$pageWasRefreshed = isset($_SERVER['HTTP_CACHE_CONTROL']) && $_SERVER['HTTP_CACHE_CONTROL'] === 'max-age=0'; if($pageWasRefreshed ) { //do something because page was refreshed; } else { //do nothing; } |
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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
<?php session_start(); if (!isset($_SESSION["visits"])) $_SESSION["visits"] = 0; $_SESSION["visits"] = $_SESSION["visits"] + 1; if ($_SESSION["visits"] > 1) { //you refreshed the page! } else { //nothing to do here! } ?> |