Search code examples
phppreg-matchadsensehttp-referer

How to display Google AdSense ads to search engine traffic only?


I want to display Google AdSense ads to search engine traffic only and NO ads to regular visitors coming in directly or from Facebook, Twitter, email link, etc...

Here's the code I currently use and it seems to work okay, but I want to also improve the code to include many other search engines in addition to Google such as Bing, Yahoo, Ask, etc.. Would someone mind looking at the code below and revise it with improvements?

<?php
$ref = $_SERVER['HTTP_REFERER'];
if (preg_match("(google|yahoo|bing)", $ref) != false) {
echo <<<END
<script type="text/javascript"><!--
google_ad_client = "xx-xx-xxxxxxxxxxxxxxxxxx";
/* xxxxxxxx xxxxxx xxx xxx xxx xx xxxxxx */
google_ad_slot = "xxxxxxxxxxxxxx";
google_ad_width = xxx;
google_ad_height = xxx;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script>
</div>
END;
}
else {
     echo ""
;
}
?>

Solution

  • The code looks fairly good. My suggestions would be to use / rather than ( as the pattern delimiter as parens can also be used for match groups. You can also add the i flag to make your matches case insensitive. There is no need for your else statement, as it just outputs and empty string. There is also an extra </div> tag in your END HEREDOC - you want to make sure that both the open and close are either inside or outside your if statement.

    <?php
    $referrer = $_SERVER['HTTP_REFERER'];
    $my_domain = "example.com";
    $search_engines = "google|yahoo|bing|altavista|digg";
    $pattern = "((http(s)?:\/\/)(\w+?\.)?(?!{$my_domain})({$search_engines}))";
    if (preg_match("/{$pattern}/i", $referrer) != false) {
        echo <<<END
        <script type="text/javascript"><!--
        google_ad_client = "xx-xx-xxxxxxxxxxxxxxxxxx";
        /* xxxxxxxx xxxxxx xxx xxx xxx xx xxxxxx */
        google_ad_slot = "xxxxxxxxxxxxxx";
        google_ad_width = xxx;
        google_ad_height = xxx;
        //-->
        </script>
        <script type="text/javascript" src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
        </script>
    END;
    } else {
        // Show something to visitors not referred by a search engine
    }
    ?>
    

    The regex pattern results in the following, matches marked with *:

    FALSE - http://example.com/google
    FALSE - http://example.com/google.com
    FALSE - http://www.example.com/google.com
    TRUE  - *http://google*.com/example.com
    TRUE  - *http://www1.google*.com/example.com
    TRUE  - *http://www.google*.com/example.com
    TRUE  - *http://images.google*.com/page
    TRUE  - *https://google*.com/example.com
    TRUE  - *https://www.google*.com/example.com