Page 359 - Beginning PHP 5.3
P. 359

Chapter 11: Working with Files and Directories
                                  < p > < ?php echo $dirPath ? >  contains the following files and folders: < /p >

                                  < ul >
                               < ?php

                             while ( $file = $dir- > read() ) {

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

                             $dir- > close();

                             ? >
                                  < /ul >
                                < /body >
                               < /html >


                           Telling a File from a Directory
                           Often you need to know whether a particular file is a regular file or a directory. For example, suppose
                         you want to write some code that travels down through a tree of folders. You ’ d need to detect when a
                         file was actually a folder, so you could enter the folder and continue working through the tree. By the
                         same token, if you want to display the files in a folder, you ’ d need to detect when a file is in fact a
                         regular file.

                               Remember: both directories and regular files are all essentially files, but directories are a special kind
                             of file.

                           PHP has two functions to help you test for a file or a directory:
                            ❑       is_dir()   —  Returns  true  if the given filename refers to a directory
                            ❑       is_file()   —  Returns  true  if the given filename refers to a regular file


                          Here ’ s a simple example that determines if a file called   myfile  is a file or a directory:
                             $filename = “myfile”;

                             if ( is_dir( $filename ) ) {
                               echo “$filename is a directory.”;
                             } elseif ( is_file( $filename ) ) {
                               echo “$filename is a file.”;
                             } else {
                               echo “$filename is neither a directory nor a file.”;



                             }











                                                                                                         321





                                                                                                      9/21/09   9:10:19 AM
          c11.indd   321
          c11.indd   321                                                                              9/21/09   9:10:19 AM
   354   355   356   357   358   359   360   361   362   363   364