|
 |
scandir (PHP 5) scandir --
Получить список файлов и каталогов, расположенных по указанному пути
Описаниеarray scandir ( string directory [, integer sorting_order] )
Возвращает array, содержащий имена файлов и каталогов,
расположенных по пути, переданном в параметре directory.
Если directory не является таковым, функция
возвращает логическое значение FALSE и генерирует сообщение
об ошибке уровня E_WARNING.
По умолчанию, сортировка производится в алфавитном порядке по возрастанию.
Если указан необязательный параметр sorting_order
(равен 1), сортировка производится в алфавитном порядке по убыванию.
Пример 1. Простой пример использования функции scandir()
<?php
$dir = '/tmp';
$files1 = scandir($dir);
$files2 = scandir($dir, 1);
print_r($files1);
print_r($files2);
?>
|
|
Пример 2. Альтернативный вариант функции scandir() для PHP 4
<?php
$dir = "/tmp";
$dh = opendir($dir);
while (false !== ($filename = readdir($dh))) {
$files[] = $filename;
}
sort($files);
print_r($files);
rsort($files);
print_r($files);
?>
|
|
См.также описания функций opendir(),
readdir(),
glob(),
is_dir() и
sort().
scandir
greg at sasses dot net
19-May-2006 12:27
A minor revision to elbekko at gmail dot com <PHP5 scandir function. The arsort should be rsort. Here is the complete function with the correction:
<?php
if(!function_exists('scandir')) {
function scandir($dir, $sortorder = 0) {
if(is_dir($dir)) {
$dirlist = opendir($dir);
while( ($file = readdir($dirlist)) !== false) {
if(!is_dir($file)) {
$files[] = $file;
}
}
($sortorder == 0) ? asort($files) : rsort($files); return $files;
} else {
return FALSE;
break;
}
}
}
?>
elbekko at gmail dot com
08-Apr-2006 04:34
Scandir function for php 3 and up.
<?php
if(!function_exists('scandir'))
{
function scandir($dir, $sortorder = 0)
{
if(is_dir($dir))
{
$dirlist = opendir($dir);
while( ($file = readdir($dirlist)) !== false)
{
if(!is_dir($file))
{
$files[] = $file;
}
}
($sortorder == 0) ? asort($files) : arsort($files);
return $files;
}
else
{
return FALSE;
break;
}
}
}
?>
www.mdsjack.bo.it
07-Apr-2006 11:54
I would like to share a couple of functions I've made to get an Array of files of a certain extension inside a Directory.
<?php
function php4_scandir($dir, $sort = 0)
{
if (PHP_VERSION >= '5') return scandir($dir, $sort);
$dirmap = array();
if(!is_dir($dir))
{
trigger_error("lib::scandir($dir): failed to open dir: Invalid argument", E_USER_WARNING);
return false;
}
$dir = opendir($dir);
while (false !== ($file = readdir($dir)))
$dirmap[] = $file;
closedir($dir);
($sort == 1) ? rsort($dirmap) : sort($dirmap);
return $dirmap;
}
function dir2arr($dir, $ext = null)
{
$arr = array();
if(PHP_VERSION >= '4.3.0')
{
if ($dir = glob("$dir*".(!$ext ? '.*' : '{'.$ext.', '.strtoupper($ext).'}'), GLOB_NOSORT + GLOB_BRACE))
foreach ($dir as $file)
$arr[] = preg_replace("#(?:.+\/{1})*([^\.]+)\.(.+)#i", '$1', $file);
}
else
{
$dir = php4_scandir($dir); if(!$ext) $ext = '\.[a-z]+';
$pattern = "#([^\.|\.\.$]+)$ext#i";
foreach ($dir as $file)
if (preg_match($pattern, $file, $filename))
$arr[] = $filename[1];
}
return (empty($arr) ? false : $arr);
}
?>
Bosmans Koen
23-Jan-2006 02:14
in addition to "brodseba at brodseba dot com" from march 2005:
Perfected the script to sort files and directories
in natural alphabetic order and with files listed first.
Also added a more relative directory path approach.
And changed the javascripting for links in simple ordinary href's.
Note that the script uses scandir from the pear package
(since I'm obliged to use an older PHP version).
<?
require_once '\pear\PHP\Compat\Function\scandir.php';
function cmp($a, $b) {
if ( substr_count($a,".") == substr_count($b,".") ) {
if ( is_string($a) && is_string($b) ) {
return strcasecmp($a, $b) > 0 ? 1 : -1;
}elseif ( is_int($a) && is_int($b) ) {
return $a > $b ? 1 : -1;
}elseif ( is_int($a) && is_string($b) ) {
return 1;
}elseif ( is_string($a) && is_int($b) ) {
return -1;
}else {
return 0;
}}
return substr_count($a,".") < substr_count($b,".") ? 1 : -1;
}
function ls_recursive2($dir) {
if (is_dir($dir)) {
$files = scandir($dir);
usort ($files, "cmp");
foreach ($files as $file) {
$currentfile = $dir . "/" . $file;
$last_dir = "";
$count = substr_count($currentfile, '/');
$minus_count = substr_count($_SERVER['SCRIPT_FILENAME'], '/');
$count -= ($minus_count +1);
for($p = 0; $p < $count; $p++) {
$last_dir .= " ";
}
if (is_dir($currentfile)) {
if ($file != '.' && $file != '..') {
$sub_len = strlen(dirname($_SERVER['SCRIPT_FILENAME']))+1;
$java_targ = substr($currentfile, $sub_len);
$last_dir .= " <img src='folder.png'
alt='' align='middle' border='0'>
<a href=".$java_targ.">".$java_targ ."</a><br>\n";
echo $last_dir;
ls_recursive2($currentfile);
}
} else {
$sub_len = strlen(dirname($_SERVER['SCRIPT_FILENAME']))+1;
$java_targ = substr($currentfile, $sub_len);
$last_dir .= "<img src='file.png'
alt='' align='middle' border='0'>
<a href=".$java_targ.">".$java_targ."</a><br>\n";
echo $last_dir;
}}}}
?>
<?
$this = dirname($_SERVER['SCRIPT_FILENAME']);
echo $this."<br>\n";
ls_recursive2($this);
?>
**
ps: I can take a comment, even some criticism,
but do understand: I'm fairly new at this.
colabus at gmail dot com
08-Jan-2006 10:02
I made a small dir listing based on file modification date, could find alot on this myself so I hope this helps someone.
<?
$dirView="./blah";
$dirFiles=scandir($dirView);
$cwdName=array(); $cwdMod=array(); $whatWeNeed=array();
foreach ($dirFiles as $data)
{
if (!preg_match('/^\./', $data))
{
$cwdName[]=$data;
$cwdMod[]=filemtime($dirView."/".$data);
}
}
$mergeArray=array_combine($cwdMod, $cwdName);
krsort($mergeArray, SORT_NUMERIC);
foreach ($mergeArray as $key => $value)
{
$whatWeNeed[]=$value;
}
unset($dirFiles, $cwdName, $cwdMod, $mergeArray);
?>
Tested with error_reporting(E_ALL); and PHP5.1
carlfredrik dot bowin at gmail dot com
05-Jan-2006 06:03
I made a function that scans the directory and all it subfolders. You can also sort them with folders first and files after, in alphabetic order. It works with both PHP 4 and 5.
<?php
function rec_scandir($dir)
{
$files = array();
if ( $handle = opendir($dir) ) {
while ( ($file = readdir($handle)) !== false ) {
if ( $file != ".." && $file != "." ) {
if ( is_dir($dir . "/" . $file) ) {
$files[$file] = rec_scandir($dir . "/" . $file);
}else {
$files[] = $file;
}
}
}
closedir($handle);
return $files;
}
}
function cmp($a, $b)
{
if ( is_string($a) && is_string($b) ) {
return strcmp($a, $b) > 0 ? 1 : -1;
}elseif ( is_int($a) && is_int($b) ) {
return $a > $b ? 1 : -1;
}elseif ( is_int($a) && is_string($b) ) {
return 1;
}elseif ( is_string($a) && is_int($b) ) {
return -1;
}else {
return 0;
}
}
function array_ukmultisort(&$arr, $func) {
uksort($arr, $func);
while ( list($key, $val) = each($arr) ) {
if ( is_array($val) ) {
array_ukmultisort($arr[$key], $func);
}
}
}
$dir = rec_scandir(".");
array_ukmultisort($dir, "cmp");
echo "<pre>";
print_r($dir);
echo "</pre>";
?>
sk3391 at gmail dot com
06-Dec-2005 06:56
Here is a little script that i through together to count the files in my directory while excluding the "." i hope it helps you out!
<?
$dir = ".";
$sort = 0;
$dir_open = @ opendir($dir);
while (($dir_content = readdir($dir_open)) !== false)
$files[] = $dir_content;
if ($sort == 1) {
rsort($files, SORT_STRING);
} else {
sort($files, SORT_STRING);
}
$a=0;
$b=10;
$file_s="";
while($a < $b) {
$c=1;
$d=5;
while($c < $d) {
$dot[$c.",".$a]=str_repeat(".", $c);
if($files[$a] == $dot[$c.",".$a]) {
unset($files[$a]);
} else {
}
$c++;
}
if($files[$a] != "") {
$brake[$a]="<br>";
} else {
$brake[$a]="";
}
$file_s.=$files[$a].$brake[$a];
$a++;
}
echo $file_s;
echo "<br><br><br>";
echo count($files);
?>
Yassin Ezbakhe <yassin88 at gmail dot com>
31-Aug-2005 04:18
/**********************************************
*
* PURPOSE: List files inside the specified path and its
* subdirectories
*
* array scandir_recursive (string dir)
*
* This function will return a multidimensional array
* that represents main folder's tree structure.
* Each folder has its own named array
*
**********************************************/
function scandir_recursive($directory)
{
$folderContents = array();
$directory = realpath($directory).DIRECTORY_SEPARATOR;
foreach (scandir($directory) as $folderItem)
{
if ($folderItem != "." AND $folderItem != "..")
{
if (is_dir($directory.$folderItem.DIRECTORY_SEPARATOR))
{
$folderContents[$folderItem] = scandir_recursive( $directory.$folderItem."\\");
}
else
{
$folderContents[] = $folderItem;
}
}
}
return $folderContents;
}
trevi55 at gmail dot com
08-Jul-2005 05:38
For non php5-users here you are this function...
It isn't set the wrapper, but I think it's enough :P.
If no pararameter is set, the scandir() function will scan the local file directory.
Set the optional parameter "$sort" to 1 to reverse the alphabetical-sorting.
<?
function scandir($dir = './', $sort = 0)
{
$dir_open = @ opendir($dir);
if (! $dir_open)
return false;
while (($dir_content = readdir($dir_open)) !== false)
$files[] = $dir_content;
if ($sort == 1)
rsort($files, SORT_STRING);
else
sort($files, SORT_STRING);
return $files;
}
?>
progrium+php at gmail dot com
30-Jun-2005 04:54
I made this to represent a directory tree in an array that uses the file or directory names as keys and full paths as the value for files. Directories are nested arrays.
<?php
function generatePathTree($rootPath) {
$pathStack = array($rootPath);
$contentsRoot = array();
$contents = &$contentsRoot;
while ($path = array_pop($pathStack)) {
$contents[basename($path)] = array();
$contents = &$contents[basename($path)];
foreach (scandir($path) as $filename) {
if ('.' != substr($filename, 0, 1)) {
$newPath = $path.'/'.$filename;
if (is_dir($newPath)) {
array_push($pathStack, $newPath);
$contents[basename($newPath)] = array();
} else {
$contents[basename($filename)] = $newPath;
}
}
}
}
return $contentsRoot[basename($rootPath)];
}
?>
The function will return something like this:
Array
(
[index.php] => /usr/local/www/index.php
[js] => Array
(
[async.js] => /usr/local/www/js/async.js
[dom.js] => /usr/local/www/js/dom.js
[effects.js] => /usr/local/www/js/effects.js
[prototype.js] => /usr/local/www/js/prototype.js
)
[logo.png] => /usr/local/www/logo.png
[server.php] => /usr/local/www/server.php
[test.js] => /usr/local/www/test.js
)
welshwizard at gmail dot com
21-May-2005 07:37
Im wanting to when php executed for the script to scan for certain file extensions in a windows mapped out folder which is set as H:\ when a user logs on.
Will the php scan locally (the linux box) or will it work client side like i want?
thnks
Mat
pablo dot fabregat at gmail dot com
14-May-2005 02:46
i was triyng to do something similar to the ls -R command in linux, so, using the functions from csaba , i could, so, using this simple lines, you'll get that result:
<?php
$directory = "."; $directories = dirList($directory, 2, 0); foreach ($directories as $dir){
echo $dir."<br>";
}
?>
and that's it, remember that you need the functions listed above from csaba to use this
Pawel Dlugosz
11-May-2005 11:18
For directory containing files like (for example) -.jpg the results of scandir are a little "weird" ;)
<?php
$dir = '/somedir';
$files = scandir($dir);
print_r($files);
?>
Array
(
[0] => -.jpg
[1] => .
[2] => ..
[3] => foo.txt
[4] => somedir
)
Beware - sorting is in ASCII order :)
wwwebdesigner at web doott de
12-Apr-2005 12:20
using sort of scandir() that returns the content sorted by Filemodificationtime.
<?php
function scandir_by_mtime($folder) {
$dircontent = scandir($folder);
$arr = array();
foreach($dircontent as $filename) {
if ($filename != '.' && $filename != '..') {
if (filemtime($folder.$filename) === false) return false;
$dat = date("YmdHis", filemtime($folder.$filename));
$arr[$dat] = $filename;
}
}
if (!ksort($arr)) return false;
return $arr;
}
?>
returns false if an error occured
otherwise it returns an array like this.
Array
(
[20040813231320] => DSC00023.JPG
[20040813231456] => DSC00024.JPG
[20040814003728] => MOV00055.MPG
[20040814003804] => DSC00056.JPG
[20040814003946] => DSC00057.JPG
[20040814004030] => DSC00058.JPG
[20040814014516] => DSC00083.JPG
[20050401161718] => album.txt
)
brodseba at brodseba dot com
24-Mar-2005 08:53
This function create a HTML view of a directory. It also look for subdirectory. I use some icon to differ from folders or files. It's also possible to get specific icon for specific file type.
Each entrey is clickable so you can use it to populate a form field.
Have fun!
function ls_recursive2($dir)
{
if (is_dir($dir))
{
$files = scandir($dir);
foreach ($files as $file)
{
$currentfile = $dir . "/" . $file;
$last_dir = "";
// Calculate they identation.
$count = substr_count($currentfile, '/');
$minus_count = substr_count($_SERVER['DOCUMENT_ROOT'], '/');
$count -= ($minus_count + 2);
for($p = 0; $p < $count; $p++)
{
$last_dir .= " ";
}
if (is_dir($currentfile))
{
if ($file != '.' && $file != '..')
{
$last_dir .= "<img src='images/folder.gif' alt='' align='middle' width='16' height='16' border='0'> <a href=\"javascript:go('" . $currentfile . "')\">". substr($currentfile, strrpos($currentfile, '/')) . "</a><br>";
echo $last_dir;
ls_recursive2($currentfile);
}
}
else
{
$last_dir .= "<img src='images/file.gif' alt='' align='middle' width='16' height='16' border='0'> <a href=\"javascript:go('" . $currentfile . "')\">". substr($currentfile, strrpos($currentfile, '/')) . "</a><br>";
echo $last_dir;
}
}
}
}
csaba at alum dot mit dot edu
04-Mar-2005 03:19
Scandir on steroids:
For when you want to filter your file list, or only want to list so many levels of subdirectories...
<?php
function dirList($path="", $types=2, $levels=1, $aFilter=array()) {
$dS = DIRECTORY_SEPARATOR;
if (!($path = realpath($path?$path:getcwd()))) return array(); if (substr($path,-1)==$dS) $path = substr($path,0,-1);
if (is_null($types)) $types = 2;
if (is_null($levels)) $levels = 1;
if (is_null($aFilter)) $aFilter=array();
$aFilter = array_slice(func_get_args(),3);
if ($aFilter && gettype($aFilter[0])=="array") $aFilter=$aFilter[0];
$adFilter = array();
foreach ($aFilter as $i=>$filter) if (($pos=stripos(" $filter","d")) && $pos<3) { $adFilter[] = substr($filter,0,$pos-1) . substr($filter,$pos);
unset($aFilter[$i]); }
$aFilter = array_merge($aFilter); $aRes = array(); $aDir = array($path); for ($i=$levels>0?$levels++:-1;($aAcc=array())||$i--&&$aDir;$aDir=$aAcc)
while ($dir = array_shift($aDir))
foreach (scandir ($dir) as $fileOrDir)
if ($fileOrDir!="." && $fileOrDir!="..") {
if ($dirP = is_dir ($rp="$dir$dS$fileOrDir"))
if (pathFilter("$rp$dS", $adFilter))
$aAcc[] = $rp;
if ($i<$levels-1 && ($types & (2-$dirP)))
if (pathFilter($rp, $aFilter))
$aRes[] = ($dirP?"*":"") . $rp; }
return $aRes;
}
?>
example usage:
<?php
define ("_", NULL);
$aFiles = dirList('c:\Photo', _, 0, '-/\.jpg$/i', '-/\\\\Thumbs.db$/');
$aFiles = dirList(); set_time_limit(60); $aFiles = dirList("c:\\", _, 0, '/\.jpg$/i', '-d/\\\\Photos?$/i', '-d/Temporary Internet/i');
?>
See my earlier entry for the definition of pathFilter(...)
Note that this function will consume a lot of time if scanning large
directory structures (which is the reason for the '[-]d/.../' filters).
Csaba Gabor from Vienna
csaba at alum dot mit dot edu
04-Mar-2005 04:52
A nice way to filter the files/directories you get back from scandir:
<?php
function pathFilter ($path, $aFilter) {
if (!$aFilter) return true; foreach ($aFilter as $filter) break; $in = $filter[0]=="-"; foreach ($aFilter as $filter) if ($in==$not=($filter[0]=="-")) $in ^= preg_match(substr($filter,$not),$path); return $in;
}
?>
Csaba Gabor from Vienna
rich at jamsoft dot biz
09-Feb-2005 07:33
Ok, in my previous example, you need to do the SORT after you remove the "." and ".." entries from the array. Otherwise, you cannot start using the array at 0.
Here is corrected code:
<?php
function scandir($dir, $no_dots=FALSE) {
$files = array();
$dh = @opendir($dir);
if ($dh!=FALSE) {
while (false !== ($filename = readdir($dh))) {
$files[] = $filename;
}
if ($no_dots) {
while(($ix = array_search('.',$files)) > -1)
unset($files[$ix]);
while(($ix = array_search('..',$files)) > -1)
unset($files[$ix]);
}
sort($files);
}
return $files;
}
?>
virtual at NOSPAM dot lapinbleu dot ch
09-Feb-2005 05:58
Since I needed to scan dirs and subdirs and wanted to have files and dirs not in the same var without having to explode it, I did this little function:
<?php
function scan_Dir($directory=NULL)
{
$temp = "";
if ($directory==NULL)
{
$directory = getcwd();
}
$handle = opendir($directory);
while (false !== ($filename = readdir($handle)))
{
if (($filename!=".") AND ($filename!=".."))
{
if (is_dir($directory."/".$filename))
{
$old_directory = $directory;
$directory .= "/".$filename;
$temp = scan_Dir($directory);
$cpt = 0;
while ($cpt<count($temp["filename"]))
{
$arrfiles["path"][] = $directory."/".$temp["filename"][$cpt];
$arrfiles["directory"][] = $directory;
$arrfiles["filename"][] = $temp["filename"][$cpt];
$cpt++;
}
$directory = $old_directory;
}
else
{
$arrfiles["path"][] = $directory."/".$filename;
$arrfiles["directory"][] = $directory;
$arrfiles["filename"][] = $filename;
}
}
}
return $arrfiles;
}
?>
This one seems to work properly and use multidimensional array.
To show your files, just use:
<?php
$dir2scan = "admin";
$yourvar = scan_Dir($dir2scan);
echo $yourvar["path"][0]."<br>"; echo $yourvar["directory"][0]."<br>"; echo $yourvar["filename"][0]."<br>"; ?>
Note that the parameter of the function is not necessary. If you don't give any, it will scan from the returned value of getcwd() function.
skatecrazy1 at digibase dot ca
24-Nov-2004 10:25
Scandir can be used to make directories of files not unlike apache's indexes, but CSS enabled and fully customizable:
<?
$list = scandir("images");
$i = 0;
$num = count($list);
while($i < $num){
print "<a href=\"images/$list[$i]\">$list[$i]</a><br />";
$i++;
}
?>
That will print all the files in the "images" directory linked to the files.
Stan P. van de Burgt
26-Oct-2004 09:05
scandir() with regexp matching on file name and sorting options based on stat().
function myscandir($dir, $exp, $how='name', $desc=0)
{
$r = array();
$dh = @opendir($dir);
if ($dh) {
while (($fname = readdir($dh)) !== false) {
if (preg_match($exp, $fname)) {
$stat = stat("$dir/$fname");
$r[$fname] = ($how == 'name')? $fname: $stat[$how];
}
}
closedir($dh);
if ($desc) {
arsort($r);
}
else {
asort($r);
}
}
return(array_keys($r));
}
$r = myscandir('./book/', '/^article[0-9]{4}\.txt$/i', 'ctime', 1);
print_r($r);
files can be sorted on name and stat() attributes, ascending and descending:
name file name
dev device number
ino inode number
mode inode protection mode
nlink number of links
uid userid of owner
gid groupid of owner
rdev device type, if inode device *
size size in bytes
atime time of last access (Unix timestamp)
mtime time of last modification (Unix timestamp)
ctime time of last inode change (Unix timestamp)
blksize blocksize of filesystem IO *
blocks number of blocks allocated
| |