如何使用PHP检测爬虫/蜘蛛?

ftf50wuq  于 2023-01-04  发布在  PHP
关注(0)|答案(3)|浏览(312)

如何使用PHP检测爬虫/蜘蛛?

我目前正在做一个项目,我需要跟踪每个爬虫的访问。
我知道您应该使用HTTP_USER_AGENT,但我不确定如何为此目的格式化代码,而且我知道用户代理可以很容易地更改,因此我还想知道是否可以添加更多参数以避免欺骗?
我正在尝试做的示例代码。

<?php
$user_agent = $_SERVER['HTTP_USER_AGENT'];
if (strpos( $user_agent, 'Google') !== false)
{
echo "Googlebot is here";
}
?>

谢谢

4xy9mtcn

4xy9mtcn1#

根据Verifying Googlebot
You can verify that a bot accessing your server really is Googlebot (or another Google user-agent) by using a reverse DNS lookup, verifying that the name is in the googlebot.com domain, and then doing a forward DNS lookup using that googlebot name. This is useful if you're concerned that spammers or other troublemakers are accessing your site while claiming to be Googlebot.
例如:
第一个月
1.66.249.66.in-addr.arpa domain name pointer
一米二米一米三米一
crawl-66-249-66-1.googlebot.com has address 66.249.66.1
Google不会将网站管理员的IP地址公开发布到白名单中。这是因为这些IP地址范围可能会改变,从而给硬编码的网站管理员带来问题。识别Googlebot访问的最佳方法是使用用户代理(Googlebot)。
您可以执行反向DNS查找:

function validateGoogleBotIP($ip) {
    $hostname = gethostbyaddr($ip); //"crawl-66-249-66-1.googlebot.com"

    return preg_match('/\.google(bot)?\.com$/i', $hostname);
}

if (strpos($_SERVER['HTTP_USER_AGENT'], 'Google') !== false) {
    if (validateGoogleBotIP($_SERVER['REMOTE_ADDR'])) {
        echo 'It is ACTUALLY google';
    } else {
        echo 'Someone\'s faking it!';
    }
} else {
    echo 'Nothing to do with Google';
}
de90aj5v

de90aj5v2#

100%在我的网站上工作检测机器人,爬虫,蜘蛛和复印机。

