一、文件函数库
1、readfile()函数读取文件,并把它写入缓存。
新建一个01.txt,写入一下内容
php readfile
<?php
echo readfile("01.txt");
?>
2、fopen打开文件
fopen()函数的第一个参数表示要操作的文件,第二个参数表示打开文件的模式。
<?php
$file = fopen("01.txt", "r") or die("出现错误!");
echo fread($file, filesize("01.txt"));
fclose($file);
?>
模式 | 描述 |
---|---|
r | 打开文件为只读。文件指针在文件的开头开始。 |
w | 打开文件为只写。删除文件的内容或创建一个新的文件,如果它不存在。文件指针在文件的开头开始。 |
a | 打开文件为只写。文件中的现有数据会被保留。文件指针在文件结尾开始。创建新的文件,如果文件不存在。 |
x | 创建新文件为只写。返回 FALSE 和错误,如果文件已存在。 |
r+ | 打开文件为读/写、文件指针在文件开头开始。 |
w+ | 打开文件为读/写。删除文件内容或创建新文件,如果它不存在。文件指针在文件开头开始。 |
a+ | 打开文件为读/写。文件中已有的数据会被保留。文件指针在文件结尾开始。创建新文件,如果它不存在。 |
x+ | 创建新文件为读/写。返回 FALSE 和错误,如果文件已存在。 |
3、fread()读取文件
fread()第一个参数表示待读取的文件(就是fopen()的指针),第二个参数规定待读取的最大字节数。
4、fclose()关闭文件
关闭文件,节省计算机资源
5、fgets()读取单行文件
调用fgets()函数后,文件指针会移动到下一行
6、feof()遍历未知长度的数据很有用。
7、fget()函数用于从文件中读取但个字符。
文件指针会自动下移
8、fwirte()写入文件
第一个参数表示要写入的文件,第二个参数表示要写入的内容。
9、file_get_contents() 整个文件读入到字符串。
二、目录操作
1.目录读取、opendir()、readdir()、closedir()
<?php
$dir = opendir("filedir/");
while ($filelist = readdir($dir)) {
echo $filelist . "<br />";
}
closedir($dir);
?>
dirname($path)返回文件目录部分
basename($path)返回文件名称部分
disk_free_space($path)返回文件所在分区的大小
2.php拷贝一个目录操作
<?php
function copydir($sourceDir, $destDir)
{
if (!is_dir($sourceDir)) {
return false;
}
if (!is_dir($destDir)) {
if (!mkdir($destDir)) {
return false;
}
}
$dir = opendir($sourceDir);
if (!$dir) {
return false;
}
while(false !== ($file=readdir($dir))) {
if ($file != '.' && $file != '..') {
if (is_dir($sourceDir.'/'.$file)) {
if (!copydir($sourceDir.'/'.$file, $destDir.'/'.$file)) {
return false;
}
}else {
if (!copy($sourceDir.'/'.$file, $destDir.'/'.$file)) {
return false;
}
}
}
}
closedir($dir);
return true;
}
copydir('./test1', './test2');
3.php删除一个目录
<?php
function deldir($dir)
{
$dh = opendir($dir);
while ($file = readdir($dh))
{
if ($file != '.' && $file != '..') {
$fullpath = $dir.'/'.$file;
if (!is_dir($fullpath)) {
unlink($fullpath);
} else {
deldir($fullpath);
}
}
}
closedir($dh);
if (rmdir($dir)) {
return true;
}
return false;
}
deldir('./test2');