Skip to content

Blocking AdSense ads on your own site

One of the fears of AdSense users is that they will accidentally click on an ad on their own site and get banned by Google. I’ve always assumed that these fears are a little over-hyped. I just can’t see one accidental click causing you to get dropped. Of course you certainly don’t want to make a habit out of “accidental” clicks.

But there is another reason to not have AdSense ads shown to you on your own sites. By having them visible you can really skew your stats. So what can you do?

I’ve read several options, most center around editing your HOSTS file to keep the ads from showing. But I don’t like that. So what I did is use a little PHP to decide whether to show ads based on the user-agent string.

First, I added my initials to my user-agent string. In FireFox this is pretty easy. Type about:config into the address bar. Look for general.useragent.vendor. If it’s already there just add your initials to the string. If it’s not there add it.

Now, in place of the AdSense javascript code use the following PHP code. Note that the AdSense code itself is not changed, it’s just that the server now decides whether to output the javascript.

$output = '';
if (!strstr($_SERVER['HTTP_USER_AGENT'], 'Your Initials'))
{
$output .= 'Your AdSense Code';
}
else
{
$output .= 'No ads';
}

echo $output;

You’ll need to replace Your Initials in line 2 with your actual initials. Actually any string will work as long as it matches what you entered in About:Config. You’ll also need to paste the code from the AdSense site into line 4 replacing Your AdSense Code.

It’s also possible to use the same logic to block based on IP address. Just replace

if (!strstr($_SERVER['HTTP_USER_AGENT'], 'Your Initials'))

with

if ($_SERVER['REMOTE_ADDR']=='123.123.123.123')

replacing 123.123.123.123 with your actual IP address. I didn’t go with this method because I’m on cable modem and my IP address changes periodically.

Published inInternetProgramming

One Comment

  1. […] A few months ago I wrote about a technique I use so that Adsense ads aren’t shown to me when I’m viewing my sites. Recently I started doing the same with Google Analytics code so that I don’t show up in my stats. […]

Leave a Reply

Your email address will not be published. Required fields are marked *