web-dev-qa-db-fra.com

comment détecter les robots des moteurs de recherche avec php?

Comment détecter les robots des moteurs de recherche en utilisant php?

113
terrific

Voici un Répertoire du moteur de recherche des noms d'araignées

Ensuite, vous utilisez $_SERVER['HTTP_USER_AGENT']; pour vérifier si l'agent est dit araignée.

if(strstr(strtolower($_SERVER['HTTP_USER_AGENT']), "googlebot"))
{
    // what to do
}
71
Ólafur Waage

J'utilise le code suivant qui semble fonctionner correctement:

function _bot_detected() {

  return (
    isset($_SERVER['HTTP_USER_AGENT'])
    && preg_match('/bot|crawl|Slurp|spider|mediapartners/i', $_SERVER['HTTP_USER_AGENT'])
  );
}

mise à jour 16-06-2017 https://support.google.com/webmasters/answer/1061943?hl=fr

ajouté mediapartners

221
minnur

Vérifier la $_SERVER['HTTP_USER_AGENT'] pour certaines des chaînes énumérées ici:

http://www.useragentstring.com/pages/useragentstring.php

Ou plus spécifiquement pour les chenilles:

http://www.useragentstring.com/pages/useragentstring.php?typ=Crawler

Si vous souhaitez enregistrer le nombre de visites des robots les plus courants dans les moteurs de recherche, vous pouvez utiliser:

$interestingCrawlers = array( 'google', 'yahoo' );
$pattern = '/(' . implode('|', $interestingCrawlers) .')/';
$matches = array();
$numMatches = preg_match($pattern, strtolower($_SERVER['HTTP_USER_AGENT']), $matches, 'i');
if($numMatches > 0) // Found a match
{
  // $matches[1] contains an array of all text matches to either 'google' or 'yahoo'
}
19
Jukka Dahlbom

Vous pouvez vérifier si c'est un moteur de recherche avec cette fonction:

<?php
function crawlerDetect($USER_AGENT)
{
$crawlers = array(
'Google' => 'Google',
'MSN' => 'msnbot',
      'Rambler' => 'Rambler',
      'Yahoo' => 'Yahoo',
      'AbachoBOT' => 'AbachoBOT',
      'accoona' => 'Accoona',
      'AcoiRobot' => 'AcoiRobot',
      'ASPSeek' => 'ASPSeek',
      'CrocCrawler' => 'CrocCrawler',
      'Dumbot' => 'Dumbot',
      'FAST-WebCrawler' => 'FAST-WebCrawler',
      'GeonaBot' => 'GeonaBot',
      'Gigabot' => 'Gigabot',
      'Lycos spider' => 'Lycos',
      'MSRBOT' => 'MSRBOT',
      'Altavista robot' => 'Scooter',
      'AltaVista robot' => 'Altavista',
      'ID-Search Bot' => 'IDBot',
      'eStyle Bot' => 'eStyle',
      'Scrubby robot' => 'Scrubby',
      'Facebook' => 'facebookexternalhit',
  );
  // to get crawlers string used in function uncomment it
  // it is better to save it in string than use implode every time
  // global $crawlers
   $crawlers_agents = implode('|',$crawlers);
  if (strpos($crawlers_agents, $USER_AGENT) === false)
      return false;
    else {
    return TRUE;
    }
}
?>

Ensuite, vous pouvez l'utiliser comme:

<?php $USER_AGENT = $_SERVER['HTTP_USER_AGENT'];
  if(crawlerDetect($USER_AGENT)) return "no need to lang redirection";?>
16
macherif

J'utilise ceci pour détecter les robots:

if (preg_match('/bot|crawl|curl|dataprovider|search|get|spider|find|Java|majesticsEO|google|yahoo|teoma|contaxe|yandex|libwww-Perl|facebookexternalhit/i', $_SERVER['HTTP_USER_AGENT'])) {
    // is bot
}

De plus, j'utilise une liste blanche pour bloquer les robots indésirables:

if (preg_match('/Apple|baidu|bingbot|facebookexternalhit|googlebot|-google|ia_archiver|msnbot|naverbot|pingdom|seznambot|Slurp|teoma|Twitter|yandex|yeti/i', $_SERVER['HTTP_USER_AGENT'])) {
    // allowed bot
}

