Tisha Tisha - 3 years ago 89
PHP Question

Displaying Google AdSense Advertisements only to Facebook, Twitter Visitors

I am using below code. When I place this code in

single.php
, it's showing ads with content. I want, when a Facebook visitor visits my URL, that it shows only ads and no content. When others visitors normally visit the URL, then it should show the content.

<?php

$ref = $_SERVER['HTTP_REFERER'];
if (preg_match("(facebook)", $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 "";
}

?>


If
single.php
is the wrong place, where should I placed it instead?

Answer Source

Please give this a try:

<?php

    $ref = $_SERVER['HTTP_REFERER'];
    if (preg_match('facebook\.com', $ref) != false) {

?>
<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>
<?php

    } else {
        echo "";
    }

?>

Another way you can check the referral is to use strpos instead of preg_match.

<?php

    $ref = $_SERVER['HTTP_REFERER'];
    if (strpos($ref, 'facebook.com') != false) {

?>
<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>
<?php

    } else {
        echo "";
    }

?>
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download