仅向Facebook,Twitter访客展示Google AdSense广告

时间:2016-07-11 17:26:19

标签: php preg-match adsense http-referer

我正在使用下面的代码。当我将此代码放入single.php时,它会显示带有内容的广告。我想,当Facebook访问者访问我的网址时,它只显示 广告,而不显示任何内容。当其他访问者通常访问该网址时,它应该显示内容。

<?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 "";
    }

?>

如果single.php错误的地方,我应该把它放在哪里?

1 个答案:

答案 0 :(得分:0)

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 "";
    }

?>