PHP's opendir() readdir() and closedir() are used for reading the contents of a directory (there's also glob() and scandir() but I'll cover those in later posts). Combined with functions like is_file() is_dir() and is_link() and you can easily build up a directory tree or process files etc.
Example directory
The examples below look at a directory with the following:
Simple example
A simple example to loop through the directory's contents and display the names of the files, directories etc within it is as follows:
The output for the example directory is:
Note that it's not sorted in any particular way and includes . and .. which are indicators for the current directory and parent directory.
Sorting the data
Instead of echoing out the filenames they could instead be stored in an array, sorted and then some other processing done on them. This will ensure they are in alphabetical order.
Doing print_r($names) will show this:
Testing what type of file it is
The final example loops through the directory and checks whether it's a file, directory or symbolic link and does some processing depending on which type it is (in this example it's simply echoing out what type it is and the name). The additional if($name != '.' && $name != '..') text excludes the special . and .. directory names.
And the output:
0 comments:
Post a Comment