7.8 Processing a Directory File-by-File


You want to process a directory file-by-file, the same way that you would process a file line-by-line with fgets() .

Technique

Either use the dir() function and manipulate the directory via a pseudo-object, or use the opendir() , readdir() , and closedir() functions to read the directory.

  1. Using dir()

     $dh = dir ($directory_name); while ($entry = $dh->read()) {     print $entry . "\n"; } $dh->close(); 
  2. Using opendir() , readdir() , and closedir()

     $dh = opendir ($directory_name); while ($entry = readdir ($dh)) {     print $entry . "\n"; } closedir ($dh); 

Comments

Both solutions will work equally well; which one you choose is a matter of preference. The dir() function actually calls opendir() and creates an object that calls the corresponding functions in the second solution, so when you call $dh->read() , you are really calling readdir($dh) . As a matter of practice, I use the first solution just because I enjoy using the object interface.

You might have noticed that the functions PHP offers are much like the C functions for manipulating directories. In fact, readdir() , rewinddir() , opendir() , and closedir() are simply wrappers for the C functions.



PHP Developer's Cookbook
PHP Developers Cookbook (2nd Edition)
ISBN: 0672323257
EAN: 2147483647
Year: 2000
Pages: 351

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net