How to know if the visitor is the Google bot, or Facebook bot

Asked

Viewed 278 times

0

Have some way, via PHP, to know if who is visiting my page is Google bot and Facebook bot?

1 answer

1

Google

if (strstr(strtolower($_SERVER['HTTP_USER_AGENT']), "googlebot")) {
    // Provavelmente proveio do google.
    // Aqui você implementa as suas firulas.
}

Facebook:

if (
    strpos($_SERVER["HTTP_USER_AGENT"], "facebookexternalhit/") !== false ||          
    strpos($_SERVER["HTTP_USER_AGENT"], "Facebot") !== false
) {
    // Provavelmente proveio do facebook.
    // Aqui você implementa as suas firulas.
}

Note: Be aware that it is easy to manipulate HTTP_USER_AGENT. Anyone can create a script that identifies itself as googlebot, for example. So do not trust this parameter 100%.

To ensure greater integrity you will need to do reverse DNS checks, IP origin, etc.

  • +1, but a small remark: in both cases I would use the stripos, which is case-insensitive. Moreover, strstr is less efficient, the PHP manual itself recommends using strpos if it’s just to see if the string is contained.

  • If it is for simple count of visits, use google Analytics. It filters and lists only valid visits.

  • @Andrecardoso has more information on how to use the same?

  • @Luizach, it’s very simple. Just register in Google Analytics, add a new website (inform the necessary data as type of site and everything else), confirm membership (terms of use) and Google will generate a code to be added to the site, it is very simple, the code comes ready, just add to the bottom of the page. Then just follow the access by the panel: http://www.andrebian.com/wp-content/uploads/2016/03/Screenshot-from-2016-03-15-223530.png

Browser other questions tagged

You are not signed in. Login or sign up in order to post.