Un bot indésirable (= utilisateur faussement positif) est alors capable de résoudre un captcha pour se débloquer pendant 24 heures. Et comme personne ne résout ce captcha, je sais que cela ne produit pas de faux positifs. Donc, la détection de bot semble fonctionner parfaitement.

Remarque: ma liste blanche est basée sur Facebooks robots.txt .

10
mgutt

J'utilise cette fonction ... une partie de la regex provient de prestashop mais j'y ai ajouté un peu plus de bot.

    public function isBot()
{
    $bot_regex = '/BotLink|bingbot|AhrefsBot|ahoy|AlkalineBOT|anthill|appie|arale|araneo|AraybOt|ariadne|arks|ATN_Worldwide|Atomz|bbot|Bjaaland|Ukonline|borg\-bot\/0\.9|boxseabot|bspider|calif|christcrawler|CMC\/0\.01|combine|confuzzledbot|CoolBot|cosmos|Internet Cruiser Robot|cusco|cyberspyder|cydralspider|desertrealm, desert realm|digger|DIIbot|grabber|downloadexpress|DragonBot|dwcp|ecollector|ebiness|elfinbot|esculapio|esther|fastcrawler|FDSE|FELIX IDE|ESI|fido|H�m�h�kki|KIT\-Fireball|fouineur|Freecrawl|gammaSpider|gazz|gcreep|golem|googlebot|griffon|Gromit|gulliver|gulper|hambot|havIndex|hotwired|htdig|iajabot|INGRID\/0\.1|Informant|InfoSpiders|inspectorwww|irobot|Iron33|JBot|jcrawler|Teoma|Jeeves|jobo|image\.kapsi\.net|KDD\-Explorer|ko_yappo_robot|label\-grabber|larbin|legs|Linkidator|linkwalker|Lockon|logo_gif_crawler|marvin|mattie|mediafox|MerzScope|NEC\-MeshExplorer|MindCrawler|udmsearch|moget|Motor|msnbot|muncher|muninn|MuscatFerret|MwdSearch|sharp\-info\-agent|WebMechanic|NetScoop|newscan\-online|ObjectsSearch|Occam|Orbsearch\/1\.0|Packrat|pageboy|ParaSite|patric|pegasus|perlcrawler|phpdig|piltdownman|Pimptrain|pjspider|PlumtreeWebAccessor|PortalBSpider|psbot|Getterrobo\-Plus|Raven|RHCS|RixBot|roadrunner|Robbie|robi|RoboCrawl|robofox|Scooter|Search\-AU|searchprocess|Senrigan|Shagseeker|sift|SimBot|Site Valet|skymob|SLCrawler\/2\.0|Slurp|ESI|snooper|solbot|speedy|spider_monkey|SpiderBot\/1\.0|spiderline|nil|suke|http:\/\/www\.sygol\.com|tach_bw|TechBOT|templeton|titin|topiclink|UdmSearch|urlck|Valkyrie libwww\-Perl|verticrawl|Victoria|void\-bot|Voyager|VWbot_K|crawlpaper|wapspider|WebBandit\/1\.0|webcatcher|T\-H\-U\-N\-D\-E\-R\-S\-T\-O\-N\-E|WebMoose|webquest|webreaper|webs|webspider|WebWalker|wget|winona|whowhere|wlm|WOLP|WWWC|none|XGET|Nederland\.zoek|AISearchBot|woriobot|NetSeer|Nutch|YandexBot|YandexMobileBot|SemrushBot|FatBot|MJ12bot|DotBot|AddThis|baiduspider|SeznamBot|mod_pagespeed|CCBot|openstat.ru\/Bot|m2e/i';
    $userAgent = empty($_SERVER['HTTP_USER_AGENT']) ? FALSE : $_SERVER['HTTP_USER_AGENT'];
    $isBot = !$userAgent || preg_match($bot_regex, $userAgent);

    return $isBot;
}

Quoi qu'il en soit, veillez à ce que certains robots utilisent un navigateur comme un agent utilisateur pour simuler leur identité.
(J'ai beaucoup d'IP russe qui a ce comportement sur mon site)

Une caractéristique distinctive de la plupart des robots est qu’ils ne portent aucun cookie et qu’aucune session ne leur est donc associée.
(Je ne sais pas comment mais c’est la meilleure façon de les suivre)

9
WonderLand

