Documentation on opendir

opendir = Open directory handle

Opens up a directory handle to be used in subsequent closedir(), readdir(), and rewinddir() calls.

path The directory path that is to be opened context For a description of the context parameter, refer to the streams section of the manual.

Usage, params, and more on opendir

resource opendir ( string $path [, resource $context ] )

path The directory path that is to be opened context For a description of the context parameter, refer to the streams section of the manual.

Returns a directory handle resource on success, or FALSE on failure.

Notes and warnings on opendir

Basic example of how to use: opendir

Example #1 opendir() example

<?php
$dir 
"/etc/php5/";

// Open a known directory, and proceed to read its contents
if (is_dir($dir)) {
    if (
$dh opendir($dir)) {
        while ((
$file readdir($dh)) !== false) {
            echo 
"filename: $file : filetype: " filetype($dir $file) . "\n";
        }
        
closedir($dh);
    }
}
?>

The above example will output something similar to:

 filename: . : filetype: dir filename: .. : filetype: dir filename: apache : filetype: dir filename: cgi : filetype: dir filename: cli : filetype: dir 

Other code examples of opendir being used

Breadth-first-search (BFS) for a file or directory (vs. Depth-first-search)
http://en.wikipedia.org/wiki/Breadth-first_search

<?php

// Breadth-First Recursive Directory Search, for a File or Directory
// with optional black-list paths and optional callback function.
//
// $root -- is the relative path to the start-of-search directory
// $file -- is the qualified file name: 'name.ext' EX: 'data.xml'
//    (or) $file -- is the target directory name EX: 'xml_files'
// $callback -- is an optional function name and will be passed all
//    matching paths EX: 'my_func', instead of exiting on first match
// $omit -- is an optional array of exclude paths -- relative to root
//    To use $omit but not $callback, pass NULL as the $callback argument
//
// TESTING VALUES FOLLOW ...

function my_func ( $path ) {
  print
"<strong>$path</strong><br>\n";
}

$root = '../public_html';
$file = 'data.xml';
$callback = 'my_func';
$omit = array( 'include/img', 'include/css', 'scripts' );

//print breadth_first_file_search ( $root, $file );
//print breadth_first_file_search ( $root, $file, $callback );
//print breadth_first_file_search ( $root, $file, NULL, $omit );
print breadth_first_file_search ( $root, $file, $callback, $omit );

function
breadth_first_file_search ( $root, $file, $callback = NULL, $omit = array() ) {
 
$queue = array( rtrim( $root, '/' ).'/' ); // normalize all paths
 
foreach ( $omit as &$path ) { // &$path Req. PHP ver 5.x and later
   
$path = $root.trim( $path, '/' ).'/';
  }
  while (
$base = array_shift( $queue ) ) {
   
$file_path = $base.$file;
    if (
file_exists( $file_path ) ) { // file found
     
if ( is_callable( $callback ) ) {
       
$callback( $file_path ); // callback => CONTINUE
     
} else {
        return
$file_path; // return file-path => EXIT
     
}
    }
    if ( (
$handle = opendir( $base ) ) ) {
      while ( (
$child = readdir( $handle ) ) !== FALSE ) {
        if (
is_dir( $base.$child ) && $child != '.' && $child != '..' ) {
         
$combined_path = $base.$child.'/';
          if ( !
in_array( $combined_path, $omit ) ) {
           
array_push( $queue, $combined_path);
          }
        }
      }
     
closedir( $handle );
    }
// else unable to open directory => NEXT CHILD
 
}
  return
FALSE; // end of tree, file not found
}

?>

A couple of notes on Matt's posts on Windows Network Drives:

Since the system() command writes the output of the executed shell command straight to the output buffer, if you wish to hide the return of the mapping command (i.e. "The command completed succesfully" or an error message) from a web browser, you need to alter the command that is sent to the shell so that the output of that command is hidden.

You probably thinking "why not just use exec()?", and it's a reasonable question, but for some reason it doesn't always work - I guess it's another NT user permissions issue. If you want to guarantee you app will work with no messing around on the host system, use the system() command.

In the Windows command shell, you can hide the output of a command by sending both the output (1) and error (2) messages to "nul" using pipes, in other words ">nul 2>&1" on the end of the command. The username and password order in the "net use..." command needs switching in Matt's post.

