用PHP的fopen函数读写robots.txt文件

用PHP的fopen函数读写robots.txt文件

  以前介绍了用PHP读写文本文档制作最简单的访问计数器不需要数据库,仅仅用文本文档就可以实现网页访问计数功能。同样我们可以拓展一下这个思路,robots.txt文件对于我们网站来说非常重要,有时候我们需要修改robots.txt文件来屏蔽或者引导蜘蛛如何访问我们的网站。  读写robots文件的代码如下:

   

<?php
function get_txt($robots_file)
//定义函数,内容用{}括起来
{
if(file_exists($robots_file))
//如果文件存在,读取其中的内容
{
$fp=@fopen($robots_file,"r");
//r是read的缩写,代表读取的意思,以只读方式打开文件
if ($fp) {
while (!feof($fp)) { //如果没有到文件尾部
 $robots_txt = fgets($fp, 4096); //逐行读取
 $robots_all = $robots_all.$robots_txt; //将数据保存到$robots_all里面
}
return($robots_all); //返回所有内容
fclose($fp); //关闭文件
}
}
}
  
function put_txt($robots_txt)
{
$fp=fopen("robots.txt","w");
//w是write的缩写,代表写入的意思,以写入的方式打开文件
fputs($fp,$robots_txt);
//输出文本到文件
fclose($fp);
}
?>
  
<?php
$edit=$_GET["edit"];
$txt=$_POST["txt"];
$get_txt=get_txt("robots.txt");
 //调用刚才定义的函数打开robots文件。
  
if($edit=="write")
{
put_txt($txt);
echo "成功保存 <a href=robots-editer.php>返回</a>";
}
else
{
echo "成功读取<a href=robots.txt target=_blank>robots.txt</a> <a href=writer.php>返回</a>";
}
?>
  
<?php
if($edit=="")
{
?>
<form name="form1" action="?edit=write" method="post">
<textarea name="txt" cols="160" rows="30"><?php echo $get_txt; ?></textarea>
<br />
<input name="submit" value="保存" type="submit" />
</form>
<?php
}
?>