Parce que tout client peut configurer l’agent utilisateur comme il le souhaite, rechercher "Googlebot", "bingbot", etc. ne représente que la moitié du travail.

La deuxième partie vérifie l'adresse IP du client. Auparavant, cela nécessitait de maintenir des listes IP. Toutes les listes que vous trouvez en ligne sont obsolètes. Les principaux moteurs de recherche prennent officiellement en charge la vérification via DNS, comme expliqué par Google https://support.google.com/webmasters/answer/80553 et Bing http://www.bing.com/webmaster/help/how-to-verify-bingbot-3905dc26

Tout d’abord, effectuez une recherche DNS inversée de l’IP du client. Pour Google, cela amène un nom d'hôte sous googlebot.com, pour Bing, il se trouve sous search.msn.com. Ensuite, comme une personne peut définir un tel DNS inversé sur son IP, vous devez vérifier avec une recherche DNS directe sur ce nom d’hôte. Si l'adresse IP obtenue est la même que celle du visiteur du site, vous êtes certain qu'il s'agit d'un robot d'exploration issu de ce moteur de recherche.

J'ai écrit une bibliothèque dans Java qui effectue ces vérifications pour vous. N'hésitez pas à la porter sur PHP. Elle se trouve sur GitHub: https: // github .com/optimaize/webcrawler-verifier

8
Fabian Kessler

Vous pouvez analyser l'agent utilisateur ($_SERVER['HTTP_USER_AGENT']) ou comparez l’adresse IP du client ($_SERVER['REMOTE_ADDR']) avec un liste des adresses IP des robots des moteurs de recherche .

6
Gumbo

Utilisez la bibliothèque open source Device Detector, elle offre une fonction isBot (): https://github.com/piwik/device-detector

5
mattab
 <?php // IPCLOACK HOOK
if (CLOAKING_LEVEL != 4) {
    $lastupdated = date("Ymd", filemtime(FILE_BOTS));
    if ($lastupdated != date("Ymd")) {
        $lists = array(
        'http://labs.getyacg.com/spiders/google.txt',
        'http://labs.getyacg.com/spiders/inktomi.txt',
        'http://labs.getyacg.com/spiders/lycos.txt',
        'http://labs.getyacg.com/spiders/msn.txt',
        'http://labs.getyacg.com/spiders/altavista.txt',
        'http://labs.getyacg.com/spiders/askjeeves.txt',
        'http://labs.getyacg.com/spiders/wisenut.txt',
        );
        foreach($lists as $list) {
            $opt .= fetch($list);
        }
        $opt = preg_replace("/(^[\r\n]*|[\r\n]+)[\s\t]*[\r\n]+/", "\n", $opt);
        $fp =  fopen(FILE_BOTS,"w");
        fwrite($fp,$opt);
        fclose($fp);
    }
    $ip = isset($_SERVER['REMOTE_ADDR']) ? $_SERVER['REMOTE_ADDR'] : '';
    $ref = isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : '';
    $agent = isset($_SERVER['HTTP_USER_AGENT']) ? $_SERVER['HTTP_USER_AGENT'] : '';
    $Host = strtolower(gethostbyaddr($ip));
    $file = implode(" ", file(FILE_BOTS));
    $exp = explode(".", $ip);
    $class = $exp[0].'.'.$exp[1].'.'.$exp[2].'.';
    $threshold = CLOAKING_LEVEL;
    $cloak = 0;
    if (stristr($Host, "googlebot") && stristr($Host, "inktomi") && stristr($Host, "msn")) {
        $cloak++;
    }
    if (stristr($file, $class)) {
        $cloak++;
    }
    if (stristr($file, $agent)) {
        $cloak++;
    }
    if (strlen($ref) > 0) {
        $cloak = 0;
    }

    if ($cloak >= $threshold) {
        $cloakdirective = 1;
    } else {
        $cloakdirective = 0;
    }
}
?>

Ce serait le moyen idéal de camoufler les araignées. Cela provient d'un script open source appelé [YACG] - http://getyacg.com

Besoin d'un peu de travail, mais certainement la voie à suivre.

4
L. Cosio

J'utilise ce code, très bien. Vous aurez très facilement connaissance des agents utilisateurs visités sur votre site. Ce code ouvre un fichier et écrit le user_agent dans le fichier. Vous pouvez vérifier chaque jour ce fichier en allant à yourdomain.com/useragent.txt et connaître les nouveaux user_agents et les mettre dans votre condition de clause if.

