Reading the list of files from a directory |
| Written by phpecho.com | |||
In this PHP tutorial, we look at how we can browse through the list of all files in a directory recursively. Suppose we have a directory called tutorials, and inside that directory there are two directories – java and php. Assume that there are individual files inside these directories. Our script should read the file names and print them out. We will show the code snippet and then explain what each piece of code does. $handle=opendir("path/to/tutorial/folder");
while (($file = readdir($handle))!=false) {
echo ($file.’<br>’);
}
The first line gets a handle to the folder on which we want to operate. We must pass the location of the directory to the opendir function. The while loop browses through the directory and the file name is printed. When we execute the above code, the output will be similar to the following: tutorials
This works fine but what we wanted was only the file names but in the example above, we got the folder names too. We change the code to add a line to check if it is a file. We do this based on file extensions. The new code is given below:
$handle=opendir("path/to/tutorial/folder");
while (($file = readdir($handle))!=false) {
if (!is_dir($file) {
echo ($file.’<br>’);
}
}
In this code snippet, we check if $file is a directory. For this purpose we use the is_dir function. This function returns true if it is a directory, false otherwise. Since in our example, we do not have a probability that $file is a non-existent file, this code snippet is good enough to use.
|