本文章来给大家介绍利用php 读目录以列表形式展示,读取目录我们会使用到scandir,opendir,foreach,sizeof这几个常用的函数,下面我们直接看实例.
例1,代码如下:
- $getUrl = (emptyempty($_GET['url'])) ? './' : $_GET['url'].'/';
- function fileName($dir)
- {
-
- $fileAll = scandir($dir,0);
- $pathDir = $pathFile = array();
- $count = count($fileAll);
-
- if($count <= 2){
- echo "空目录<br />";
- }
-
- foreach($fileAll as $pdf){
- if(is_dir($dir.$pdf)){
- $pathDir[] = $pdf;
- }else{
- $pathFile[] = $pdf;
- }
- }
-
- foreach($pathDir as $pd){
- if($pd == '.' or $pd == '..') continue;
- echo "<a href="?url=$dir$pd">$pd</a><br />";
- }
-
- foreach($pathFile as $pf){
- echo "<a href="$dir$pf" target="_blank">$pf</a><br />";
- }
-
- if($dir != './'){
- $dir = rtrim($dir,'/');
- $dir = explode('/',$dir);
- unset($dir[sizeof($dir)-1]);
- $dir = implode('/',$dir);
- echo "<a href="?url=$dir">Go Back</a>";
- }
-
- }
-
- fileName($getUrl);
例2,代码如下:
- <?php
-
-
-
-
-
-
-
- function getDir($dir) {
- $dirArray[]=NULL;
- if (false != ($handle = opendir ( $dir ))) {
- $i=0;
- while ( false !== ($file = readdir ( $handle )) ) {
-
- 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 )) ) {
-
- if ($file != "." && $file != ".."&&strpos($file,".")) {
- $fileArray[$i]="./imageroot/current/".$file;
- if($i==100){
- break;
- }
- $i++;
- }
- }
-
- closedir ( $handle );
- }
- return $fileArray;
- }
-
-
- ?>
|