13.09.2016 Views

PHP and MySQL Web Development 4th Ed-tqw-_darksiderg

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

440 Chapter 19 Interacting with the File System <strong>and</strong> the Server<br />

This script makes use of the opendir(), closedir(), <strong>and</strong> readdir()functions.<br />

The function opendir() opens a directory for reading. Its use is similar to the use of<br />

fopen() for reading from files. Instead of passing it a filename, you should pass it a directory<br />

name:<br />

$dir = opendir($current_dir);<br />

The function returns a directory h<strong>and</strong>le, again in much the same way as fopen() returns<br />

a file h<strong>and</strong>le.<br />

When the directory is open, you can read a filename from it by calling<br />

readdir($dir), as shown in the example.This function returns false when there are<br />

no more files to be read. Note that it will also return false if it reads a file called “0”;in<br />

order to guard against this, we explicitly test to make sure the return value is not equal<br />

to false:<br />

while(false !== ($file = readdir($dir)))<br />

When you are finished reading from a directory, you call closedir($dir) to finish.This<br />

is again similar to calling fclose() for a file.<br />

Sample output of the directory browsing script is shown in Figure 19.3.<br />

Figure 19.3<br />

The directory listing shows all the files in the chosen directory.<br />

Typically the . (the current directory) <strong>and</strong> .. (one level up) directories would also display<br />

in the list in Figure 19.3. However, we stripped these directories out with the following<br />

line of code:<br />

if($file != "." && $file != "..")<br />

If you delete this line of code, the . <strong>and</strong> .. directories will be added to the list of files that<br />

are displayed.

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!