downloads | documentation | faq | getting help | mailing lists | reporting bugs | php.net sites | links | my php.net 
search for in the  

<opendirrewinddir>
Last updated: Thu, 26 Jun 2008

readdir

(PHP 4, PHP 5)

readdir — Read entry from directory handle

Description

string readdir ( resource $dir_handle )

Returns the filename of the next file from the directory. The filenames are returned in the order in which they are stored by the filesystem.

Parameters

dir_handle

The directory handle resource previously opened with opendir().

Return Values

Returns the filename on success, or FALSE on failure.

Warning

This function may return Boolean FALSE, but may also return a non-Boolean value which evaluates to FALSE, such as 0 or "". Please read the section on Booleans for more information. Use the === operator for testing the return value of this function.

Examples

Example #1 List all files in a directory

Please note the fashion in which readdir()'s return value is checked in the examples below. We are explicitly testing whether the return value is identical to (equal to and of the same type as--see Comparison Operators for more information) FALSE since otherwise, any directory entry whose name evaluates to FALSE will stop the loop (e.g. a directory named "0").

<?php
// Note that !== did not exist until 4.0.0-RC2

if ($handle = opendir('/path/to/files')) {
   echo
"Directory handle: $handle\n";
   echo
"Files:\n";

  
/* This is the correct way to loop over the directory. */
  
while (false !== ($file = readdir($handle))) {
       echo
"$file\n";
   }

  
/* This is the WRONG way to loop over the directory. */
  
while ($file = readdir($handle)) {
       echo
"$file\n";
   }

  
closedir($handle);
}
?>

Example #2 List all files in the current directory and strip out . and ..

<?php
if ($handle = opendir('.')) {
   while (
false !== ($file = readdir($handle))) {
       if (
$file != "." && $file != "..") {
           echo
"$file\n";
       }
   }
  
closedir($handle);
}
?>

See Also



add a noteadd a note User Contributed Notes
Read entry from directory handle
There are no user contributed notes for this page.




<opendirrewinddir>
Last updated: Thu, 26 Jun 2008
show source | credits | sitemap | contact | advertising | mirror sites
Copyright © 2001-2005 The PHP Group
All rights reserved.
This unofficial mirror is operated at: http://phpbuilder.com/
Last updated: Tue Nov 1 20:20:59 2005 EST
Columns / Articles | Tips / Quickies | News | News Linking and RSS Feeds | Shared Code Library
Mail Archives | Support / Discussion Forums | Get Started! Links | Contribute! | Docs