Home >php教程 >php手册 >用php实现让页面只能被百度gogole蜘蛛访问的方法

用php实现让页面只能被百度gogole蜘蛛访问的方法

WBOY
WBOYOriginal
2016-06-13 12:19:46862browse

普通用户与搜索引擎蜘蛛爬行的区别在于发送的user agent,
看网站日志文件能发现百度蜘蛛名字包含Baiduspider, 而google的则是Googlebot, 这样我们可以通过判断发送的user agent来决定要不要取消普通用户的访问,编写函数如下:

复制代码 代码如下:


function isAllowAccess($directForbidden = FALSE) {
$allowed = array('/baiduspider/i', '/googlebot/i');
$user_agent = $_SERVER['HTTP_USER_AGENT'];
$valid = FALSE;
foreach ($allowed as $pattern) {
if (preg_match($pattern, $user_agent)) {
$valid = TRUE;
break;
}
}
if (!$valid && $directForbidden) {
exit("404 not found");
}
 
return $valid;
}


在要禁止访问的页面头部引用这个函数来做判断就ok了,如下俩中调用方式:

复制代码 代码如下:


if (!isAllowAccess()) {
exit("404 not found");
}
//或者
isAllowAccess(TRUE);

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn