php列出一个目录下的所有文件的代码_php技巧

WBOY
Release: 2016-05-17 09:08:30
Original
914 people have browsed it
复制代码 代码如下:

function dir_path($path) {
$path = str_replace('\\', '/', $path);
if (substr($path, -1) != '/') $path = $path . '/';
return $path;
}
/**
* 列出目录下的所有文件
*
* @param str $path 目录
* @param str $exts 后缀
* @param array $list 路径数组
* @return array 返回路径数组
*/
function dir_list($path, $exts = '', $list = array()) {
$path = dir_path($path);
$files = glob($path . '*');
foreach($files as $v) {
if (!$exts || preg_match("/\.($exts)/i", $v)) {
$list[] = $v;
if (is_dir($v)) {
$list = dir_list($v, $exts, $list);
}
}
}
return $list;
}
?>

使用方法:
复制代码 代码如下:

$r = dir_list('dir');
printf("

输出数据为:

%s
Copy after login
\n", var_export($r , true));
?>


PHP函数-用来列出目录下所有文件2

采用PHP编写的函数,用来列出指定目录下的所有的文件。
函数后面带有一个使用的示例代码。
注意:如果页面是utf-8的,在window中文版本的系统中,读取中文的文件名的时候会出现乱码。
复制代码 代码如下:

/* 函数 listDirTree( $dirName = null )
** 功能 列出目录下所有文件及子目录
** 参数 $dirName 目录名称
** 返回 目录结构数组 false为失败
*/
function listDirTree( $dirName = null )
{
if( empty( $dirName ) )
exit( "IBFileSystem: directory is empty." );
if( is_dir( $dirName ) )
{
if( $dh = opendir( $dirName ) )
{
$tree = array();
while( ( $file = readdir( $dh ) ) !== false )
{
if( $file != "." && $file != ".." )
{
$filePath = $dirName . "/" . $file;
if( is_dir( $filePath ) ) //为目录,递归
{
$tree[$file] = listDirTree( $filePath );
}
else //为文件,添加到当前数组
{
$tree[] = $file;
}
}
}
closedir( $dh );
}
else
{
exit( "IBFileSystem: can not open directory $dirName.");
}
//返回当前的$tree
return $tree;
}
else
{
exit( "IBFileSystem: $dirName is not a directory.");
}
}
$files = listDirTree(".");
//print_r($files);
$size = count(files);
//以下代码是创建一个本目录下文件的列表(带有链接地址)
echo '
    ';
    for( $i=0; $files[$i] != NULL; $i++ ) {
    echo '
  1. '.$files[$i].'
  2. ';
    }
    echo '
';
?>
Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!