加入收藏 | 设为首页 | 会员中心 | 我要投稿 安卓应用网 (https://www.0791zz.com/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > PHP > 正文

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

发布时间:2020-05-24 17:06:13 所属栏目:PHP 来源:互联网
导读:使用php的glob函数可以列出所有符合路径结构的文件和目录,以下从某cms提取出来的函数

<div class="codetitle"><a style="CURSOR: pointer" data="77441" class="copybut" id="copybut77441" onclick="doCopy('code77441')"> 代码如下:<div class="codebody" id="code77441">
<?php
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;
}
?>

使用方法:
<div class="codetitle"><a style="CURSOR: pointer" data="69155" class="copybut" id="copybut69155" onclick="doCopy('code69155')"> 代码如下:<div class="codebody" id="code69155">
<?php
$r = dir_list('dir');
printf("

输出数据为:

%s
n",var_export($r,true));
?>

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

采用PHP编写的函数,用来列出指定目录下的所有的文件。
函数后面带有一个使用的示例代码。
注意:如果页面是utf-8的,在window中文版本的系统中,读取中文的文件名的时候会出现乱码。
<div class="codetitle"><a style="CURSOR: pointer" data="47128" class="copybut" id="copybut47128" onclick="doCopy('code47128')"> 代码如下:<div class="codebody" id="code47128">
<?php
/
函数 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. <a href="'.($files[$i]).'" target="_blank">'.$files[$i].'
  2. ';
    }
    echo '
';
?>

(编辑:安卓应用网)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读