PHP Directories Processing All Files in a Directory - Supercoders | Web Development and Design | Tutorial for Java, PHP, HTML, Javascript PHP Directories Processing All Files in a Directory - Supercoders | Web Development and Design | Tutorial for Java, PHP, HTML, Javascript

Breaking

Post Top Ad

Post Top Ad

Monday, July 15, 2019

PHP Directories Processing All Files in a Directory

PHP Directories 



Processing All Files in a Directory

Problem

You want to iterate over all files in a directory. For example, you want to create a <select/> box in a form that lists all the files in a directory.

Solution

Use a DirectoryIterator to get each file in the directory:

       echo "<select name='file'>\n";
       foreach (new DirectoryIterator('/usr/local/images') as $file) {
              echo '<option>' . htmlentities($file) . "</option>\n";
       }
       echo '</select>';

Discussion

The DirectoryIterator yields one value for each element in the directory. That value is an object with some handy characteristics. The object’s string representation is the filename (with no leading path) of the directory element. For example, if /usr/local/images contains the files cucumber.gif and eggplant.png, the code in the Solution prints:

       <select name='file'>
       <option>.</option>
       <option>..</option>
       <option>cucumber.gif</option>
       <option>eggplant.png</option>
       </select>

A DirectoryIterator yields an object for all directory elements, including . (current directory) and .. (parent directory). Fortunately, that object has some methods that help us identify what it is. The isDot() method returns true if it’s either . or ... This example uses isDot() to prevent those two entries from showing up in the output:

       echo "<select name='file'>\n";
       foreach (new DirectoryIterator('/usr/local/images') as $file) {
              if (! $file->isDot()) {
                   echo '<option>' . htmlentities($file) . "</option>\n";
              }
       }
       echo '</select>';

Table  DirectoryIterator object information methods
       
______________________________________________________________________

The data that the functions report come from the same underlying system calls as the data that the functions report, so the same cautions on differences between Unix and Windows apply.

No comments:

Post a Comment

Post Top Ad