Here (http://networkm.co.uk/static/drive.html) is a function I wrote to dynamically choose which drive letter to use, based on what is currently mapped and accessible to PHP.

<?php

// Define the parameters for the shell command
$location = "\\servername\sharename";
$user = "USERNAME";
$pass = "PASSWORD";
$letter = "Z";

// Map the drive
system("net use ".$letter.": \"".$location."\" ".$pass." /user:".$user." /persistent:no>nul 2>&1");

// Open the directory
$dir = opendir($letter.":/an/example/path")

...

?>

Here are two versions of the same function to list all files in a directory tree.

The first one is recursive (calls itself while going through subdirectories) :
<?php
function rec_listFiles( $from = '.')
{
    if(!
is_dir($from))
        return
false;
   
   
$files = array();
    if(
$dh = opendir($from))
    {
        while(
false !== ($file = readdir($dh)))
        {
           
// Skip '.' and '..'
           
if( $file == '.' || $file == '..')
                continue;
           
$path = $from . '/' . $file;
            if(
is_dir($path) )
               
$files += rec_listFiles($path);
            else
               
$files[] = $path;
        }
       
closedir($dh);
    }
    return
$files;
}
?>

The second one is iterative (uses less memory) :
<?php
function listFiles( $from = '.')
{
    if(!
is_dir($from))
        return
false;
   
   
$files = array();
   
$dirs = array( $from);
    while(
NULL !== ($dir = array_pop( $dirs)))
    {
        if(
$dh = opendir($dir))
        {
            while(
false !== ($file = readdir($dh)))
            {
                if(
$file == '.' || $file == '..')
                    continue;
               
$path = $dir . '/' . $file;
                if(
is_dir($path))
                   
$dirs[] = $path;
                else
                   
$files[] = $path;
            }
           
closedir($dh);
        }
    }
    return
$files;
}
?>
The iterative version should be a little faster most of the time, but the big difference is in the memory usage.

Here is also a profiling function (works in php5 only) :
<?php
function profile( $func, $trydir)
{
   
$mem1 = memory_get_usage();
    echo
'<pre>-----------------------
Test run for '
.$func.'() ...
'
; flush();

   
$time_start = microtime(true);
   
$list = $func( $trydir);
   
$time = microtime(true) - $time_start;

    echo
'Finished : '.count($list).' files</pre>';
   
$mem2 = memory_get_peak_usage();

   
printf( '<pre>Max memory for '.$func.'() : %0.2f kbytes
Running time for '
.$func.'() : %0.f s</pre>',
    (
$mem2-$mem1)/1024.0, $time);
    return
$list;
}
?>

A simple piece to open a directory and display any files with a given extension. Great for things like newsletters, score sheets or the like where you just want to make it easy on the user - they just dump in the file with the correct extension and it's done. A link is given to the file which opens up in a new window.

<?php
  $current_dir
= "$DOCUMENT_ROOT"."dirname/";    //Put in second part, the directory - without a leading slash but with a trailing slash!
 
$dir = opendir($current_dir);        // Open the sucker
 
 
echo ("<p><h1>List of available files:</h1></p><hr><br />");
  while (
$file = readdir($dir))            // while loop
   
{
   
$parts = explode(".", $file);                    // pull apart the name and dissect by period
   
if (is_array($parts) && count($parts) > 1) {    // does the dissected array have more than one part
       
$extension = end($parts);        // set to we can see last file extension
       
if ($extension == "ext" OR $extension == "EXT")    // is extension ext or EXT ?
            
echo "<a href=\"$file\" target=\"_blank\"> $file </a><br />";    // If so, echo it out else do nothing cos it's not what we want
       
}
    }
  echo
"<hr><br />";
 
closedir($dir);        // Close the directory after we are done
?>

Hopefully this helps someone else. Returns a list of all the files in the directory and any subdirectories.
Excludes files/folders that are in the $exempt array. Can modifiy it so files aren't passed by reference fairly easily.

<?php

   
function getFiles($directory,$exempt = array('.','..','.ds_store','.svn'),&$files = array()) {
       
$handle = opendir($directory);
        while(
false !== ($resource = readdir($handle))) {
            if(!
in_array(strtolower($resource),$exempt)) {
                if(
is_dir($directory.$resource.'/'))
                   
array_merge($files,
                       
self::getFiles($directory.$resource.'/',$exempt,$files));
                else
                   
$files[] = $directory.$resource;
            }
        }
       
closedir($handle);
        return
$files;
    }

?>

An other way to recursively walk a directory and it's content, applying a callback to each file.

Exemple: Update the last modification time of each file in a folder

<?php

clearstatcache
();

$sourcepath = "C:/WINDOWS/TEMP";

// Replace \ by / and remove the final / if any
$root = ereg_replace( "/$", "", ereg_replace( "[\\]", "/", $sourcepath ));
// Touch all the files from the $root directory
if( false === m_walk_dir( $root, "m_touch_file", true )) {
    echo
"'{$root}' is not a valid directory\n";
}

// Walk a directory recursivelly, and apply a callback on each file
function m_walk_dir( $root, $callback, $recursive = true ) {
   
$dh = @opendir( $root );
    if(
false === $dh ) {
        return
false;
    }
    while(
$file = readdir( $dh )) {
        if(
"." == $file || ".." == $file ){
            continue;
        }
       
call_user_func( $callback, "{$root}/{$file}" );
        if(
false !== $recursive && is_dir( "{$root}/{$file}" )) {
           
m_walk_dir( "{$root}/{$file}", $callback, $recursive );
        }
    }
   
closedir( $dh );
    return
true;
}

// if the path indicates a file, run touch() on it
function m_touch_file( $path ) {
    echo
$path . "\n";
    if( !
is_dir( $path )) {
       
touch( $path );
    }
}

?>

Sometimes the programmer needs to access folder content which has arabic name but the opendir function will return null resources id

for that we must convert the dirname charset from utf-8 to windows-1256 by the iconv function just if the preg_match function detect arabic characters and use " U " additionality to enable multibyte matching

<?php

$dir
= ("./"); // on this file dir
     
// detect if the path has arabic characters and use " u "  optional to enable function to match multibyte characters

if (preg_match('#[\x{0600}-\x{06FF}]#iu', $dir) ) 
{

   
// convert input ( utf-8 ) to output ( windows-1256 )
   
   
$dir = iconv("utf-8","windows-1256",$dir);
   
}

if(
is_dir($dir) )
{
    
    
     if(  (
$dh = opendir($dir) ) !== null  )
     {
   
        
         while ( (
$file = readdir($dh) ) !== false  )
         {
            
            
             echo
"filename: ".$file ." filetype : ".filetype($dir.$file)."<br/>";
            
            
         }
       
     }
    
    
}

?>

In reponse to Tozeiler.  Nice short directory dump.  However, that displays the "." and "..".  This removes those.  It also makes an ordered list in case I needed to be on the phone while looking at the page.  Easy to call out.

<?php

$path
= "your path";
$dh = opendir($path);
$i=1;
while ((
$file = readdir($dh)) !== false) {
    if(
$file != "." && $file != "..") {
        echo
"$i. <a href='$path/$file'>$file</a><br />";
       
$i++;
    }
}
closedir($dh);
?>

The easiest way to get a dir listing and sort it is to exec() out to ls (eg:'ls -t'). But, that is considered "unsafe". My hosting company finally caught me doing it so here is my fastest solution. (Lucky for me each file is created with a Unix Timestamp at the end of the name and no other numbers in it.)

<?php
#exec('ls -t ./images/motion_detection/', $files); # They outlawed exec, so now I have to do it by hand.
if ($handle = opendir('./images/motion_detection/')) {
   
$files=array();
    while (
false !== ($file = readdir($handle))) {
       
$files[$file] = preg_replace('/[^0-9]/', '', $file); # Timestamps may not be unique, file names are.
   
}
   
closedir($handle);
   
arsort($files);
   
$files=array_keys($files);
}
?>

Before you go copying someone's bloat kitchen sink function/class, consider what you have and what you really need.

when you run Apache as a service on your Windows computer, it chooses to run as the LocalSystem account by default (usually SYSTEM). The LocalSystem account has no network privileges whatsoever which, while no doubt a good thing, makes it impossible to access networked resources (such as a shared drive) in your Apache service.

First, you have to change the user the Apache service runs as.
Go to your Services panel (Start -> Run -> "services.msc").
Find the Service labeled Apache, right-click, and hit Properties.
Choose the "Log On" tab.
Presumably you'll see that Apache is set up to run as the Local System Account. You'll want to change this to the second option, "This account", and then fill in the details of the User account you would like Apache to run under.
Some sites tell you to create a special Apache-based user account just for this occasion. It's not a bad idea, but then you have to make sure it has all of the proper permissions that an Apache user would need, such as read/write to to htdocs and the .conf and .log files, and permissions to log on as a service, etc etc - as well as the permissions to access the network resource you're trying to get to in the first place.
In light of that process, I chose to just run it under my own account instead. Once you get it working, you can go back and create that special account.
Hit "Apply" - it'll pop up a box saying you need to restart Apache to take effect, but hold off on that for a moment.
This is the tricky part: you have to give the user (the one you're running Apache as) permissions to act as part of the OS.
Go to the Local Security Policy panel (Start -> Run -> "secpol.msc").
Under the navigation section in the left sidebar, choose Local Policies -> User Rights Assignments.
In the right-hand frame, double-click the item "Act as part of the operating system" to open up its properties.
Select "Add User or Group, Enter the appropriate user in the box provided, and hit "OK."
At this point, you are technically complete - Apache can now do the same things to the network resource that your user can - read, write, execute, whatever. However, in my case, I was trying to create an actual readable resource, so I edited my Apache config file to create an alias to my share.
Open up your Apache configuration file. For most people it's httpd.conf in the conf subdirectory of your Apache install directory.
Add the following text to your config file (obviously substituting your UNC for "//servername/sharename" and renaming ALIAS_DIRECTORY to whatever you'd like):

Alias /ALIAS_DIRECTORY "//servername/sharename"

<Directory "//servername/sharename">
    Options Indexes
    AllowOverride None
    Order allow,deny
    Allow from all
</Directory
The other thing that is tricky and caught me up is that unlike Windows UNCs, the Apache config file requires forward slashes, not backslashes. So if you're copying the UNC directly from Windows, you'll have to turn all those slashes around.

Now you can restart your Apache service. Take a swing over to http://your.site.name/ALIAS_DIRECTORY and you should be able to view the network resource just fine.

Would you like to view your directories in your browser this script might come in handy.

<?php
$sub
= ($_GET['dir']);
$path = 'enter/your/directory/here/';
$path = $path . "$sub";
$dh = opendir($path);
$i=1;
while ((
$file = readdir($dh)) !== false) {
    if(
$file != "." && $file != "..") {
            if (
substr($file, -4, -3) =="."){
            echo
"$i. $file <br />";
            }else{           
        echo
"$i. <a href='?dir=$sub/$file'>$file</a><br />";
          }
       
$i++;
    }
}
closedir($dh);
?>

How to find files in a directory, using regular expressions (case-sensitive or not)

<?php

clearstatcache
();

$sourcepath = "C:/WINDOWS/TEMP";

// Replace \ by / and remove the final / if any
$root = ereg_replace( "/$", "", ereg_replace( "[\\]", "/", $sourcepath ));

// Search for text files
$results = m_find_in_dir( $root, ".*\.txt" );
if(
false === $results ) {
    echo
"'{$sourcepath}' is not a valid directory\n";
} else {
   
print_r( $results );
}

/**
* Search for a file maching a regular expression
*
* @param string $root Root path
* @param string $pattern POSIX regular expression pattern
* @param boolean $recursive Set to true to walk the subdirectories recursively
* @param boolean $case_sensitive Set to true for case sensitive search
* @return array An array of string representing the path of the matching files, or false in case of error
*/
function m_find_in_dir( $root, $pattern, $recursive = true, $case_sensitive = false ) {
   
$result = array();
    if(
$case_sensitive ) {
        if(
false === m_find_in_dir__( $root, $pattern, $recursive, $result )) {
            return
false;
        }
    } else {
        if(
false === m_find_in_dir_i__( $root, $pattern, $recursive, $result )) {
            return
false;
        }
    }
   
    return
$result;
}

/**
* @access private
*/
function m_find_in_dir__( $root, $pattern, $recursive, &$result ) {
   
$dh = @opendir( $root );
    if(
false === $dh ) {
        return
false;
    }
    while(
$file = readdir( $dh )) {
        if(
"." == $file || ".." == $file ){
            continue;
        }
        if(
false !== @ereg( $pattern, "{$root}/{$file}" )) {
           
$result[] = "{$root}/{$file}";
        }
        if(
false !== $recursive && is_dir( "{$root}/{$file}" )) {
           
m_find_in_dir__( "{$root}/{$file}", $pattern, $recursive, $result );
        }
    }
   
closedir( $dh );
    return
true;
}

/**
* @access private
*/
function m_find_in_dir_i__( $root, $pattern, $recursive, &$result ) {
   
$dh = @opendir( $root );
    if(
false === $dh ) {
        return
false;
    }
    while(
$file = readdir( $dh )) {
        if(
"." == $file || ".." == $file ){
            continue;
        }
        if(
false !== @eregi( $pattern, "{$root}/{$file}" )) {
           
$result[] = "{$root}/{$file}";
        }
        if(
false !== $recursive && is_dir( "{$root}/{$file}" )) {
           
m_find_in_dir__( "{$root}/{$file}", $pattern, $recursive, $result );
        }
    }
   
closedir( $dh );
    return
true;
}

?>

A simple function to count all the files and/or dirs inside a dir.
With optional extention when counting files.

Index of /
Some text file.txt
files/
num_files.phps
test.php

<?php
function num_files($dir, $type, $ext="")
{
// type 1: files only
// type 2: direcories only
// type 3: files and directories added
// type 4: files and directories separated with a space

   
if (!isset($dir) OR empty($dir))
    {
        echo
'<b>Syntax error:</b> $dir value empty.';
        exit;
    }

   
$num_files = 0;
   
$num_dirs = 0;
    switch(
$type)
    {
        case
1: // count only files, not dirs
           
if ($dir = @opendir($dir))
            {
                while ((
$file = readdir($dir)) !== false)
                {
                    if(
is_file($file) AND $file != "." AND $file != "..")
                    {
                        if (isset(
$ext) AND !empty($ext))
                        {
                           
$extension = end(explode(".", $file));
                            if (
$ext == $extension)
                            {
                               
$num_files++;
                            }
                        }
                        else
                        {
                           
$num_files++;
                        }
                    }
                } 
               
closedir($dir);
               
$total = $num_files;
            }
        break;

        case
2: // count only dirs, not files
           
if ($dir = @opendir($dir))
            {
                while ((
$file = readdir($dir)) !== false)
                {
                    if(
is_dir($file) AND $file != "." AND $file != "..")
                    {
                       
$num_dirs++;
                    }
                } 
               
closedir($dir);   
               
$total = $num_dirs;
            }
        break;

        case
3: // count files PLUS dirs in once variable
           
if ($dir = @opendir($dir))
            {
                while ((
$file = readdir($dir)) !== false)
                {
                    if(
is_dir($file) OR is_dir($file))
                    {
                        if (
$file != "." AND $file != "..")
                        {
                           
$num_files++;
                        }
                    }
                } 
               
closedir($dir);
               
$total = $num_files;
            }
        break;

        case
4: // count files AND dirs separately
           
if ($dir = @opendir($dir))
            {
                while ((
$file = readdir($dir)) !== false)
                {
                    if(
is_file($file) AND $file != "." AND $file != "..")
                    {
                       
$num_files++;
                    }

                    if(
is_dir($file) AND $file != "." AND $file != "..")
                    {
                       
$num_dirs++;
                    }
                } 
               
closedir($dir);
               
$total = $num_files." ".$num_dirs;
            }
        break;

        default:
            echo
'<b>Syntax error:</b> $type value empty.';
        break;
    }

    return
$total;
}

echo
num_files($_SERVER['DOCUMENT_ROOT'], 1, "php"). " file(s) met php extention<br /> ";
echo
num_files($_SERVER['DOCUMENT_ROOT'], 1). " file(s)<br />";
echo
num_files($_SERVER['DOCUMENT_ROOT'], 2). " dir(s)<br />";
echo
num_files($_SERVER['DOCUMENT_ROOT'], 3). " file(s) + dir(s)<br />";
$nummers = explode(" ", num_files($_SERVER['DOCUMENT_ROOT'], 4));
echo
reset($nummers) ." file(s) en ". end($nummers) ." dir(s)";
?>

will output:
1 file(s) with php extention
3 file(s)
1 dir(s)
1 file(s) + dir(s)
3 file(s) en 1 dir(s)

I sometimes find this useful. Hope you will too.

<?php
//list_by_ext: returns an array containing an alphabetic list of files in the specified directory ($path) with a file extension that matches $extension

function list_by_ext($extension, $path){
   
$list = array(); //initialise a variable
   
$dir_handle = @opendir($path) or die("Unable to open $path"); //attempt to open path
   
while($file = readdir($dir_handle)){ //loop through all the files in the path
       
if($file == "." || $file == ".."){continue;} //ignore these
       
$filename = explode(".",$file); //seperate filename from extenstion
       
$cnt = count($filename); $cnt--; $ext = $filename[$cnt]; //as above
       
if(strtolower($ext) == strtolower($extension)){ //if the extension of the file matches the extension we are looking for...
           
array_push($list, $file); //...then stick it onto the end of the list array
       
}
    }
    if(
$list[0]){ //...if matches were found...
   
return $list; //...return the array
   
} else {//otherwise...
   
return false;
    }
}

//example usage
if($win32_exectuables = list_by_ext("exe", "C:\WINDOWS")){
   
var_dump($win32_exectuables);
} else {
    echo
"No windows executables found :(\n";
}

?>

# simple directory walk with callback function

<?php
function callbackDir($dir)
{
  
# do whatever you want here
  
echo "$dir\n";
}

function
walkDir($dir,$fx)
{
 
$arStack = array();
 
$fx($dir);
  if( (
$dh=opendir($dir)) )
  { while( (
$file=readdir($dh))!==false )
    { if(
$file=='.' || $file=='..' ) continue;
      if(
is_dir("$dir/$file") )
      { if( !
in_array("$dir/$file",$arStack) ) $arStack[]="$dir/$file";
      }
    }
   
closedir($dh);
  }
  if(
count($arStack) )
  { foreach(
$arStack as $subdir )
    {
walkDir($subdir,$fx);
    }
  }
}

walkDir($root,callBackDir);
?>

Here's a function that will recrusively turn a directory into a hash of directory hashes and file arrays, automatically ignoring "dot" files.

<?php
function hashify_directory($topdir, &$list, $ignoredDirectories=array()) {
    if (
is_dir($topdir)) {
        if (
$dh = opendir($topdir)) {
            while ((
$file = readdir($dh)) !== false) {
                if (!(
array_search($file,$ignoredDirectories) > -1) && preg_match('/^\./', $file) == 0) {
                    if (
is_dir("$topdir$file")) {
                        if(!isset(
$list[$file])) {
                           
$list[$file] = array();
                        }
                       
ksort($list);
                       
hashify_directory("$topdir$file/", $list[$file]);
                    } else {
                       
array_push($list, $file);
                    }
                }
            }
           
closedir($dh);
        }
    }
}
?>

e.g.
<?php
$public_html
["StudentFiles"] = array();
hashify_directory("StudentFiles/", $public_html["StudentFiles"]);
?>
on the directory structure:
./StudentFiles/tutorial_01/case1/file1.html
./StudentFiles/tutorial_01/case1/file2.html
./StudentFiles/tutorial_02/case1/file1.html
./StudentFiles/tutorial_02/case2/file2.html
./StudentFiles/tutorial_03/case1/file2.html
etc...
becomes:
<?php
print_r
($public_html);
/*
outputs:
array(
  "StudentFiles" => array (
        "tutorial_01" => array (
              "case1" => array( "file1.html", "file2.html")
        ),
        "tutorial_02" => array (
              "case1" => array( "file1.html"),
              "case2" => array( "file2.html")
        ),
       "tutorial_03" => array (
              "case1" => array( "file2.html")
       )
  )
)
*/
?>
I'm using it to create a tree view of a directory.

Hello,

A friend of mine is running a webhost, I think i found a security leak with this script:

<?php
function select_files($dir, $label = "", $select_name, $curr_val = "", $char_length = 30) {
   
$teller = 0;
    if (
$handle = opendir($dir)) {
       
$mydir = ($label != "") ? "<label for=\"".$select_name."\">".$label."</label>\n" : "";
       
$mydir .= "<select name=\"".$select_name."\">\n";
       
$curr_val = (isset($_REQUEST[$select_name])) ? $_REQUEST[$select_name] : $curr_val;
       
$mydir .= ($curr_val == "") ? "  <option value=\"\" selected>...\n" : "<option value=\"\">...\n";
        while (
false !== ($file = readdir($handle))) {
           
$files[] = $file;
        }
       
closedir($handle);
       
sort($files);
        foreach (
$files as $val) {
            if (
is_file($dir.$val)) { // show only real files (ver. 1.01)
               
$mydir .= "    <option value=\"".$val."\"";
               
$mydir .= ($val == $curr_val) ? " selected>" : ">";
               
$mydir .= (strlen($val) > $char_length) ? substr($val, 0, $char_length)."...\n" : $val."\n";
               
$teller++;   
            }
        }
       
$mydir .= "</select>";
    }
    if (
$teller == 0) {
       
$mydir = "No files!";
    } else {
        return
$mydir;
    }
}

echo
select_files("C:/winnt/", "", "", "", "60");
?>

Now i can see hist files in his windows dir. Is this a leak? and is it fixable? I'll report this as bug too!

Tim2005

"opendir" said:
------------------------------------------------------------------

23-Jan-2006 08:04
I Just wanted a directory list and a clickable link to download the files

<snip>
------
<?
echo ("<h1>Directory Overzicht:</h1>");

function getFiles($path) {

<snip complicated function contents>

------------------------------------------------------------------
Here's a more straightforward way to linkify $path/files:

<?php

echo "<h1>Directory Overzicht:</h1>";

$dh = opendir($path);
while ((
$file = readdir($dh)) !== false) {
    echo
"<a href='$path/$file'>$file</a><br />";
}
closedir($dh);

?>

<?php
/* The below function will list all folders and files within a directory
It is a recursive function that uses a global array.  The global array was the easiest
way for me to work with an array in a recursive function
*This function has no limit on the number of levels down you can search.
*The array structure was one that worked for me.
ARGUMENTS:
$startdir => specify the directory to start from; format: must end in a "/"
$searchSubdirs => True/false; True if you want to search subdirectories
$directoriesonly => True/false; True if you want to only return directories
$maxlevel => "all" or a number; specifes the number of directories down that you want to search
$level => integer; directory level that the function is currently searching
*/
function filelist ($startdir="./", $searchSubdirs=1, $directoriesonly=0, $maxlevel="all", $level=1) {
   
//list the directory/file names that you want to ignore
   
$ignoredDirectory[] = ".";
   
$ignoredDirectory[] = "..";
   
$ignoredDirectory[] = "_vti_cnf";
    global
$directorylist;    //initialize global array
   
if (is_dir($startdir)) {
        if (
$dh = opendir($startdir)) {
            while ((
$file = readdir($dh)) !== false) {
                if (!(
array_search($file,$ignoredDirectory) > -1)) {
                 if (
filetype($startdir . $file) == "dir") {
                      
//build your directory array however you choose;
                       //add other file details that you want.
                      
$directorylist[$startdir . $file]['level'] = $level;
                      
$directorylist[$startdir . $file]['dir'] = 1;
                      
$directorylist[$startdir . $file]['name'] = $file;
                      
$directorylist[$startdir . $file]['path'] = $startdir;
                       if (
$searchSubdirs) {
                           if (((
$maxlevel) == "all") or ($maxlevel > $level)) {
                              
filelist($startdir . $file . "/", $searchSubdirs, $directoriesonly, $maxlevel, $level + 1);
                           }
                       }
                   } else {
                       if (!
$directoriesonly) {
                          
//if you want to include files; build your file array 
                           //however you choose; add other file details that you want.
                        
$directorylist[$startdir . $file]['level'] = $level;
                        
$directorylist[$startdir . $file]['dir'] = 0;
                        
$directorylist[$startdir . $file]['name'] = $file;
                        
$directorylist[$startdir . $file]['path'] = $startdir;
      }}}}
          
closedir($dh);
}}
return(
$directorylist);
}
$files = filelist("./",1,1); // call the function
foreach ($files as $list) {//print array
   
echo "Directory: " . $list['dir'] . " => Level: " . $list['level'] . " => Name: " . $list['name'] . " => Path: " . $list['path'] ."<br>";
}
?>