Home > php教程 > PHP源码 > body text

php 读目录以列表形式展示实例

WBOY
Release: 2016-06-08 17:24:01
Original
2288 people have browsed it

本文章来给大家介绍利用php 读目录以列表形式展示,读取目录我们会使用到scandir,opendir,foreach,sizeof这几个常用的函数,下面我们直接看实例。

<script>ec(2);</script>

例1

 代码如下 复制代码

 
$getUrl = (empty($_GET['url'])) ? './' : $_GET['url'].'/';
 
function fileName($dir)
{
 
    $fileAll = scandir($dir,0);
    $pathDir = $pathFile = array();
    $count = count($fileAll);
 
    if($count         echo "空目录
";
    }
     
    foreach($fileAll as $pdf){
        if(is_dir($dir.$pdf)){
            $pathDir[] = $pdf;
        }else{
            $pathFile[] = $pdf;
        }
    }
 
    foreach($pathDir as $pd){
        if($pd == '.' or $pd == '..') continue;
        echo "$pd
";
    }
 
    foreach($pathFile as $pf){
        echo "$pf
";
    }
 
    if($dir != './'){
        $dir = rtrim($dir,'/'); 
        $dir = explode('/',$dir);
        unset($dir[sizeof($dir)-1]);
        $dir = implode('/',$dir);
        echo "Go Back";
    }
 
}
 
fileName($getUrl);

例2

 代码如下 复制代码

/**
 * Goofy 2011-11-30
 * getDir()去文件夹列表,getFile()去对应文件夹下面的文件列表,二者的区别在于判断有没有“.”后缀的文件,其他都一样
 */

//获取文件目录列表,该方法返回数组
function getDir($dir) {
 $dirArray[]=NULL;
 if (false != ($handle = opendir ( $dir ))) {
  $i=0;
  while ( false !== ($file = readdir ( $handle )) ) {
   //去掉"“.”、“..”以及带“.xxx”后缀的文件
   if ($file != "." && $file != ".."&&!strpos($file,".")) {
    $dirArray[$i]=$file;
    $i++;
   }
  }
  //关闭句柄
  closedir ( $handle );
 }
 return $dirArray;
}

//获取文件列表
function getFile($dir) {
 $fileArray[]=NULL;
 if (false != ($handle = opendir ( $dir ))) {
  $i=0;
  while ( false !== ($file = readdir ( $handle )) ) {
   //去掉"“.”、“..”以及带“.xxx”后缀的文件
   if ($file != "." && $file != ".."&&strpos($file,".")) {
    $fileArray[$i]="./imageroot/current/".$file;
    if($i==100){
     break;
    }
    $i++;
   }
  }
  //关闭句柄
  closedir ( $handle );
 }
 return $fileArray;
}

//调用方法getDir("./dir")……可以是绝对路径也可以是相对路径
?>

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 Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template