本文章来给大家介绍利用php 读目录以列表形式展示,读取目录我们会使用到scandir,opendir,foreach,sizeof这几个常用的函数,下面我们直接看实例。
例1
代码如下 |
复制代码 |
<?php $getUrl = (empty($_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 /** * 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")……可以是绝对路径也可以是相对路径 ?> |
本文地址:http://www.phprm.com/code/47049.html
转载随意,但请附上文章地址:-)