PHP: Detect Page Refresh
I found this snippet here, and it worked perfectly for me:
$pageWasRefreshed = isset($_SERVER['HTTP_CACHE_CONTROL']) && $_SERVER['HTTP_CACHE_CONTROL'] === 'max-age=0';
if($pageWasRefreshed ) {
//do something because page was refreshed;
} else {
//do nothing;
}
Best way to Detect Page Refresh. or Not ?(Ctrl+F5,F5,Ctrl+R, Enter)
$pageRefreshed = isset($_SERVER['HTTP_CACHE_CONTROL']) &&($_SERVER['HTTP_CACHE_CONTROL'] === 'max-age=0' || $_SERVER['HTTP_CACHE_CONTROL'] == 'no-cache');
if($pageRefreshed == 1){
echo "Yes page Refreshed";
}else{
//enter code here
echo "No";
}
If you just want to run it once for a user, I would set a session cookie and then use an if() statement.
<?php
session_start();
if (!$_SESSION['loaded'])
{
// insert query here
}
$_SESSION['loaded'] = true;
?>
You can't directly detect a page refresh, but you can use a cookie to simulate what you want:
if (isset($_COOKIE['action'])) {
// action already done
} else {
setcookie('action');
// run query
}
Depending on your requirements, you also need to decide when to remove the cookie and/or perform the action again.