The process required for reading a directory's contents is quite similar to that involved in reading a file. This section introduces the functions available for this task, and also introduces a function new to PHP 5 that reads a directory's contents into an array. opendir() resource opendir (string path) Just as fopen() opens a file pointer to a given file, opendir() opens a directory stream specified by path. closedir() void closedir (resource directory_handle) The closedir() function closes the directory stream pointed to by directory_handle. readdir() string readdir (int directory_handle) The readdir() function returns each element in the directory specified by directory_handle. You can use this function to list all files and child directories in a given directory: <?php Sample output follows: --------------------------------------------. 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 != "..")... scandir() array scandir (string directory [,int sorting_order [, resource context]]) The scandir() function, which is new to PHP 5, returns an array consisting of files and directories found in directory, or returns FALSE on error. Setting the optional sorting_order parameter to 1 sorts the contents in descending order, overriding the default of ascending order. Revisiting the example from the previous section: <?php This returns: --------------------------------------------Array ( [0] => . [1] => .. [2] => articles [3] => images The context parameter refers to a stream context. You'll learn more about this topic in Chapter 16.
blog comments powered by Disqus |
|
|
|
|
|
|
|