Page 358 - Beginning PHP 5.3
P. 358
Part III: Using PHP in Practice
Getting the Directory Path
The dirname() function returns the directory part of a given path. It complements the basename()
function, which returns the filename portion of a given path (see the section “ Retrieving a Filename from
a Path ” earlier in the chapter).
For example:
$path = “/home/james/docs/index.html”;
$directoryPath = dirname( $path );
$filename = basename( $path );
After running this code., $directoryPath contains “ /home/james/docs ” , and $filename holds
“ index.html .
”
Working with Directory Objects
PHP offers an alternative object - oriented mechanism for working with directories: the Directory class.
To use it, first create a Directory object by calling the dir() function with the name of the directory
you want to work with, as follows:
$dir = dir( “/home/james/docs” );
The Directory object provides two properties: handle and path . These refer to the directory handle
and the path to the directory, respectively:
echo $dir- > handle . “ < br / > ”; // Displays the directory handle
echo $dir- > path . “ < br / > ”; // Displays “/home/james/docs”
You can use the handle property with other directory functions such as readdir() , rewinddir() ,
and closedir() , just as if you were using a regular directory handle.
The Directory object supports three methods — read() , rewind() , and close() — which are
functionally equivalent to readdir() , rewinddir() , and closedir() , respectively. For example, you
can rewrite the dir_list.php script from earlier in the chapter using a Directory object:
< !DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Strict//EN”
“http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd” >
< html xmlns=”http://www.w3.org/1999/xhtml” xml:lang=”en” lang=”en” >
< head >
< title > Listing the contents of a directory < /title >
< link rel=”stylesheet” type=”text/css” href=”common.css” / >
< /head >
< body >
< h1 > Listing the contents of a directory < /h1 >
< ?php
$dirPath = “/home/matt/images”;
$dir = dir( $dirPath );
? >
320
9/21/09 9:10:19 AM
c11.indd 320 9/21/09 9:10:19 AM
c11.indd 320