PHP for detecting adblock on client side
PHP Code to Detect Adblock on Client Side
<?php
// Detect if adblock is enabled
$adblockDetected = false;
$requestHeaders = getallheaders();
if (isset($requestHeaders['Sec-Fetch-Dest']) && $requestHeaders['Sec-Fetch-Dest'] == 'empty') {
$adblockDetected = true;
}
// Handle adblock detection results
if ($adblockDetected) {
// Display message to user or take appropriate action (e.g., show alternative content)
echo "Adblock detected! Please disable it to support our website.";
} else {
// User has not enabled adblock, continue as normal
echo "No adblock detected.";
}
?>
Explanation:
This PHP code detects adblock on the client side by analyzing the request headers. Many adblockers use a technique called "empty.gif blocking" to prevent certain requests from being sent to ad servers. This involves setting the Sec-Fetch-Dest
request header to empty
for requests that are believed to be ads.
By checking if the Sec-Fetch-Dest
header is set to empty
and the request is not for an image, this code can reliably detect if an adblocker is enabled on the client.
Implementation:
To use this code, you can include it as a script in your PHP pages or add it to a shared library file. The code should be placed before any content that you want to display conditionally based on whether adblock is enabled.
If adblock is detected, you can display a message or take other appropriate actions, such as:
- Displaying alternative content (e.g., a donation request or a reminder to disable adblock)
- Redirecting users to a different page or asking them to refresh the page with adblock disabled
- Reducing the frequency of ad requests or disabling them altogether
Considerations:
- This technique is not foolproof and can be bypassed by advanced adblockers or custom adblock filters.
- Some legitimate users may also use adblockers for privacy or security reasons. Consider balancing the desire to display ads with the user’s experience and privacy concerns.
- It’s important to respect user’s adblock preferences and avoid being overly aggressive in trying to bypass them.