为php遍历目录和文件列表写了一个简单的类,并附上使用实例,大家参考使用吧
class getdirfile{
//返回数组
private $dirarray = array();
private $filearray = array();
private $dirfilearray = array();
private $handle,$dir,$file;
//获取目录列表
public function getdir( & $dir ){
if( is_dir($dir) ){
if( false != ($handle = opendir($dir)) ){
while( false != ($file = readdir($handle)) ){
if( $file!='.' && $file!='..' && !strpos($file,'.') ){
$dirarray[] = $file;
}
}
closedir( $handle );
}
}else{
$dirarray[] = '[path]:\''.$dir.'\' is not a dir or not found!';
}
return $dirarray;
}
//获取文件列表
public function getfile( & $dir ){
if( is_dir($dir) ){
if( false != ($handle = opendir($dir)) ) {
while( false != ($file = readdir($handle)) ){
if( $file!='.' && $file!='..' && strpos($file,'.') ){
$filearray[] = $file;
}
}
closedir( $handle );
}
}else{
$filearray[] = '[path]:\''.$dir.'\' is not a dir or not found!';
}
return $filearray;
}
//获取目录/文件列表
public function getdirfile( & $dir ){
if( is_dir($dir) ){
$dirfilearray['dirlist'] = $this->getdir( $dir );
if( $dirfilearray ){
foreach( $dirfilearray['dirlist'] as $handle ){
$file = $dir.ds.$handle;
$dirfilearray['filelist'][$handle] = $this->getfile( $file );
}
}
}else{
$dirfilearray[] = '[path]:\''.$dir.'\' is not a dir or not found!';
}
return $dirfilearray;
}
}
?>
实例:(相对路径或绝对路径)
1.获取目录列表
显示
$getdirfile = new getdirfile();
$getfile_one = $getdirfile->getfile( $file_one_dir );
$getfile_two = $getdirfile->getfile( $file_two_dir );
print_r($getfile_one);
print_r($getfile_two);
?>
2.获取文件列表
$getdirfile = new getdirfile();
$getfile_one = $getdirfile->getfile( $file_one_dir );
$getfile_two = $getdirfile->getfile( $file_two_dir );
print_r($getfile_one);
print_r($getfile_two);
?>
显示
array
(
[0] => example.php
)
3.获取目录/文件列表
$getdirfile = new getdirfile();
$getdirfile = $getdirfile->getdirfile( $dir_dir );
print_r($getdirfile);
?>
显示
[filelist] => array
(
[example_one] => array
(
[0] => example.sql
[1] => example.txt
)
[example_two] => array
(
[0] => example.php
)
)
)
如对本文有疑问, 点击进行留言回复!!
[ACTF2020 新生赛]Include 1【文件包含】【读取代码】
算法题解 - 牛客编程巅峰赛S1第6场 - 黄金&钻石&王者组
推荐一个程序员必备网站之一:Dev Hints ,非常实用!
网友评论