function isBotDetected() {

    if ( !empty($_SERVER['HTTP_USER_AGENT']) and preg_match('/abacho|accona|AddThis|AdsBot|ahoy|AhrefsBot|AISearchBot|alexa|altavista|anthill|appie|applebot|arale|araneo|AraybOt|ariadne|arks|aspseek|ATN_Worldwide|Atomz|baiduspider|baidu|bbot|bingbot|bing|Bjaaland|BlackWidow|BotLink|bot|boxseabot|bspider|calif|CCBot|ChinaClaw|christcrawler|CMC\/0\.01|combine|confuzzledbot|contaxe|CoolBot|cosmos|crawler|crawlpaper|crawl|curl|cusco|cyberspyder|cydralspider|dataprovider|digger|DIIbot|DotBot|downloadexpress|DragonBot|DuckDuckBot|dwcp|EasouSpider|ebiness|ecollector|elfinbot|esculapio|ESI|esther|eStyle|Ezooms|facebookexternalhit|facebook|facebot|fastcrawler|FatBot|FDSE|FELIX IDE|fetch|fido|find|Firefly|fouineur|Freecrawl|froogle|gammaSpider|gazz|gcreep|geona|Getterrobo-Plus|get|girafabot|golem|googlebot|\-google|grabber|GrabNet|griffon|Gromit|gulliver|gulper|hambot|havIndex|hotwired|htdig|HTTrack|ia_archiver|iajabot|IDBot|Informant|InfoSeek|InfoSpiders|INGRID\/0\.1|inktomi|inspectorwww|Internet Cruiser Robot|irobot|Iron33|JBot|jcrawler|Jeeves|jobo|KDD\-Explorer|KIT\-Fireball|ko_yappo_robot|label\-grabber|larbin|legs|libwww-perl|linkedin|Linkidator|linkwalker|Lockon|logo_gif_crawler|Lycos|m2e|majesticsEO|marvin|mattie|mediafox|mediapartners|MerzScope|MindCrawler|MJ12bot|mod_pagespeed|moget|Motor|msnbot|muncher|muninn|MuscatFerret|MwdSearch|NationalDirectory|naverbot|NEC\-MeshExplorer|NetcraftSurveyAgent|NetScoop|NetSeer|newscan\-online|nil|none|Nutch|ObjectsSearch|Occam|openstat.ru\/Bot|packrat|pageboy|ParaSite|patric|pegasus|perlcrawler|phpdig|piltdownman|Pimptrain|pingdom|pinterest|pjspider|PlumtreeWebAccessor|PortalBSpider|psbot|rambler|Raven|RHCS|RixBot|roadrunner|Robbie|robi|RoboCrawl|robofox|Scooter|Scrubby|Search\-AU|searchprocess|search|SemrushBot|Senrigan|seznambot|Shagseeker|sharp\-info\-agent|sift|SimBot|Site Valet|SiteSucker|skymob|SLCrawler\/2\.0|slurp|snooper|solbot|speedy|spider_monkey|SpiderBot\/1\.0|spiderline|spider|suke|tach_bw|TechBOT|TechnoratiSnoop|templeton|teoma|titin|topiclink|twitterbot|twitter|UdmSearch|Ukonline|UnwindFetchor|URL_Spider_SQL|urlck|urlresolver|Valkyrie libwww\-perl|verticrawl|Victoria|void\-bot|Voyager|VWbot_K|wapspider|WebBandit\/1\.0|webcatcher|WebCopier|WebFindBot|WebLeacher|WebMechanic|WebMoose|webquest|webreaper|webspider|webs|WebWalker|WebZip|wget|whowhere|winona|wlm|WOLP|woriobot|WWWC|XGET|xing|yahoo|YandexBot|YandexMobileBot|yandex|yeti|Zeus/i', $_SERVER['HTTP_USER_AGENT'])
    ) {
        return true; // 'Above given bots detected'
    }

    return false;

} // End :: isBotDetected()
gopyfrb3

gopyfrb33#

要正确验证访问者是否来自搜索引擎,您需要的不仅仅是检查用户代理,因为它很容易被欺骗。
正确的方法是查找IP的主机名,并快速检查它是否与我们知道的搜索引擎爬虫使用的任何主机名匹配。
如果主机名与某个已知的爬虫匹配,那么你就查找该主机名的IP地址,看看两者是否匹配。如果其中一个步骤失败,那么你有一个假冒的搜索引擎爬虫正在访问。
下面的函数接受一个IP,并遵循前面提到的步骤。它识别百度,必应,谷歌,雅虎和Yandex。

/**
 * Validate a crawlers IP against the hostname 
 * Warning - str_ends_with() requires PHP 8
 *
 * @param   mixed   $ip 
 * @return  boolean
 */
function validate_crawler_ip( $testip ) {
   $hostname = strtolower( gethostbyaddr( $testip ) );
   $valid_host_names = array(
      '.crawl.baidu.com',
      '.crawl.baidu.jp',
      '.google.com',
      '.googlebot.com',
      '.crawl.yahoo.net',
      '.yandex.ru',
      '.yandex.net',
      '.yandex.com',
      '.search.msn.com',
   );
   $valid_ip = false;
   foreach ( $valid_host_names as $valid_host ) {
     // Using string_ends_with() to make sure the match is in the -end- of the hostname (to prevent fake matches)
     if ( str_ends_with( $hostname, $valid_host ) ) { // PHP 8 function
      $returned_ip = gethostbyname( $hostname );        
      if ( $returned_ip === $testip ) {
        // The looked up IP from the host matches the incoming IP - we have validated!
        return true;
      }
    }
  }
  // No match - not valid crawler
  return false;
}

相关问题