This section describes opendir() and other directory management functions. A tutorial example is provided on how to open a directory as a directory resource handle and read its entries with the readdir() function in a loop.
PHP offers the following built-in functions to manage directories of file systems:
chdir($path) - This "change directory" function changes the current directory to the specified path.
If the specified path is invalid, it returns FALSE.
For example, chdir("/herong/php") changes the current directory to /herong/php.
getcwd() - This "get current working directory" function returns the path name of the current directory.
opendir($path) - This "open directory" function creates and returns a directory resource handle
that represents the directory of the specified path. The returned directory resource handle contains
a current entry pointer initially set to the position before the first entry of the directory.
If the specified path is invalid, it returns FALSE.
For example, $dir = opendir("/herong/php") assigns a directory resource handle to $dir represents /herong/php.
closedir($dir) - This "close directory" function closes the specified directory resource handle.
readdir($dir) - This "read directory" function moves the internal pointer to the next entry in the directory
represented by the specified directory resource handle and returns the entry as a string.
If the internal pointer is currently pointing to the end of the directory,
it returns FALSE, because there is no next entry.
rewinddir($dir) - This "rewind directory" function resets its internal pointer to the position
before the first entry.
scandir($path,$order) - The "scan directory" function returns all entries in the directory of
the specified path as an array sorted in the specified order. If $order is not specified or $order=0,
entries are sorted alphabetically in ascending order. If $order=0, entries are sorted alphabetically in descending order.
dir($path) - This "directory" class constructor returns a directory object representing the directory of
the specified path.
mkdir($path) - This "make directory" function creates a new directory with the specified path.
rmdir($path) - This "remove directory" function removes the directory of the specified path.
To show you how to use some of these functions should be used, I wrote this simple script:
<?php # OpendirTest.php
# Copyright (c) 2003 by Dr. Herong Yang
#
$path = "/php";
print "\n First 10 entries in $path:\n";
$dir = opendir($path);
$i = 0;
while (FALSE !== ($entry = readdir($dir)) && $i<10) {
$i++;
print " $entry\n";
}
print "\n First 10 entries in $path again:\n";
$dir = dir($path);
$i = 0;
while (FALSE !== ($entry = $dir->read()) && $i<10) {
$i++;
print " $entry\n";
}
?>
If you run this script, you should get:
First 10 entries in /php:
.
..
chm
dev
ext
extras
fdftk.dll
fribidi.dll
gds32.dll
go-pear.bat
First 10 entries in /local/php again:
.
..
chm
dev
ext
extras
fdftk.dll
fribidi.dll
gds32.dll
go-pear.bat