php文件读写操作
本文章主要介绍了在php中的文章读取与写文件的操作,我们主要讲取三个函数file_get_contents,fwrite,file用法,然后简单说is_readable判断文件是否可写.
首先是一个文件看能不能读取(权限问题),或者存在不,我们可以用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 ); ?>读取远程文件,这是本教程这外的话题了,代码如下:
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.phpfensi.com/local/something.txt" ; $handle = fopen ( $filename , "r" ); $contents = fread ( $handle , filesize ( $filename )); fclose( $handle );php5以上版本读取远程服务器内容,代码如下:
$handle = fopen ( "http://www.phpfensi.com/" , "rb" ); $contents = stream_get_contents( $handle ); fclose( $handle );还有一种方式,可以读取二进制的文件,代码如下:
$data = implode('', file($file));
fwrite 文件的写操作
fwrite() 把 string 的内容写入文件指针 file 处,如果指定了 length,当写入了 length 个字节或者写完了 string 以后,写入就会停止.
fwrite() 返回写入的字符数,出现错误时则返回 false,文件写入函式,代码如下:
<?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文件操作的详细内容...
声明:本文来自网络,不代表【好得很程序员自学网】立场,转载请注明出处:http://www.haodehen.cn/did27825