Home  >  Article  >  php教程  >  php文件读写操作

php文件读写操作

WBOY
WBOYOriginal
2016-06-08 17:24:561288browse

本文章主要介绍了在php中的文章读取与写文件的操作,我们主要讲取三个函数file_get_contents,fwrite,file用法,然后简单说is_readable判断文件是否可写。

<script>ec(2);</script>

首先是一个文件看能不能读取(权限问题),或者存在不,我们可以用is_readable函数获取信息.:
php/func_filesystem_is_readable.htm">is_readable函数用法

 代码如下 复制代码

$file = "test.txt";
if(is_readable($file))
  {
  echo ("$file is readable");
  }
else
  {
  echo ("$file is not readable");
  }
?>

输出:

test.txt is readable


利用file_get_contents函数来读取文件,这个函数可以读取大数据量的文件,也可以读取远程服务器文件,但必须在php.ini开始allow_url_fopen = On否则此函数不可用。

 代码如下 复制代码

  $file = "filelist.php";

  if (file_exists($file) == false) {

  die('文件不存在');

}

$data = file_get_contents($file);

echo htmlentities($data);

?>

读取远程 文件,这是本教程这外的话题了。

 代码如下 复制代码

function vita_get_url_content($url) {
if(function_exists('file_get_contents')) {
$file_contents = file_get_contents($url);
} else {
$ch = curl_init();
$timeout = 5;
curl_setopt ($ch, curlopt_url, $url);
curl_setopt ($ch, curlopt_returntransfer, 1);
curl_setopt ($ch, curlopt_connecttimeout, $timeout);
$file_contents = curl_exec($ch);
curl_close($ch);
}
return $file_contents;
}

利用fread函数
来读取文件,这个函数可以读取指定大小的数据量
//fread读取文件实例一

 代码如下 复制代码

$filename = "/www.111cn.net/local/something.txt";
$handle = fopen($filename, "r");
$contents = fread($handle, filesize($filename));
fclose($handle);

//php5以上版本读取远程服务器内容

 代码如下 复制代码

$handle = fopen("http://www.111cn.net/", "rb");
$contents = stream_get_contents($handle);
fclose($handle);


还有一种方式,可以读取二进制的文件:

 代码如下 复制代码

$data = implode('', file($file));


fwrite 文件的写操作

fwrite() 把 string 的内容写入文件指针 file 处。 如果指定了 length,当写入了 length 个字节或者写完了 string 以后,写入就会停止,视乎先碰到哪种情况。

fwrite() 返回写入的字符数,出现错误时则返回 false。

文件写入函式:

 代码如下 复制代码
//文件写入函式
function PHP_Write($file_name,$data,$method="w") {
$filenum=@fopen($file_name,$method);
flock($filenum,LOCK_EX);
$file_data=fwrite($filenum,$data);
fclose($filenum);
return $file_data;
}
?>
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