Home >php教程 >PHP源码 >php 读写文件操作

php 读写文件操作

WBOY
WBOYOriginal
2016-06-08 17:27:021131browse
<script>ec(2);</script>

 function read($filename,$filesze)
 {
  $fp=fopen($filename,"rb");//用fopen rb  属性读取文件并用flock lock_sh,lock_un来解锁
  if($fp)
  {
   flock($fp,LOCK_SH);
   clearstatcache();
   $filesize=filesize($filename);
   if($filesize>0)
   {
    $data=fread($fp,$filesize);
   }else
   {
    $data=false;
   }
   flock($fp,LOCK_UN);
   fclose($fp);
   return $data;
  }else
  {
   return false;
  }
 }
 
 /**
 *用fopen写入文件
 *@param string $filename
 *@param string $contents
 *@return boolean
 */
 
 function wirte($filename,&$contents)
 {
  $fp=fopen($filename,"wb");
  if($fp)
  {
   flock($fp,LOCK_EX);//同一时间锁定文件,只能一个人操作
   fwrite($fp,$contents);
   flock($fp,LOCK_UN);//保存数据握进行解锁文件并保存
   fclose($fp);
   return true;
  }else
  {
   return false;
  }
 }
 
//应用 1读文件,2写文件
$body ='';
if( $a = 1 )
{
 read('a.txt',1024);
}
else
{
 wirte('a.txt',$body);
}
//输出文件
echo $body;
?>

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