Prev | Current Page 362 | Next

W. Jason Gilmore

"Beginning PHP and MySQL: From Novice to Professional"

Its prototype follows:
void closedir(resource directory_handle)
Parsing Directory Contents
The readdir() function returns each element in the directory. Its prototype follows:
300 CHAPTER 10 ?–  WORKING WITH THE FI LE AND OPERATING SYSTEM
string readdir(int directory_handle)
Among other things, you can use this function to list all files and child directories
in a given directory:
$dh = opendir('/usr/local/apache2/htdocs/');
while ($file = readdir($dh))
echo "$file
";
closedir($dh);
?>
Sample output follows:
.
..
articles
images
news
test.php
Note that readdir() also returns the . and .. entries common to a typical Unix
directory listing. You can easily filter these out with an if statement:
if($file != "." AND $file != "..")...
Reading a Directory into an Array
The scandir() function, introduced in PHP 5, returns an array consisting of files and
directories found in directory, or returns FALSE on error. Its prototype follows:
array scandir(string directory [,int sorting_order [, resource context]])
Setting the optional sorting_order parameter to 1 sorts the contents in descending
order, overriding the default of ascending order. Executing this example (from the
previous section)
print_r(scandir("/usr/local/apache2/htdocs"));
?>
CHAPTER 10 ?–  WORKING WITH T HE FILE A ND OPERATING SYSTEM 301
returns the following:
Array ( [0] => .


Pages:
350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374