File Handling in  PHP - Page 2
       by Jeff Wheeler aka nokrev | 5 July 2006

On the previous page, you got an introduction to using PHP to manipulate files. In this page, we will pick up from where we left off and discuss how to list files from a directory.

Listing Files
Occasionally, it's nice to use PHP to list all files in a certain directory. This can be achieved via the dir class.

  1. First, we have to initiate the dir object with the directory we want to look through. If it's the current directory, use '.', as this references the current directory.

  2. The next part is a little bit more complicated, but that is because the PHP documentation recommends a complex but short way to do what we intended.

    I use the while control structure, to loop through all the entries. For the condition, I test if the $dir->read() returns false (the !== operator tests for the correct type, so '' would not evaluate to 0 or false, as it would with a non-type-sensitive operator). I also define $file inside the expression, but the assignment will return the final value of $file after the assignment. The $dir->read() method will return false in the case that there are no more files, and it'll break out of the loop.



    If you are using html, you will want to use a <br /> instead of a newline character, so that the files will appear on new lines in your page.
  3. If you executed the previous code, you will notice two strange files listed in your script's output: . and ... These are references to the current directory (the '.'), and the parent directory (the '..').

    If you want to exclude these from your list, simply write an if statement that tests whether the $file variable is either of those values, and if so, ignore it.

  4. It's necessary to close instances of the dir class when you're done with them, in order to clean the resource handle, and announce to the operating system that you're done with it.

 

This wraps up learning how to list files using PHP. On the next page, you will learn how to upload files from a directory to the server. Before I send you off to the next page though, for another practical use of being able to retrieve a list of files from a directory, read Kirupa's tutorial on Parsing External Data.

More file handling coverage on the next page!

1 | 2 | 3




SUPPORTERS:

kirupa.com's fast and reliable hosting provided by Media Temple.