下面我们利用几个实例来总结了利用php fopen函数来实现文件的读写操作,有需要学习的朋友可参考参考.
简单的参考fopen函数fopen() 函数打开文件或者 URL.
如果打开失败,本函数返回 FALSE.
语法
fopen(filename,mode,include_path,context)
创建一个文件的实例代码如下:
- <?php
- if(!file_exists("test.txt")){
- $fh = fopen("test.txt","w");
- fclose($fh);
- }
- ?>
利用php的读写文本文档的功能来实现修改和编辑robots文件实例代码如下:
- <?php
- function get_txt($robots_file)
-
- {
- if(file_exists($robots_file))
-
- {
- $fp=@fopen($robots_file,"r");
-
- if ($fp) {
- while (!feof($fp)) {
- $robots_txt = fgets($fp, 4096);
- $robots_all = $robots_all.$robots_txt;
- }
- return($robots_all);
- fclose($fp);
- }
- }
- }
-
- function put_txt($robots_txt)
- {
- $fp=fopen("robots.txt","w");
-
- fputs($fp,$robots_txt);
-
- fclose($fp);
- }
- ?>
-
- <?php
- $edit=$_GET["edit"];
- $txt=$_POST["txt"];
- $get_txt=get_txt("robots.txt");
-
-
- 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
- }
- ?>
通过PHP读取文本文档counter.txt里的数据,并+1保存到文本文档中.
新建counter.php文档,输入如下代码,跟ASP不同的是PHP里的单行注释是用//或者#,多行注释用/* */来实现:
实例代码如下:
- <?php
- function get_hit($counter_file)
-
- {
- $count=0;
-
-
- if(file_exists($counter_file))
-
- {
- $fp=fopen($counter_file,"r");
-
- $count=0+fgets($fp,20);
-
-
- fclose($fp);
-
- }
- $count++;
-
- $fp=fopen($counter_file,"w");
-
- fputs($fp,$count);
-
- fclose($fp);
- return($count);
-
- }
- ?>
-
- <?php
- $hit=get_hit("counter.txt");
-
- echo "您是第<b>"."$hit"."</b>位访客!";
-
- ?>
同样在需要调用的PHP文档中插入这个文件:
<?php include("counter.php");?> |