<BR><?php <BR>function dir_path($path) { <BR>$path = str_replace('\\', '/', $path); <BR>if (substr($path, -1) != '/') $path = $path . '/'; <BR>return $path; <BR>} <BR>/** <BR>* 列出目录下的所有文件 <BR>* <BR>* @param str $path 目录 <BR>* @param str $exts 后缀 <BR>* @param array $list 路径数组 <BR>* @return array 返回路径数组 <BR>*/ <BR>function dir_list($path, $exts = '', $list = array()) { <BR>$path = dir_path($path); <BR>$files = glob($path . '*'); <BR>foreach($files as $v) { <BR>if (!$exts || preg_match("/\.($exts)/i", $v)) { <BR>$list[] = $v; <BR>if (is_dir($v)) { <BR>$list = dir_list($v, $exts, $list); <BR>} <BR>} <BR>} <BR>return $list; <BR>} <BR>?> <BR>
使用方法:
<BR><?php <BR>$r = dir_list('dir'); <BR>printf("<p>输出数据为:</p><pre class="prettyprint linenums">%s
\n”, var_export($r , true));
?>
PHP函数-用来列出目录下所有文件2
采用PHP编写的函数,用来列出指定目录下的所有的文件。
函数后面带有一个使用的示例代码。
注意:如果页面是utf-8的,在window中文版本的系统中,读取中文的文件名的时候会出现乱码。
<BR><?php <BR>/* 函数 listDirTree( $dirName = null ) <BR>** 功能 列出目录下所有文件及子目录 <BR>** 参数 $dirName 目录名称 <BR>** 返回 目录结构数组 false为失败 <BR>*/ <BR>function listDirTree( $dirName = null ) <BR>{ <BR>if( empty( $dirName ) ) <BR>exit( "IBFileSystem: directory is empty." ); <BR>if( is_dir( $dirName ) ) <BR>{ <BR>if( $dh = opendir( $dirName ) ) <BR>{ <BR>$tree = array(); <BR>while( ( $file = readdir( $dh ) ) !== false ) <BR>{ <BR>if( $file != "." && $file != ".." ) <BR>{ <BR>$filePath = $dirName . "/" . $file; <BR>if( is_dir( $filePath ) ) //为目录,递归 <BR>{ <BR>$tree[$file] = listDirTree( $filePath ); <BR>} <BR>else //为文件,添加到当前数组 <BR>{ <BR>$tree[] = $file; <BR>} <BR>} <BR>} <BR>closedir( $dh ); <BR>} <BR>else <BR>{ <BR>exit( "IBFileSystem: can not ope<a>@本文9来源gao($daima.com搞@代@#码8网^</a><strong>搞代gaodaima码</strong>n directory $dirName."); <BR>} <BR>//返回当前的$tree <BR>return $tree; <BR>} <BR>else <BR>{ <BR>exit( "IBFileSystem: $dirName is not a directory."); <BR>} <BR>} <BR>$files = listDirTree("."); <BR>//print_r($files); <BR>$size = count(files); <BR>//以下代码是创建一个本目录下文件的列表(带有链接地址) <BR>echo '<ol>'; <BR>for( $i=0; $files[$i] != NULL; $i++ ) { <BR>echo '<li>'.$files[$i].'</li>'; <BR>} <BR>echo '</ol>'; <BR>?> <BR>