PHP: Detect Page Refresh
Running a database update on every page load sounds like a straightforward way to track activity, but it introduces a significant logical flaw: the refresh button. When a user executes an action and then hits F5 or clicks the reload icon, your script runs again. If you treat that second execution as a new view or event, your data becomes inflated. The core requirement is to distinguish between an initial load and a subsequent refresh of the same request.
In PHP, there is no direct property like is_refresh() provided by the framework or language engine. You have to infer this state based on the HTTP headers sent by the client. The most reliable signal for a page reload is the presence of the HTTP_REFERER header combined with the current URL, but simply checking if the referer matches the current URL is often insufficient because users can navigate via direct links that lack a referer while still being "fresh" views.
However, the standard approach to solving this specific problem relies on detecting the Post/Redirect cycle or simply identifying that the request method and state haven't changed since the last interaction in a way that implies a manual reload. But there is a more direct signal often used: the X-Forwarded-For header isn't it; the real indicator for a client-side refresh is usually implicit in how the browser handles the history stack, but at the PHP level, we look at specific headers.
The most common and robust method to detect a page refresh is checking for the HTTP_REFERER header when you are on a POST action that has just been rendered. But if you are on a simple GET request (like your action.php), detecting a hard refresh is tricky because the browser often clears cookies or session data differently depending on cache settings.
A more practical solution involves checking the X-Forwarded-For header isn't right here. The specific header that indicates a page reload in many scenarios is actually absent by default, but we can simulate the logic using session flags. When a user visits a page for the first time, you set a flag in the session. On subsequent requests to the same URL within a short timeframe, if that flag exists and hasn't been cleared, it suggests a refresh.
Here is how you can implement this check in your action.php:
session_start();
$currentUrl = $_SERVER['REQUEST_URI'];
// Check if we have seen this specific URL recently
if (!isset($_SESSION['last_viewed_url']) || $_SESSION['last_viewed_url'] !== $currentUrl) {
// First time visiting this URL, or the session expired/reset between visits
$_SESSION['last_viewed_url'] = $currentUrl;
// Run your SQL query here as it counts a genuine new view
mysqli_query("UPDATE ****");
} else {
// This is likely a refresh of the same page
// Do not run the update, or handle it differently
}
This approach uses the session to maintain state across HTTP requests. The logic assumes that if the user lands on action.php and immediately hits refresh, the URL in the session will match the current request URI, triggering the "refresh" branch.
Trade-offs and Pitfalls
While this session-based method is effective, it introduces a specific edge case: Incognito Mode or Session Timeout. If a user opens an incognito window, their browser does not retain cookies or session data between different tabs or after closing and reopening the browser. Consequently, every new tab in incognito will be treated as a "first visit," causing your query to run twice if they refresh within that session. This is generally acceptable behavior, but it's a limitation to keep in mind when designing your analytics logic.
Another consideration is Caching. If your server or a CDN caches the action.php page, a user might hit a cached copy without sending a new request to your PHP script. In this scenario, your code never runs regardless of whether they refreshed or not. This isn't a bug in your detection logic but a fundamental limitation of static caching strategies. You must ensure that pages intended for real-time tracking are either uncached or have appropriate cache-control headers set to no-store or short expiration times.
A Note on Laravel and Frameworks
If you are building this application using the Laravel framework, you might find the session handling more robust due to its built-in helpers. However, the underlying HTTP mechanism remains the same: PHP relies on stateless requests unless you introduce state via sessions or cookies. For high-volume applications where session overhead is a concern, you might consider storing this "viewed" flag in a Redis cache key instead of the database-backed session store. This reduces write latency and avoids locking issues during concurrent updates.
Ultimately, avoiding double-counting on refresh requires accepting that HTTP is stateless by default. You must artificially introduce stateâeither through sessions, cookies, or server-side storageâto track the difference between "new arrival" and "reload." There is no magic header like Content-Type: Refresh sent by modern browsers; you have to deduce intent from context, session history, or explicit JavaScript flags passed to your backend.