php文件读写操作
首先是一个文件看能不能读取(权限问题),或者存在不,我们可以用is_readable函数获取信息.:
is_readable函数用法
<?php
$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否则此函数不可用。
<?php
$file = "filelist.php";
if (file_exists($file) == false) {
die('文件不存在');
}
$data = file_get_contents($file);
echo htmlentities($data);
?>
读取远程 文件,这是本教程这外的话题了。
<table width="620" align="center" border="0" cellpadding="1" cellspacing="1" style="background:#FB7"> <tr> <td width="464" height="27" bgcolor="#FFE7CE"> 代码如下</td> <td width="109" align="center" bgcolor="#FFE7CE" style="cursor:pointer;" onclick="doCopy('copy2525')">复制代码</td> </tr> <tr> <td height="auto" colspan="2" valign="top" bgcolor="#FFFFFF" style="padding:10px;" class="copyclass" id=copy2525>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.jiaochengji.com/local/something.txt";
$handle = fopen($filename, "r");
$contents = fread($handle, filesize($filename));
fclose($handle);
//php5以上版本读取远程服务器内容
<table width="620" align="center" border="0" cellpadding="1" cellspacing="1" style="background:#FB7"> <tr> <td width="464" height="27" bgcolor="#FFE7CE"> 代码如下</td> <td width="109" align="center" bgcolor="#FFE7CE" style="cursor:pointer;" onclick="doCopy('copy8200')">复制代码</td> </tr> <tr> <td height="auto" colspan="2" valign="top" bgcolor="#FFFFFF" style="padding:10px;" class="copyclass" id=copy8200>$handle = fopen("http://www.jiaochengji.com/", "rb");
$contents = stream_get_contents($handle);
fclose($handle);
还有一种方式,可以读取二进制的文件:
$data = implode('', file($file));
fwrite 文件的写操作
fwrite() 把 string 的内容写入文件指针 file 处。 如果指定了 length,当写入了 length 个字节或者写完了 string 以后,写入就会停止,视乎先碰到哪种情况。
fwrite() 返回写入的字符数,出现错误时则返回 false。
文件写入函式:
<table width="620" align="center" border="0" cellpadding="1" cellspacing="1" style="background:#FB7"> <tr> <td width="464" height="27" bgcolor="#FFE7CE"> 代码如下</td> <td width="109" align="center" bgcolor="#FFE7CE" style="cursor:pointer;" onclick="doCopy('copy5748')">复制代码</td> </tr> <tr> <td height="auto" colspan="2" valign="top" bgcolor="#FFFFFF" style="padding:10px;" class="copyclass" id=copy5748><?php//文件写入函式
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;
}
?>
您可能感兴趣的文章:
学习php写入文件内容的方法
php文件写操作
学习php读取文件内容的方法
php文件操作之读取与写入文件
php文件操作的小例子
php操作xml文件的一些简单范例
php读取与下载csv文件的示例代码
python写文件怎么读出来
php设置index.php文件为只读的方法
python fd是什么意思