Page 356 - Beginning PHP 5.3
P. 356

Part III: Using PHP in Practice
                You can see that the returned filenames are not sorted in any way. To sort them, first read the entries
                into an array:

                    $filenames = array();
                    while ( $file = readdir( $handle ) ) $filenames[] = $file;
                    closedir( $handle );

                The $filenames array now contains every entry in the directory. Now you can call sort() to arrange
                the array elements in ascending order, then loop through the array displaying all except the “.” and
                “..” entries:

                    sort( $filenames );

                    foreach ( $filenames as $file ) {
                      if ( $file != “.” && $file != “..” ) {
                        echo “<li>$file</li>“;
                      }
                    }





                  Other Directory Functions
                   Just as with files, PHP provides a range of ways to manipulate directories, including the following
                 functions:
                   ❑       rewinddir()  —  Moves the directory pointer back to the start of the list of entries

                   ❑       chdir()  —  Changes the current directory

                   ❑       mkdir()  —  Creates a directory

                   ❑       rmdir()  —  Deletes a directory

                   ❑       dirname()  —  Returns the directory portion of a path

                  Resetting the Directory Pointer
                  The  rewinddir()  function resets PHP ’ s internal pointer back to the first entry in a given directory. This
                 function is the directory counterpart to the   rewind()  function for files. To use  rewinddir() , pass an
                 open directory handle to it, as follows:

                    rewinddir( $handle );

                  Changing the Current Directory
                  The  chdir()  function call changes the current directory to a new directory:


                    chdir( “/home/matt/myfolder” );






              318





                                                                                                      9/21/09   9:10:18 AM
          c11.indd   318
          c11.indd   318                                                                              9/21/09   9:10:18 AM
   351   352   353   354   355   356   357   358   359   360   361