2012-10-02 10 views
2

我要顯示谷歌AdSense廣告僅搜索引擎的流量,並沒有廣告經常訪問者直接或Facebook,微博,電子郵件中的鏈接,等等如何僅將Google AdSense廣告展示給搜索引擎流量?

這是我目前使用的代碼,它似乎工作不錯,但我想也提高了代碼,包括除了許多其他搜索引擎谷歌,如兵,雅虎,ASK等會有人介意看一下下面的代碼,並與改進修正呢?

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

回答

3

該代碼看起來相當不錯。我的建議是使用/,而不是作爲(模式定界符括號也可以用於匹配組。您還可以添加i標誌以使匹配不區分大小寫。不需要其他語句,因爲它只是輸出和空字符串。還有一個在你的END HEREDOC額外</div>標籤 - 你要確保,無論是打開和關閉或者是內部或if語句之外。

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

下面的正則表達式的結果,匹配標有*

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 
+0

哇感謝!聽到我編寫了一些「相當不錯」的東西,真是太酷了,太棒了。非常感謝您修改代碼並給我一個很好的解釋。我真的非常欣賞這一點。 if語句是向常規觀衆顯示其他內容。我想我可以設法加回來。再次感謝doublesharp。 – Garry

+0

嘿@doublesharp我收到此錯誤: 我收到此錯誤信息: '解析錯誤:語法錯誤,意想不到的$結束,預計T_VARIABLE或/var/www/xxxxx.com/public_html T_END_HEREDOC或T_DOLLAR_OPEN_CURLY_BRACES或T_CURLY_OPEN /xxx-xxx-xx.php固定它行18' – Garry

+0

...的'END'不能縮進。發現這裏的解決方案:http://www.codingforums.com/showpost.php?s=f1da607bd751dc4213191c3d82624a4d&p=1253001&postcount=2 – Garry

相關問題