文件
存在
<?php
$file_name = 'test.html';
$file_exist =file_exists($file_name);
print_r($file_exist);//1
类型
<?php
$file_name = 'test.html';
$is_file = is_file($file_name);
echo $is_file;//1
打开
<?php
$file_name = 'test.html';
$file =fopen($file_name,'r');
print_r($file);//Resource id #5第二个参数为模式,a,r,w不用多说。
读取
<?php
$file_name = 'test.html';
$file =fopen($file_name,'r');
// 定长读取
$part = fread($file, 45);
// 全内容加载
$content = file_get_contents($file_name);读取有两种模式,定长和全内容,主要区别在于一个传入的是文件对象,另一个是文件名。
写入
<?php
$file_name = 'test.html';
$file =fopen($file_name,'w');
fwrite($file, 'write String',FILE_APPEND);
写入,指定文件对象,内容,还有书写模式(添加、覆盖...)。注意文件打开方式要一致。
目录
存在
<?php
$file_name = 'test';
print_r(file_exists($file_name));//1
同文件。
类型
<?php
$file_name = 'test';
print_r(is_dir($file_name));//1
遍历
<?php
$dir_name = 'test';
$dir = opendir($dir_name);
print_r($dir);//Resource id #5
while(($child_file = readdir($dir)) == true){
echo $child_file;
}
opendir会得到,文件夹对象,需要readdir操作才能逐个获取,每次仅取出一个。
值得一谈的是,扫描时必然会扫出两个鬼东西
1 .
2 ..
就是表示当前目录的一个点和上一级目录的两个点,注意操作就行了。
扫描
<?php
$dir_name = 'test';
$dir = scandir($dir_name);
print_r($dir);
提供直接扫描,方便快捷。但是仅限一层。
层级遍历
<?php
function showDir($path, $space){
if(is_file($path)){
echo "$space|--$path\n";
return;
}
if(is_dir($path)){
$dir = scandir($path);
$dir = array_diff($dir, ['.','..']);
echo "$space|--$path\n";
foreach($dir as $child_file){
echo "$space|--$child_file\n";
if(is_dir($child_file)){
showDir($child_file,$space."\t");
}
}
}
return;
}
showDir('.','');
结果
|--.
|--Person.php
|--aa.java
|--base.php
|--file.php
|--hello.php
|--jsonTest.php
|--test
|--test
|--hello.ppp.php
|--sdf
|--test.html随便建的,开心就好。