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

WBOY
Freigeben: 2016-05-17 09:08:30
Original
915 人浏览过
复制代码 代码如下:

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
Nach dem Login kopieren
\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 '
';
?>
Verwandte Etiketten:
Quelle:php.cn
Erklärung dieser Website
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn
Beliebte Tutorials
Mehr>
Neueste Downloads
Mehr>
Web-Effekte
Quellcode der Website
Website-Materialien
Frontend-Vorlage
Über uns Haftungsausschluss Sitemap
Chinesische PHP-Website:Online-PHP-Schulung für das Gemeinwohl,Helfen Sie PHP-Lernenden, sich schnell weiterzuentwickeln!