有朋友问到如何使用PHP去判断是否是搜索引擎,其实PHP有个很简单的方式去实现,通过_SERVER这个预定义变量中的_SERVER[\'HTTP_USER_AGENT\']可以取得访问者的属性,具体可以看下Diiscuz!是如何判断搜索引擎的,函数代码如下:
function getrobot() {
if(!defined(‘IS_ROBOT’)) {
kw_spiders = ‘Bot|Crawl|Spider|slurp|sohu-search|lycos|robozilla’;
kw_browsers = ‘MSIE|Netscape|Opera|Konqueror|Mozilla’;
if(preg_match(“/(kw_browsers)/”, _SERVER[\'HTTP_USER_AGENT\'])) {
define(‘IS_ROBOT’, FALSE);
} elseif(preg_match(“/(kw_spiders)/”, _SERVER[\'HTTP_USER_AGENT\'])) {
define(‘IS_ROBOT’, TRUE);
} else {
define(‘IS_ROBOT’, FALSE);
}
}
return IS_ROBOT;
}
\n
根据上面还可以精简如下:
if(preg_match(“/(Bot|Crawl|Spider|slurp|sohu-search|lycos|robozilla)/i”, _SERVER[\'HTTP_USER_AGENT\'])) {
echo ‘robot’;
}
\n
如果你需要返回详细的搜索引擎名称,而不是是否是搜索引擎机器人的话,请看下面的代码:
function get_naps_bot() {
useragent = strtolower(_SERVER[\'HTTP_USER_AGENT\']);
\n
if (strpos(useragent, ‘googlebot’) !== false){
return ‘Googlebot’;
}
\n
if (strpos(useragent, ‘msnbot’) !== false){
return ‘MSNbot’;
}
\n
if (strpos(useragent, ‘slurp’) !== false){
return ‘Yahoobot’;
}
\n
if (strpos(useragent, ‘baiduspider’) !== false){
return ‘Baiduspider’;
}
\n
if (strpos(useragent, ‘sohu-search’) !== false){
return ‘Sohubot’;
}
\n
if (strpos(useragent, ‘lycos’) !== false){
return ‘Lycos’;
}
\n
if (strpos(useragent, ‘robozilla’) !== false){
return ‘Robozilla’;
}
return false;
}
\n
这段代码返回了详细的搜索引擎机器人的名称,呵呵大家看那种好用就用哪种吧!
\n