内容正文:
/182
第6章 PHP文件处理
6.1 文件操作
6.2 目录操作
6.3 上传文件
/182
6.1 文件操作
6.1.1 打开和关闭文件
用函数file_exists()来检查该文件是否存在:
bool file_exists(string $filename)
用is_file()函数判断给定文件名是不是一个正常文件:
bool is_file(string $filename)
用函数fopen()打开打开一个文件或URL:
resource fopen(string $filename,string $mode[,bool $use_include_path[,resource $context]])
用fclose()函数关闭文件:
bool fclose(resource $handle)
示例
<?php
$filename="/home/rasmus/file.txt";
if(file_exists($filename)){ //检查文件存在性
if($handle=fopen($filename,"r")){; //打开文件并检查文件指针
//对文件进行操作
fclose($handle); //关闭文件
}
}
?>
第6章目录
/182
6.1 文件操作
6.1.2 写入文件
用is_writable()函数判断给定文件是否可写:
bool is_writable(string $filename)
用fwrite()函数将一个字符串写入文件:
int fwrite(resource $handle,string $str[,int $length])
用vfprintf()函数将格式化字符串写入文件:
int vfprintf(resource $handle,string $format,array $args)
用file_put_contents()函数将一个字符串写入文件:
int file_put_contents(string $filename,string $data[,int $flags[,resource $context]])
第6章目录
/182
6.1 文件操作
6.1.3 读取文件
用is_readable()函数判断给定文件名是否可读:
bool is_readable(string $filename)
用fgetc()函数从文件中读取字符:
string fgetc(resource $handle)
用fgetcsv()函数从文件中读入一行并解析CSV字段:
array fgetcsv(int $handle[,int $length[,string $delimiter[,string $enclosure]]])
用fgets()函数从文件中读取一行:
string fgets(int $handle[,int $length])
用fgetss()函数从文件中读取一行并过滤掉HTML标签:
string fgetss(resource $handle[,int $length[,string $allowable_tags]])
用file()函数将整个文件读入一个数组中:
array file(string $filename[,int $use_include_path[,resource $context]])
用file_get_contents()函数将整个文件读入一个字符串:
string file_get_contents(string $filename[,bool $use_include_path
[,resource $context[,int $offset[,int $maxlen]]]])
用fread()函数读取文件(可安全用于二进制文件):
string fread(int $handle,int $length)
用fscanf()函数从文件中格式化输入:
mixed fscanf(resource $handle,string $format[,mixed &$...])
第6章目录
/182
6.1 文件操作
6.1.4 文件定位
用fseek()函数在文件中定位文件指针:
int fseek(resource $handle,int $offset[,int $whence])
用rewind()函数将文件指针设置到文件开头:
bool rewind(resource $handle)
用ftell()函数返回文件指针读/写的位置:
int ftell(resource $handle)
用feof()函数测试文件指针是否到了文件结束的位