시소당
readdir
(PHP 3, PHP 4 , PHP 5)
readdir -- 디렉토리 핸들에서 엔트리를 읽습니다.
설명
string readdir ( resource dir_handle)
디렉토리에서 다음 파일의 파일명을 반환합니다. 반환하는 파일명의 순서는 파일시스템에 저장한 순서입니다.
readdir()의 반환값은 아래 예제체럼 확인해야 하는 점에 주의하십시오. 반환값이 FALSE와 완전히 동일한지 (형까지 일치--자세한 정보는 비교 연산자를 참고하십시오) 확인하고 있습니다. 이렇게 하지 않으면, FALSE로 인식하는 디렉토리 엔트리에서 루프가 멈춥니다. (예. 디렉토리 이름이 "0")
예 1. 디렉토리 안의 모든 파일 목록
<?php
// !== 은 4.0.0-RC2까지 존재하지 않았던 점에 주의하십시오.
if (
$handle = opendir('/path/to/files')) {
echo "Directory handle:
$handle\n";
echo "Files:\n";
/* 디렉토리 안을 루프하는 올바른 방법입니다. */
while (false !== (
$file = readdir(
$handle))) {
echo "
$file\n";
}
/* 디렉토리 안을 루프하는 *틀린* 방법입니다. */
while (
$file = readdir(
$handle)) {
echo "
$file\n";
}
closedir(
$handle);
}
?>
readdir()이 .과 ..을 반환하는 점에 주의하십시오. 이들이 필요하지 않으면 간단히 제거할 수 있습니다: 예 2. .과 ..을 제외한 현재 디렉토리의 모든 파일 목록
<?php
if (
$handle = opendir('.')) {
while (false !== (
$file = readdir(
$handle))) {
if (
$file != "." &&
$file != "..") {
echo "
$file\n";
}
}
closedir(
$handle);
}
?>
참고: is_dir(), glob().
add a note User Contributed Notes
readdir
Alex M
28-Jun-2005 12:37
A shorter and simpler version of twista no[at]
$pam rocards
$pam[dot]no de
code to first display all folders sorted, and THEN all files sorted. Just like windows.
<?php
$path =
$_SERVER[DOCUMENT_ROOT]."/old/";
$dh = @opendir(
$path);
while (false !== (
$file=@readdir(
$dh)))
{
if (substr(
$file,0,1)!=".") #skip anything that starts with a '.'
{ #i.e.:('.', '..', or any hidden file)
if (is_dir(
$path.
$file))
$dirs[]=
$file.'/'; #put directories into dirs[] and append a '/' to differentiate
else
$files[]=
$file; #everything else goes into files[]
}
}
@closedir(
$dh);
if (
$files)
natcasesort(
$files); #natural case insensitive sort
if (
$dirs)
natcasesort(
$dirs);
$files=array_merge(
$dirs,
$files); #merge dirs[] and files[] into files with dirs first
foreach (
$files as
$file) #that's all folks, display sorted all folders and files
echo "
$file<br>\n";
?>
matthew dot panetta at gmail dot com
16-May-2005 08:44
Here is a simple directory walker class that does not use recursion.
<?
class DirWalker {
function go (
$dir) {
$dirList[] =
$dir;
while ( (
$currDir = array_pop(
$dirList)) !== NULL ) {
$dir = opendir(
$currDir);
while((false!==(
$file=readdir(
$dir)))) {
if(
$file =="." ||
$file == "..") {
continue;
}
$fullName =
$currDir . DIRECTORY_SEPARATOR .
$file;
if ( is_dir (
$fullName ) ) {
array_push (
$dirList,
$fullName );
continue;
}
$this->processFile (
$file,
$currDir);
}
closedir(
$dir);
}
}
function processFile (
$file,
$dir ) {
print ("DirWalker::processFile =>
$file,
$dir\n");
}
}
?>
twista no[at]
$pam rocards
$pam[dot]no de
12-Apr-2005 06:18
I used nagash's script from below fo myself, and enhanced it.
It will now first display all folders sorted, and THEN all files sorted. Just like windows :-)
There is also a small function for hiding secret files.
Just set
$rootdir to 1 in the root dir, and leave it 0 in all subdirs.
<?
$the_file_array = Array();
$the_folder_array = Array();
$handle = opendir('./');
while (false !== (
$file = readdir(
$handle))) {
if (
$file != ".") {
if (filetype(
$file) == "file") {
$the_file_array[] =
$file; } else if (filetype(
$file) == "dir") {
$the_folder_array[] =
$file; }
}
}
closedir(
$handle);
sort (
$the_file_array);
reset (
$the_file_array);
sort (
$the_folder_array);
reset (
$the_folder_array);
while (list (
$key,
$val) = each (
$the_folder_array)) {
if ((
$val != ".") && (!fnmatch("*.php*",
$val))) {
if ((fnmatch("~*",
$val)) || (fnmatch("~some_thing",
$val))) {
// CASE: An outcommented file. - Syn: "~<filename>" - Exp: "~nottobeseen.txt"
echo "** SECRET FILE **<br>";
}else{
if (
$val == "..") {
if (
$rootdir == "1") {
// CASE: Don't show the way upward if this is the root directory.
// Root Directory, do nothing.
}else{
// CASE: Show the ".." to go back if this is NOT the root directory.
echo '<a href="'.
$val.'/">/'.
$val.'/</a><br>';
}
}else{
// CASE: All normal folders. No ".." and no ".".
echo '<a href="'.
$val.'/">/'.
$val.'/</a><br>';
}
}
}
}
while (list (
$key,
$val) = each (
$the_file_array)) {
if ((
$val != ".") && (!fnmatch("*.php*",
$val))) {
if ((fnmatch("*~~*",
$val)) || (fnmatch("~cheat_sux^hi",
$val))) {
// CASE: An outcommented file. - Syn: "~<filename>" - Exp: "~nottobeseen.txt"
echo "** SECRET FILE **<br>";
}else{
echo '<a href="'.
$val.'">'.
$val.'</a><br>';
}
}
}
?>
davidstummer at yahoo dot co dot uk
02-Apr-2005 09:32
This is a very simple function which returns an array of image files when given a directory name - enjoy!
function listImages(
$dirname=".") {
$ext = array("jpg", "png", "jpeg", "gif");
$files = array();
if(
$handle = opendir(
$dirname)) {
while(false !== (
$file = readdir(
$handle)))
for(
$i=0;
$i<sizeof(
$ext);
$i++)
if(strstr(
$file, ".".
$ext[
$i]))
$files[] =
$file;
closedir(
$handle);
}
return(
$files);
}
steve at stevedix dot de
15-Feb-2005 06:12
IT IS VITALLY IMPORTANT that when using opendir and then scanning with readdir, that you test opendir to see if it has returned a valid pointer.
The following code does not :
<?php
$dir = opendir(
$mydir);
while((false!==(
$file=readdir(
$dir))))
if(
$file!="." and
$file !="..")
unlink(
$mydir.'/'.
$file);
closedir(
$dir);
?>
if
$mydir is not a valid directory resource (for example, the directory in question has been deleted), then the code will loop infinitely. Of course, it'll stop eventually if you have set a max execution time, but in the meantime it will visibly slow the server.
lars ( at ) noname00 dot org
16-Jan-2005 06:38
One minor change to my script below (I forgot the wrong function in the script):
To sort the arrays into alphabetical order, like I want, replace the arsort() functions with just sort(), ie:
<?php
# Sort and reset the arrays
asort(
$d_arr ); reset(
$d_arr );
asort(
$f_arr ); reset(
$f_arr );
?>
change to:
<?php
# Sort and reset the arrays
sort(
$d_arr ); reset(
$d_arr );
sort(
$f_arr ); reset(
$f_arr );
?>
Cheers!
lars ( at ) noname00 dot org
07-Jan-2005 03:06
The directory listing snippets here weren't quite what I needed, so I made this. It's collected from bits of various user notes here, so props y'all etc.
This pushes directories and files into separate arrays, sorts and prints out hyperlinked and with size information. It omits any unix dotfiles (.bashrc and the like) which are hidden. This can be changed by removing the
&&
$file[0] != "."
part from the if clause.
Example output:
---
Current path: ./example/path
Parent directory
[ D ] alpha_dir/
[ D ] beta_dir/
[ D ] zigzag_dir/
[ F ] huge.db 123.4 MB
[ F ] index.php 123 bytes
[ F ] small.db 12.3 KB
---
<?php
# Do we have a path? if not, it's the current directory
$path =
$_GET["path"];
if( !isset(
$path ) ||
$path == "" ) {
$path = ".";
}
# Print out for navigation
print "Current path: <b>" .
$path . "</b><br />";
# Initialise list arrays, directories and files separately and array counters for them
$d_arr = array();
$d = 0;
$f_arr = array();
$f = 0;
# Open possibly available directory
if( is_dir(
$path ) ) {
if(
$handle = opendir(
$path ) ) {
while( false !== (
$file = readdir(
$handle ) ) ) {
# Make sure we don't push parental directories or dotfiles (unix) into the arrays
if(
$file != "." &&
$file != ".." &&
$file[0] != "." ) {
if( is_dir(
$path . "/" .
$file ) )
# Create array for directories
$d_arr[
$d++] =
$file;
else
# Create array for files
$f_arr[
$f++] =
$file;
}
}
}
}
# Wrap things up if we're in a directory
if( is_dir(
$handle ) ) closedir(
$handle );
# Sort and reset the arrays
asort(
$d_arr ); reset(
$d_arr );
asort(
$f_arr ); reset(
$f_arr );
# Print a parent directory link
$d_prev = substr(
$path, 0, ( strrpos( dirname(
$path . "/." ), "/" ) ) );
print "<a href=\"?path=" .
$d_prev . "\"> Parent directory </a><br />\n";
# Print the directory list
for(
$i=0;
$i < count(
$d_arr );
$i++ ) {
# Print with query string
print "[ D ] <a href=\"?path=" .
$path . "/" .
$d_arr[
$i] . "\">" .
$d_arr[
$i] . "</a>/<br />\n";
}
# Print file list
for(
$i=0;
$i < count(
$f_arr );
$i++ ) {
# Only print path and filename
print "[ F ] <a href=\"" .
$path . "/" .
$f_arr[
$i] . "\"> " .
$f_arr[
$i] . "</a>";
# We may want a file size. NOTE: needs
$path to stat
if( filesize(
$path . "/" .
$f_arr[
$i] ) >= 1024 ) {
# Size in kilobytes
print " " . round( filesize(
$path . "/" .
$f_arr[
$i] ) / 1024, 1 ) . " KB<br />\n";
} elseif( filesize(
$path . "/" .
$f_arr[
$i] ) >= 1048576 ) {
# Size in megabytes
print " " . round( filesize(
$path . "/" .
$f_arr[
$i] ) / 1024 / 1024, 1 ) . " MB<br />\n";
} else {
# Size in bytes
print " " . filesize(
$path . "/" .
$f_arr[
$i] ) . " bytes<br />\n";
}
}
?>
Anton Fors-Hurd鮠<atombomben at telia dot com>
21-Dec-2004 06:10
My download function:
<?
function download(
$dir) {
if (isset(
$_GET['download'])) {
header("Content-Type: octet/stream");
header("Content-Disposition: attachment; filename=" . basename(
$_GET['download']));
echo file_get_contents(
$_GET['download']);
} else {
if (
$open = opendir(
$dir)) {
while (false !== (
$file = readdir(
$open))) {
if (
$file != "." &&
$file != "..") {
if (!is_dir(
$dir .
$file)) {
echo "< <a href=\"?download=" .
$dir .
$file . "\">" .
$file . "</a><br />\n";
} else {
echo "> " .
$file . "<br />\n";
echo "<div style=\"padding-left: 15px;\">";
download(
$dir .
$file . "/");
echo "</div>";
}
}
}
closedir(
$open);
}
}
}
?>
boorick[at]utl[dot]ru
16-Dec-2004 07:07
Simple script which counts directories and files in the set directory.
$path = '/path/to/dir'
if (
$handle = opendir(
$path)) {
while (false !== (
$file = readdir(
$handle))) {
if (
$file != "." &&
$file != "..") {
$fName =
$file;
$file =
$path.'/'.
$file;
if(is_file(
$file))
$numfile++;
if(is_dir(
$file))
$numdir++;
};
};
closedir(
$handle);
};
echo
$numfiles.' files in a directory';
echo
$numdir.' subdirectory in directory';
BY626
07-Dec-2004 07:15
here is a simple directory navigating script i created. files and directories are links and it displays the current directory and the path relative to the file the script is in. it also has a nifty 'up one level' link.
------
<?php
$path =
$_GET['path'];
if(!isset(
$path))
{
$path = ".";
}
if (
$handle = opendir(
$path))
{
$curDir = substr(
$path, (strrpos(dirname(
$path."/."),"/")+1));
print "current directory: ".
$curDir."<br>************************<br>";
print "Path: ".dirname(
$path."/.")."<br>************************<br>";
while (false !== (
$file = readdir(
$handle)))
{
if (
$file != "." &&
$file != "..")
{
$fName =
$file;
$file =
$path.'/'.
$file;
if(is_file(
$file))
{
print "[F] <a href='".
$file."'>".
$fName."</a> ".filesize(
$file)." bytes<br>";
}
if(is_dir(
$file))
{
print "[D] <a href='ex2.php?path=
$file'>
$fName</a><br>";
}
}
}
$up = substr(
$path, 0, (strrpos(dirname(
$path."/."),"/")));
print "[^] <a href='ex2.php?path=
$up'>up one level</a><br>";
closedir(
$handle);
}
?>
------ sample output ------
current directory: kate
************************
Path: ./kate
************************
[F] xyz_file.txt 13005 bytes
[F] mno_file.txt 26327 bytes
[F] abc_file.txt 8640 bytes
[D] k2
[^] up one level
Jason Wong
13-Nov-2004 07:20
Everyone seems to be using recursion for trawling through subdirectories. Here's a function that does not use recursion.
<?php
function list_directory(
$dir) {
$file_list = '';
$stack[] =
$dir;
while (
$stack) {
$current_dir = array_pop(
$stack);
if (
$dh = opendir(
$current_dir)) {
while ((
$file = readdir(
$dh)) !== false) {
if (
$file !== '.' AND
$file !== '..') {
$current_file = "{
$current_dir}/{
$file}";
if (is_file(
$current_file)) {
$file_list[] = "{
$current_dir}/{
$file}";
} elseif (is_dir(
$current_file)) {
$stack[] =
$current_file;
}
}
}
}
}
return
$file_list;
}
?>
I also did a rudimentary benchmark against Rick's function (no reason in particular why I chose Rick's, it was just the latest) and the result is that using recursion results in about 50% longer execution time.
Details of benchmark:
Directory contains 64 subdirectories and about 117,000 files. Each function was executed 100 times in a for-loop and the average time per iteration was calculated. The result is 3.77 seconds for the non-recursive function and 5.65 seconds for the recursive function.
Rick at Webfanaat dot nl
29-Sep-2004 07:47
Yet another recursive directory lister :P
Why did I create it?
I like to keep things small, and it seems like all the scripts around here are a lot bigger and more complex while they produce the same (or nearly the same) output.
This one creates a multidimensional array with the folders as associative array and the files as values.
It puts the name of the folders and files in it, not the complete path (I find that annoying but its easy to change that if you prefer it with the path).
And I used a for loop instead of a while loop like everyone around here does.
Why?
1. I just like for loops.
2. Everyone else uses a while loop.
<?php
function ls(
$dir){
$handle = opendir(
$dir);
for(;(false !== (
$readdir = readdir(
$handle)));){
if(
$readdir != '.' &&
$readdir != '..'){
$path =
$dir.'/'.
$readdir;
if(is_dir(
$path))
$output[
$readdir] = ls(
$path);
if(is_file(
$path))
$output[] =
$readdir;
}
}
return isset(
$output)?
$output:false;
closedir(
$handle);
}
print_r(ls('.'));
?>
PS: if you don't need the files in it then you can just comment out the "if(is_file....." part.
nagash at trumna dot pl
06-Jun-2004 02:11
Simplified recursive file listing (in one directory), with links to the files.
<?
$the_array = Array();
$handle = opendir('prace/.');
while (false !== (
$file = readdir(
$handle))) {
if (
$file != "." &&
$file != "..") {
$the_array[] =
$file;
}
}
closedir(
$handle);
sort (
$the_array);
reset (
$the_array);
while (list (
$key,
$val) = each (
$the_array)) {
echo "<a href=prace.php?id=
$val>
$val</a><br>";
}
?>
I'm not sure, if you were talking about that, but anyway I think somebody might find it usefull :-)
phpuser at php dot net
05-Jun-2004 12:28
Simplified recursive directory listing. Returns FolderListing object which contains an array with all the directories and files.
<?php
class FolderListing {
var
$newarr = array();
function loop(
$stack) {
if(count(
$stack) > 0) {
$arr = array();
foreach(
$stack as
$key =>
$value) {
array_push(
$this->newarr,
$stack[
$key]);
if (
$dir = @opendir(
$stack[
$key])) {
while ((
$file = readdir(
$dir)) !== false) {
if ((
$file != '.') && (
$file != '..')) {
array_push(
$arr,
$stack[
$key].'/'.
$file);
}
}
}
closedir(
$dir);
}
$this->loop(
$arr);
} else {
$sorted = sort(
$this->newarr);
return(
$sorted);
}
}
}
$start = new FolderListing;
$base = array("baseDir");
$start->loop(
$base);
foreach(
$start->newarr as
$value) {
echo
$value."<br />";
}
?>
Add the following code around the array_push line to just check for directories:
if(is_dir(
$stack[
$key].'/'.
$file)) {
}
jw5_feedback at comcast dot net
20-May-2004 06:30
Ok you have seen a bunch of them recursive directory functions, but heres mine that loads them all into an array and emdeded arrays that contain all the file names.
/*********************************************/
$main_dir = "downloads";
$A_main = Array(
$main_dir,);
$start =&
$A_main;
$j = 0;
function dir_recurse(
$dir,&
$wia) {
$i = 1;
if(
$handle = opendir(
$dir)) {
while(false !== (
$file = readdir(
$handle))) {
if(
$file != "." &&
$file != ".." ) {
if(is_dir(
$dir."/".
$file) == true) {
$fullpath =
$dir."/".
$file;
array_push(
$wia,array(
$file));
dir_recurse(
$fullpath,
$wia[
$i]);
$i++;
}
else {
$fullpath =
$dir."/".
$file;
array_push(
$wia,
$fullpath);
$i++;
}
}
}
closedir(
$handle);
}
}
dir_recurse(
$main_dir,
$start);
/********************************************/
wia stands for "where it's at" in relation to being in a directory.
paulg at i (hyphen) labs dot co dot uk
23-May-2004 02:06
Simplified recursive directory listing. Returns FolderListing object which contains an array with all the directories and files.
<?php
class FolderListing {
var
$newarr = array();
function loop(
$stack) {
if(count(
$stack) > 0) {
$arr = array();
foreach(
$stack as
$key =>
$value) {
array_push(
$this->newarr,
$stack[
$key]);
if (
$dir = @opendir(
$stack[
$key])) {
while ((
$file = readdir(
$dir)) !== false) {
if ((
$file != '.') && (
$file != '..')) {
array_push(
$arr,
$stack[
$key].'/'.
$file);
}
}
}
closedir(
$dir);
}
$this->loop(
$arr);
} else {
$sorted = sort(
$this->newarr);
return(
$sorted);
}
}
}
$start = new FolderListing;
$base = array("baseDir");
$start->loop(
$base);
foreach(
$start->newarr as
$value) {
echo
$value."<br />";
}
?>
Add the following code around the array_push line to just check for directories:
if(is_dir(
$stack[
$key].'/'.
$file)) {
}
jw5_feedback at comcast dot net
21-May-2004 10:30
Ok you have seen a bunch of them recursive directory functions, but heres mine that loads them all into an array and emdeded arrays that contain all the file names.
/*********************************************/
$main_dir = "downloads";
$A_main = Array(
$main_dir,);
$start =&
$A_main;
$j = 0;
function dir_recurse(
$dir,&
$wia) {
$i = 1;
if(
$handle = opendir(
$dir)) {
while(false !== (
$file = readdir(
$handle))) {
if(
$file != "." &&
$file != ".." ) {
if(is_dir(
$dir."/".
$file) == true) {
$fullpath =
$dir."/".
$file;
array_push(
$wia,array(
$file));
dir_recurse(
$fullpath,
$wia[
$i]);
$i++;
}
else {
$fullpath =
$dir."/".
$file;
array_push(
$wia,
$fullpath);
$i++;
}
}
}
closedir(
$handle);
}
}
dir_recurse(
$main_dir,
$start);
/********************************************/
wia stands for "where it's at" in relation to being in a directory.
abanner at netachievement dot co dot uk
12-May-2004 09:04
Whilst writing a script to check a directory to see whether certain files existed, I used an original example from this page and modified so that in the first loop that checks the directory, there is a second that looks at a database recordset and tries to find the matches.
I found an issue that I have not yet solved. I am not a PHP guru, so I might be missing something here.
In the parent loop,
$file is set correctly. As soon as your progress to the inner loop,
$file becomes just a full stop (.) - I've no idea why.
<?
if (
$handle = opendir(
$path)) :
while (false !== (
$file = readdir(
$handle))) :
// Here
$file is set correctly
while(
$row = @ mysql_fetch_array(
$result)) :
// Here
$file is set to .
endwhile;
endwhile;
closedir(
$handle);
endif;
?>
phpnet at public dot buyagun dot org
06-May-2004 09:10
Another simple recusive directory listing function.
<?php
$BASEDIR="/tmp";
function recursedir(
$BASEDIR) {
$hndl=opendir(
$BASEDIR);
while(
$file=readdir(
$hndl)) {
if (
$file=='.' ||
$file=='..') continue;
$completepath="
$BASEDIR/
$file";
if (is_dir(
$completepath)) {
# its a dir, recurse.
recursedir(
$BASEDIR.'/'.
$file);
print "DIR:
$BASEDIR/
$file<br>\n";
} else {
# its a file.
print "FILE:
$BASEDIR/
$file<br>\n";
}
}
}
recursedir(
$BASEDIR);
?>
juanma at teslg dot com
06-Apr-2004 12:13
This is a recursive function using readdir. It creates an Dir tree called Directorio on memory.
class Directorio
{
var
$path="";
var
$arrPathFich=array();
function Directorio()
{
if(func_num_args()==1)
{
$arr=func_get_args();
$obj=
$arr[0];
$this->path=
$obj->path;
$this->arrPathFich=
$obj->arrPathFich;
}
}
}//Directorio
/* *** FUNCIONES *** */
function getArbolDir(
$dir)
{
$direct=new Directorio();
$direct->path=
$dir;
$i=0;
$dir.='/';
if(is_dir(
$dir))
{
$pdir=opendir(
$dir);
while(FALSE !== (
$nomfich=readdir(
$pdir)))
{
if(
$nomfich!="." &&
$nomfich!="..")
if(is_dir(
$dir.
$nomfich))
$direct->arrPathFich[
$i++]=new Directorio(getArbolDir(
$dir.
$nomfich));
else
$direct->arrPathFich[
$i++]=
$dir.
$nomfich;
}
closedir(
$pdir);
}
return
$direct;
}//getArbolDir
gehring[at-no-2-spam]egotec.com
18-Mar-2004 11:13
If you want to walk through a directory and want to use a callback function for every dir or file you get you can use this
its like the perl File::Find method "find"
<?php
function find(
$callback,
$dir=Array())
{
foreach(
$dir as
$sPath) {
if (
$handle = opendir(
$sPath)) {
while (false !== (
$file = readdir(
$handle))) {
if(
$file !== "." &&
$file !== "..") {
if(is_dir(
$sPath."/".
$file)) {
eval("
$callback(\"
$sPath\", \"
$file\");");
find(
$callback, Array(
$sPath."/".
$file));
} else {
eval("
$callback(\"
$sPath\", \"
$file\");");
}
}
}
closedir(
$handle);
}
}
}
function walk(
$dir,
$file)
{
print ">>>
$dir/
$file\n";
}
find("walk", Array("/etc"));
?>
hope it helps
jg
josh at duovibe dot com
13-Mar-2004 08:31
After looking for awhile for a function which retrieves a folder listing based on certain criteria (return folder, files, or both; search recursively or not), I decided to write my own. Maybe somebody out there will find it helpful.
Currently, it returns a flat list, but that can changed to return a nested list by editing the line:
$file_list = array_merge(
$file_list, directory_list(
$path ...
to
$file_list[] = directory_list(
$path ...
function directory_list(
$path,
$types="directories",
$recursive=0) {
// get a list of just the dirs and turn the list into an array
// @path starting path from which to search
// @types can be "directories", "files", or "all"
// @recursive determines whether subdirectories are searched
if (
$dir = opendir(
$path)) {
$file_list = array();
while (false !== (
$file = readdir(
$dir))){
// ignore the . and .. file references
if (
$file != '.' &&
$file != '..') {
// check whether this is a file or directory and whether we're interested in that type
if ((is_dir(
$path."/".
$file)) && ((
$types=="directories") || (
$types=="all"))) {
$file_list[] =
$file;
// if we're in a directory and we want recursive behavior, call this function again
if (
$recursive) {
$file_list = array_merge(
$file_list, directory_list(
$path."/".
$file."/",
$types,
$recursive));
}
} else if ((
$types == "files") || (
$types == "all")) {
$file_list[] =
$file;
}
}
}
closedir(
$dir);
return
$file_list;
} else {
return false;
}
}
Angryman Bluts
24-Feb-2004 02:52
If anyone uses the posted script of mikael[at]limpreacher[d0t]com
...
U should use direcho(
$path.file.'/');
rockinmusicgv at y_NOSPAM_ahoo dot com
28-Nov-2003 04:24
Mainly an extension of the other drop down directory lists
Except it should handle hidden directories (unix)
function getdirs(
$directory,
$select_name,
$selected = "") {
if (
$dir = @opendir(
$directory)) {
while ((
$file = readdir(
$dir)) !== false) {
if (
$file != ".." &&
$file != ".") {
if(is_dir(
$file)) {
if(!(
$file[0] == '.')) {
$filelist[] =
$file;
}
}
}
}
closedir(
$dir);
}
echo "<select name=\"
$select_name\">";
asort(
$filelist);
while (list (
$key,
$val) = each (
$filelist)) {
echo "<option value=\"
$val\"";
if (
$selected ==
$val) {
echo " selected";
}
echo ">
$val</option>";
}
echo "</select>";
}
Steve Main
26-Nov-2003 01:53
This will allow you to print out a total recursive directory listing no files just directories for possible tree menues that need folder lists.
<?php
$DirectoriesToScan = array(realpath('/var/www/axim.caspan.com/Software/'));
$DirectoriesScanned = array();
while (count(
$DirectoriesToScan) > 0) {
foreach (
$DirectoriesToScan as
$DirectoryKey =>
$startingdir) {
if (
$dir = @opendir(
$startingdir)) {
while ((
$file = readdir(
$dir)) !== false) {
if ((
$file != '.') && (
$file != '..')) {
$RealPathName = realpath(
$startingdir.'/'.
$file);
if (is_dir(
$RealPathName)) {
if (!in_array(
$RealPathName,
$DirectoriesScanned) && !in_array(
$RealPathName,
$DirectoriesToScan)) {
$DirectoriesToScan[] =
$RealPathName;
$DirList[] =
$RealPathName;
}
}
}
}
closedir(
$dir);
}
$DirectoriesScanned[] =
$startingdir;
unset(
$DirectoriesToScan[
$DirectoryKey]);
}
}
$DirList = array_unique(
$DirList);
sort(
$DirList);
foreach (
$DirList as
$dirname) {
echo
$dirname."<br>";
}
?>
bermi_ferrer {:at:} bermi {:dot:} org
07-Nov-2003 09:09
Simple function to recursively load given directory (/full_path/to_directory/) into an array.
function akelos_recursive_dir(
$directorio)
{
if (
$id_dir = opendir(
$directorio)){
while (false !== (
$archivo = readdir(
$id_dir))){
if (
$archivo != "." &&
$archivo != ".."){
if(is_dir(
$directorio.
$archivo)){
$resultado[
$archivo] = akelos_recursive_dir(
$directorio.
$archivo."/");
}
else{
$resultado[] =
$archivo;
}
}
}
closedir(
$id_dir);
}
return
$resultado;
}
mikael[at]limpreacher[d0t]com
06-Nov-2003 10:28
I don't know if I haven't had the patience to go trough enough notes, but I didn't find any tip on how to recurively get a directory listing (show subdirectories too), so, as many other, I wrote one. Hopefully this will help someone.
<?php
function direcho(
$path) {
if (
$dir = opendir(
$path)) {
while (false !== (
$file = readdir(
$dir))){
if (is_dir(
$path.
$file)) { // if it's a dir, check it's contents too
if (
$file != '.' &&
$file != '..') { // ...but dont go recursive on '.' and '..'
echo '<li><b>' .
$file . '</b></li><ul>';
direcho(
$path.
$file); // This is a feature that surprised me, it IS possible to call
// the function itself from inside that function.
echo '</ul>';
}
else { //if it IS '.' or '..' , just output.
echo '<li><b>' .
$file . '</b></li>';
}
}
else { //if it's not a dir, just output.
echo '<li>' .
$file . '</li>';
}
}
closedir(
$dir);
}
}
direcho('/path/to/home/dir/'); // somehow only the absolute path ('/home/yourhomedir/public_html/testdir/') worked for me...
?>
Yippii! my first contribution to this site!
php at trap-door dot co dot uk
29-Sep-2003 12:22
An extension to the sorted file list in a drop-down box posted by paCkeTroUTer at iprimus dot com dot au.
Takes the directory, the "name" of the form element it produces, and optionally, a filename. If the file name is in the list, it will be the default selection in the list.
<?
function listfiles(
$directory,
$select_name,
$selected = "") {
if (
$dir = @opendir(
$directory)) {
while ((
$file = readdir(
$dir)) !== false) {
if (
$file != ".." &&
$file != ".") {
$filelist[] =
$file;
}
}
closedir(
$dir);
}
echo "<select name=\"
$select_name\">";
asort(
$filelist);
while (list (
$key,
$val) = each (
$filelist)) {
echo "<option value=\"
$val\"";
if (
$selected ==
$val) {
echo " selected";
}
echo ">
$val</option>";
}
echo "</select>";
}
?>
Hope this helps someone.
alfred-baudisch at bol dot com dot br
18-Jul-2003 02:27
I use the function below in my site, is good if you wanna only images files on the filename array.
function GetFileList(
$dirname,
$extensoes = FALSE,
$reverso = FALSE)
{
if(!
$extensoes) //EXTENSIONS OF FILE YOU WANNA SEE IN THE ARRAY
$extensoes = array("jpg", "png", "jpeg", "gif");
$files = array();
$dir = opendir(
$dirname);
while(false !== (
$file = readdir(
$dir)))
{
//GET THE FILES ACCORDING TO THE EXTENSIONS ON THE ARRAY
for (
$i = 0;
$i < count(
$extensoes);
$i++)
{
if (eregi("\.".
$extensoes[
$i] ."$",
$file))
{
$files[] =
$file;
}
}
}
//CLOSE THE HANDLE
closedir(
$dirname);
//ORDER OF THE ARRAY
if (
$reverso) {
rsort(
$files);
} else {
sort(
$files);
}
return
$files;
}
web at fischenich dot org
16-Jul-2003 12:11
Why not sorting by filemtime like this?
$handle=opendir(
$fPath);
while (
$file = readdir(
$handle))
{
if(
$file=='.'||
$file=='..')
continue;
if (preg_match("/\.(esp|xml)$/",
$file)){
$filetlist [
$file] = filemtime (
$fPath.'/'.
$file);
}
}
asort(
$filetlist);
while (list (
$key,
$val) = each (
$filetlist))
{
echo
$key;
}
thebitman at attbi dot com
30-Apr-2003 07:29
On sorting by date- no, you can't just use an associative array since some things /will/ be created on the same second. No reason why you can't append the filename to the time, though! (used md5() to kill any weird characters in a unique way)
$dirpath = getcwd() . "/";
$dir = opendir(
$dirpath);
$files = array();
while (
$file = readdir(
$dir)) {
$localpath =
$dirpath.
$file;
if (is_file(
$localpath)) {
$key = filemtime(
$localpath).md5(
$file);
$files[
$key] =
$file;
}
}
ksort(
$files);
foreach (
$files as
$file) {
echo "
$file<br>";
}
paCkeTroUTer at iprimus dot com dot au
25-Apr-2003 08:06
This is an example of how to sort directories alphabetically into a drop down list:
<?
if (
$dir = @opendir("products"))
{
while ((
$file = readdir(
$dir)) !== false)
{
if(
$file != ".." &&
$file != ".")
{
$filelist[] =
$file;
}
}
closedir(
$dir);
}
?>
<form>
<select name="selected_dir" >
<?php
asort(
$filelist);
while (list (
$key,
$val) = each (
$filelist))
{
echo "<option>
$val</option>";
}
?>
</select>
</form>
06-Mar-2003 12:34
Here is a function that will recursively copy a file into every directory within a specified directory, unless the directory is in an optional third parameter, an array with a list of directory names to skip. It will also print whether it copied each item it expected to.
Also, if you try to copy a file to itself in PHP, you end up with an empty file. To alleviate this, there is a fourth parameter, also optional, which is the number of levels to skip when copying files. The default is 0, which will only skip the directory specified in
$dir, so that a call using the file's directory will work properly. I would not recommend calling this function with a directory higher up the tree than
$file's.
<?php
function copyintodir (
$file,
$dir,
$skip = array(''),
$level_count = 0) {
if (count(
$skip) == 1) {
$skip = array("
$skip");
}
if (!@(
$thisdir = opendir(
$dir))) {
print "could not open
$dir<br />";
return;
}
while (
$item = readdir(
$thisdir) ) {
if (is_dir("
$dir/
$item") && (substr("
$item", 0, 1) != '.') && (!in_array(
$item,
$skip))) {
copyintodir(
$file, "
$dir/
$item",
$skip,
$level_count + 1);
}
}
if (
$level_count > 0) {
if (@copy(
$file, "
$dir/
$file")) {
print "Copied
$file into
$dir/
$file<br />\n";
} else {
print "Could not copy
$file into
$dir/
$file<br />\n";
}
}
}
?>
You can call it using a function call such as this:
copyintodir ('index.php', '.', 'images');
php at silisoftware dot com
31-Jan-2003 03:16
Yet another recursive directory listing script. This one returns a list of all absolute filenames (files only, no directories) in or below the directory first specified in
$DirectoriesToScan.
$DirectoriesToScan = array(realpath('.'));
$DirectoriesScanned = array();
while (count(
$DirectoriesToScan) > 0) {
foreach (
$DirectoriesToScan as
$DirectoryKey =>
$startingdir) {
if (
$dir = @opendir(
$startingdir)) {
while ((
$file = readdir(
$dir)) !== false) {
if ((
$file != '.') && (
$file != '..')) {
$RealPathName = realpath(
$startingdir.'/'.
$file);
if (is_dir(
$RealPathName)) {
if (!in_array(
$RealPathName,
$DirectoriesScanned) && !in_array(
$RealPathName,
$DirectoriesToScan)) {
$DirectoriesToScan[] =
$RealPathName;
}
} elseif (is_file(
$RealPathName)) {
$FilesInDir[] =
$RealPathName;
}
}
}
closedir(
$dir);
}
$DirectoriesScanned[] =
$startingdir;
unset(
$DirectoriesToScan[
$DirectoryKey]);
}
}
$FilesInDir = array_unique(
$FilesInDir);
sort(
$FilesInDir);
foreach (
$FilesInDir as
$filename) {
echo
$filename."\n";
}
nick_vollebergh at hotmail dot com
07-Jan-2003 05:53
This is a good way to put all your files from a directory in an arry, and echo them on your page.
<?php
$the_array = Array();
$handle = opendir('.');
while (false !== (
$file = readdir(
$handle))) {
if (
$file != "." &&
$file != "..") { /* as descripted below: these "files" will not be added to the array */
$the_array[] =
$file;
}
}
closedir(
$handle);
foreach (
$the_array as
$element) {
echo "
$element @br /@ \n";
}
?>
php dot net at phor dot net
05-Jan-2003 08:34
This is equivilent to (and more modular than):
$file_list=explode("\n",`find
$path -type f`)
function walk_dir(
$path)
{
if (
$dir = opendir(
$path)) {
while (false !== (
$file = readdir(
$dir)))
{
if (
$file[0]==".") continue;
if (is_dir(
$path."/".
$file))
$retval = array_merge(
$retval,walk_dir(
$path."/".
$file));
else if (is_file(
$path."/".
$file))
$retval[]=
$path."/".
$file;
}
closedir(
$dir);
}
return
$retval;
}
-- Full Decent
rolandfx_SPAMMENOT_ at bellsouth dot net
11-Nov-2002 06:04
While I won't make any claims as to its efficiency, this modified version of me@infinito.dk's script above does do several things the previous one doesn't. It will display jpegs using the .jpeg extension, and will not show double-extended files (foo.jpg.bar), nor will it show non-image files with an extension in their name, like mygif.html.
<?
function CheckExt(
$filename,
$ext) {
$passed = FALSE;
$testExt = "\.".
$ext."$";
if (eregi(
$testExt,
$filename)) {
$passed = TRUE;
}
return
$passed;
}
//Define an array of common extensions.
$exts = array("gif","jpg$|\\.jpeg","png","bmp");
echo "<b>Images in this folder:</b>";
$dir = opendir(".");
$files = readdir(
$dir);
while (false !== (
$files = readdir(
$dir))) {
foreach (
$exts as
$value) {
if (CheckExt(
$files,
$value)) {
echo "<a href=\"
$files\">
$files</a>\n";
$count++; //Keep track of the total number of files.
break; //No need to keep looping if we've got a match.
}
}
}
echo
$count." image(s) found in this directory.\n";
echo "<a href=\"".
$_SERVER["PHP_SELF"]."\">Refresh</a>\n";
//Be a good script and clean up after yourself...
closedir(
$dir);
?>
Silphy@nowhere
08-Nov-2002 12:26
Mod'ed the code a bit. Made it so the dir is selected by dir.php?dir=name . I made it to parse anything starting with "/" "." or "./" so there shouldn't be any security risks when using this.
<?php
$directory =
$_REQUEST["dir"]; // lets fetch the variable: REQUEST works for both, POST and GET methods
if (substr(
$directory, 0, 1) == "/")
$directory = "";
$directory = str_replace ("./", "",
$directory);
$directory = str_replace (".", "",
$directory);
if (
$directory != @
$null) { // lets check if the variable "dir" has something in it, otherwise lets just print out the empty document
if (
$dir = @opendir(
$directory)) { // changed "./" to the directory variable
echo ("Listing contents of <b>
$directory</b><br><br>\n"); // i just added this thing
while ((
$file = readdir(
$dir)) !== false) {
if (
$file != "." &&
$file != "..") {
$location = "
$directory/
$file";
$type = filetype(
$location);
$size = filesize(
$location);
if (is_dir(
$location) == true) {
echo ("
$type - <a href=\"dir.php?dir=
$location\">
$file</a><br>\n");
}
else {
echo ("
$type - <a href=\"
$location\">
$file</a> -
$size Bytes<br>\n");
}
}
}
closedir(
$dir);
}
}
?>
eric.draven[AT]tiscalinet[DOT]it
25-Aug-2002 04:39
Sometimes happens that you need to sort your files by date , but using associative arrays you won't be able to list files that were written in the same second (rarely , but with CMS system it's strangely frequent , doh!). Here's something that may come in hand in such a case. Code CAN really be improved (especially flags), but you can figure out the trick.
$dir = opendir(
$myDir);
while ((
$file = readdir(
$dir)) !== false) {
if (
$file != "." and
$file != "..") {
$fileTime=filemtime(
$docsPath.
$file);
$stillExists = true;
while (
$stillExists) {
$stillExists = validateTs(
$fileTime);
if (!
$stillExists) {
$articlesToProcess[
$fileTime] =
$file;
}
else {
echo("<font color=\"red\" size=\"3\">found ts equals to another key. add 1 second and retry </font><br>");
$fileTime++;
}
}
}
}
krsort(
$articlesToProcess);
# Follow function that do the work
function validateTs(
$fileTime) {
global
$articlesToProcess;
foreach(
$articlesToProcess as
$key =>
$value) {
if (
$fileTime ==
$key) {
return true;
}
}
return false;
}
email me for comments.
Marcus
vjtNO at SPAMazzurra dot org
05-Aug-2002 08:09
to skip hidden files ( on unix ), you can do:
$d = opendir('/path/to/dir');
while((
$f = readdir(
$d)) !== false)
{
if(
$f[0] == '.')
continue;
/* .. your code here .. */
}
mb at michaelborchers dot net
22-Jul-2002 01:16
I tried to find a script that would put all files of one directory(
$img_path) into an array while excluding any subdirectory, not only ".", ".." or "xyz".
Chriss found the solution some threads above.
The following way the slashes are used work for both- LINUX and WIN:
$handle = opendir("
$img_path");
while (false !== (
$file = readdir(
$handle))) {
if(is_file(
$img_path."//".
$file)) {
$filelist[] =
$file;
$anz_files = count(
$filelist);
}
}
phpwizard-at-pech-dot-cz
05-Jul-2002 05:22
It should work, but it'll be better to read section 13.1.3 Cache-control Mechanisms of RFC 2616 available at http://rfc.net/rfc2616.html before you start with confusing proxies on the way from you and the client.
Reading it is the best way to learn how proxies work, what should you do to modify cache-related headers of your documents and what you should never do again. :-)
And of course not reading RFCs is the best way to never learn how internet works and the best way to behave like Microsoft corp.
Have a nice day!
Jirka Pech
rmadriz at expressmail dot net
22-May-2002 08:54
One little note about the is_dir() and is_file() functions when used with readdir().
You better use the fully qualified name when testing, otherwise you could get undesired behavior.
This is the way I'm reading the files form a directory and it is working perfectly.
function get_dir(
$path)
{
if (
$dir = opendir(
$path)) {
/* This is the correct way to loop over the directory. */
while (false !== (
$file = readdir(
$dir)))
{
if (!is_dir(
$path.
$file))
{
//... Your Code Here
}
}
closedir(
$dir);
}
return // whatever you want to return, an array is very usefull
}
Hope this can help,
Rodrigo
captainmike5 at hotmail dot com
22-May-2002 03:47
while working on trying to have readdir sort a listing of directories eiter alphabetically or by modification time i discovered that the readdir() function sorts very similar to the ls -Ul
maybe that will help someone.... ?
FX at yucom dot be
21-May-2002 07:16
Nice recursive code.
It generates and displays a sorted list of all directories, sudirectories and files of your HD.
<?php
function GetFileList(
$path, &
$a)
{
$d=array();
$f=array();
$nd=0;
$nf=0;
$hndl=opendir(
$path);
while(
$file=readdir(
$hndl))
{
if (
$file=='.' ||
$file=='..') continue;
if (is_dir(
$path.'\\'.
$file))
$d[
$nd++]=
$file;
else
$f[
$nf++]=
$file;
}
closedir(
$hndl);
sort(
$d);
sort(
$f);
$n=1;
for (
$i=0;
$i<count(
$d);
$i++)
{
GetFileList(
$path.'\\'.
$d[
$i].'\\',
$a[
$n]);
$a[
$n++][0]=
$d[
$i];
}
for (
$i=0;
$i<count(
$f);
$i++)
{
$a[
$n++]=
$f[
$i];
}
}
function ShowFileList(&
$a,
$N)
{
for (
$i=1;
$i<=count(
$a);
$i++)
if (is_array(
$a[
$i]))
{
echo "<H".
$N.">".
$a[
$i][0].
"</H".
$N.">\n";
ShowFileList(
$a[
$i],
$N+1);
}
else
echo "<Normal>".
$a[
$i].
"</Normal>\n";
}
echo ("Thanks to FX.");
GetFileList("c:\\",
$array);
ShowFileList(
$array, 1);
?>
fridh at gmx dot net
10-Apr-2002 09:41
Someone mentioned the infinite recursion when a symbolic link was found...
tip: is_link() is a nice function :)
berkhout at science dot uva dot nl
21-Feb-2001 09:16
When using stristr(
$filename, ".sql") you will also get filenames of the form filename.sql.backup or .sqlrc
slicky at newshelix dot com
21-Feb-2001 04:52
@dwalet@po-box.mcgill.ca
To search for some specific file or file extension:
Make sure that you put this expression
if (ereg("\.sql",
$file)) instead of (eregi(".sql",
$file)) since the ereg function is familiar with regular expressions
and "the point" (any char) represents a special reg expr. (have a look at reg expr. if you are interested!)
You can combine in the if expression whatever you want for instance if (ereg("\.sql",
$file)) && (strlen(
$file))<100 )
:) of course this doesn't make sooo much sense to use a strlen here, but however this should only be a demonstration
Now the next thing...
Speed issue :
Since the ereg() is capable of reg expr. this means a high speed decrease for you.
So for this simple fileextension search function use the strstr() function instead... which hasn't the power of reg expr. but boast of speed
At least your "if expression" should look something like that: if(stristr(
$file,".sql"))
corbeau at iname dot com
19-Jan-2001 07:00
SIMPLE SOLUTION:
I spent a while trying to figure out how the looping and recursion would work... then I just wrote this.
The simplistic way to get files recursively:
$dir="/directory/";
$a = `find
$dir -depth -type f -print`;
$files = explode ("\n",
$a);
Puts all the files into an array.
Do a basename() on each element to get the file name, and a dirname() to get the directory name.
Viola!
CK1 at wwwtech dot de
16-Nov-2000 11:40
funny thing ;)
if you really read your dirs with subdirs into an array like described above, and there's a link like
ln -s ./ ./recursive
you'll get an endless loop ;)
My suggestion to prevent this is to limit the number of recursion instances: Change the function to
function GetDirArray(
$sPath,
$maxinst,
$aktinst = 0)
{
//Load Directory Into Array
$handle=opendir(
$sPath);
while (
$file = readdir(
$handle))
{
$retVal[count(
$retVal)] =
$file; }
//Clean up and sort
closedir(
$handle);
sort(
$retVal);
while (list(
$key,
$val) = each(
$retVal))
{
if (
$val != "." &&
$val != "..")
{
$path = str_replace("//","/",
$sPath.
$val);
if (is_dir(
$sPath.
$val) && (
$aktinst <
$maxinst ||
$maxinst == 0))
{ GetDirArray(
$sPath.
$val."/",
$maxinst,
$aktinst+1); }
}
}
}
A call could be this:
$dir = GetDirArray("./",0);
Another method could be a regexp, which looks for more than
$maxinst same named subdirs:
if (is_dir(
$sPath.
$val) && !preg_match("/\/(\w+)(\/\\1){
$max,}/",
$sPath.
$val))
{ GetDirArray(
$sPath.
$val."/",
$maxinst); }
instead of the if-construction above.