PHP记录搜索引擎蜘蛛爬行日志的实现方法
以下是实现该功能的完整代码示例:
//记录搜索引擎爬行记录 $searchbot = get_naps_bot();
if ($searchbot)
{ $tlc_thispage = addslashes($_SERVER['HTTP_USER_AGENT']);
$url = $_SERVER['HTTP_REFERER'];
$file = WEB_PATH.'robotslogs.txt';
$date = date('Y-m-d H:i:s');
$data = fopen($file,'a');
fwrite($data,"Time:$date robot:$searchbot URL:$tlc_thispage/r/n");
fclose($data);
}
其中WEB_PATH是在index.PHP中define定义的根目录路径,表明robotslogs.txt文件将保存在网站根目录下。
利用get_naps_bot()函数获取当前蜘蛛的爬行记录信息,随后使用addslashes进行转义处理,最终将数据存储到变量$tlc_thispage中。
使用fopen以追加模式打开robotslogs.txt文件,借助fwrite函数将数据写入,最后通过fclose关闭文件句柄即可完成操作。
由于作者认为展示效果并非必要,因此删除了原网站上的演示代码,故此处无法提供实际运行效果的截图或示例。
补充说明:这是用于PHP获取各主要搜索引擎蜘蛛爬行记录的代码片段。
该代码支持记录以下搜索引擎的爬行行为:Baidu、Google、Bing、Yahoo、Soso、Sogou以及Yodao。
具体代码如下所示:
<?php
/**
* 获取搜索引擎爬行记录
* edit by www.jb51.net
*/
function get_naps_bot()
{
$useragent = strtolower($_SERVER['HTTP_USER_AGENT']);
if (strpos($useragent, 'googlebot') !== false){
return 'Google';
}
if (strpos($useragent, 'baiduspider') !== false){
return 'Baidu';
}
if (strpos($useragent, 'msnbot') !== false){
return 'Bing';
}
if (strpos($useragent, 'slurp') !== false){
return 'Yahoo';
}
if (strpos($useragent, 'sosospider') !== false){
return 'Soso';
}
if (strpos($useragent, 'sogou spider') !== false){
return 'Sogou';
}
if (strpos($useragent, 'yodaobot') !== false){
return 'Yodao';
}
return false;
}
function nowtime(){
$date=date("Y-m-d.G:i:s");
return $date;
}
$searchbot = get_naps_bot();
if ($searchbot) {
$tlc_thispage = addslashes($_SERVER['HTTP_USER_AGENT']);
$url=$_SERVER['HTTP_REFERER'];
$file="www.jb51.net.txt";
$time=nowtime();
$data=fopen($file,"a");
fwrite($data,"Time:$time robot:$searchbot URL:$tlc_thispage\n");
fclose($data);
}
?>
总结
上文是小编分享的关于PHP记录搜索引擎爬行记录的方法,希望能对大家有所帮助。若有任何疑问欢迎留言,小编会及时回复。同时也非常感谢大家对本站的支持!