$user_agent = strtolower($_SERVER['HTTP_USER_AGENT']);
if(!preg_match("/Googlebot|MJ12bot|yandexbot/i", $user_agent)){
    // if not meet the conditions then
    // do what you need

    // here open a file and write the user_agent down the file. You can check each day this file useragent.txt and know about new user_agents and put them in your condition of if clause
    if($user_agent!=""){
        $myfile = fopen("useragent.txt", "a") or die("Unable to open file useragent.txt!");
        fwrite($myfile, $user_agent);
        $user_agent = "\n";
        fwrite($myfile, $user_agent);
        fclose($myfile);
    }
}

Ceci est le contenu de useragent.txt

Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)
Mozilla/5.0 (compatible; MJ12bot/v1.4.6; http://mj12bot.com/)Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)
Mozilla/5.0 (Linux; Android 6.0.1; Nexus 5X Build/MMB29P) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2272.96 Mobile Safari/537.36 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)mozilla/5.0 (compatible; yandexbot/3.0; +http://yandex.com/bots)
mozilla/5.0 (compatible; yandexbot/3.0; +http://yandex.com/bots)
mozilla/5.0 (compatible; yandexbot/3.0; +http://yandex.com/bots)
mozilla/5.0 (compatible; yandexbot/3.0; +http://yandex.com/bots)
mozilla/5.0 (compatible; yandexbot/3.0; +http://yandex.com/bots)
mozilla/5.0 (iphone; cpu iphone os 9_3 like mac os x) applewebkit/601.1.46 (khtml, like gecko) version/9.0 mobile/13e198 safari/601.1
mozilla/5.0 (windows nt 6.1; wow64) applewebkit/537.36 (khtml, like gecko) chrome/53.0.2785.143 safari/537.36
mozilla/5.0 (compatible; linkdexbot/2.2; +http://www.linkdex.com/bots/)
mozilla/5.0 (windows nt 6.1; wow64; rv:49.0) gecko/20100101 firefox/49.0
mozilla/5.0 (windows nt 6.1; wow64; rv:33.0) gecko/20100101 firefox/33.0
mozilla/5.0 (windows nt 6.1; wow64; rv:49.0) gecko/20100101 firefox/49.0
mozilla/5.0 (windows nt 6.1; wow64; rv:33.0) gecko/20100101 firefox/33.0
mozilla/5.0 (windows nt 6.1; wow64; rv:49.0) gecko/20100101 firefox/49.0
mozilla/5.0 (windows nt 6.1; wow64; rv:33.0) gecko/20100101 firefox/33.0
mozilla/5.0 (windows nt 6.1; wow64; rv:49.0) gecko/20100101 firefox/49.0
mozilla/5.0 (windows nt 6.1; wow64; rv:33.0) gecko/20100101 firefox/33.0
mozilla/5.0 (windows nt 6.1; wow64) applewebkit/537.36 (khtml, like gecko) chrome/53.0.2785.143 safari/537.36
mozilla/5.0 (windows nt 6.1; wow64) applewebkit/537.36 (khtml, like gecko) chrome/53.0.2785.143 safari/537.36
mozilla/5.0 (compatible; baiduspider/2.0; +http://www.baidu.com/search/spider.html)
zoombot (linkbot 1.0 http://suite.seozoom.it/bot.html)
mozilla/5.0 (windows nt 10.0; wow64) applewebkit/537.36 (khtml, like gecko) chrome/44.0.2403.155 safari/537.36 opr/31.0.1889.174
mozilla/5.0 (windows nt 10.0; wow64) applewebkit/537.36 (khtml, like gecko) chrome/44.0.2403.155 safari/537.36 opr/31.0.1889.174
sogou web spider/4.0(+http://www.sogou.com/docs/help/webmasters.htm#07)
mozilla/5.0 (windows nt 10.0; wow64) applewebkit/537.36 (khtml, like gecko) chrome/44.0.2403.155 safari/537.36 opr/31.0.1889.174
1
Lighthouse Nguyen
function bot_detected() {

  if(preg_match('/bot|crawl|Slurp|spider|mediapartners/i', $_SERVER['HTTP_USER_AGENT']){
    return true;
  }
  else{
    return false;
  }
}
0
Elyor