In the previous article, we introduced the method of reading the entire file at once and storing the file data line by line into an array. If you need it, please see "How to store the entire file data line by line in php 》 in the array. This time we will learn how to obtain files in the specified directory (excluding subdirectories). You can refer to it if necessary.
Sometimes when we operate a directory, we need to know whether and what files exist in the directory; this requires reading the directory contents. Today we will introduce to you how PHP obtains files in a specified directory and returns the names of files and folders in the directory.
Create a directory named "demo" on the D drive. There are these files in the directory:
If you want to get "D: /demo
", what needs to be done to output their file names?
Attach the implementation code directly:
<?php $dir = 'D:/demo'; if(is_dir($dir)){ $info = opendir($dir); while (($file = readdir($info)) !== false) { //用不全等于是区分如果文件夹名字为0的时候,那么0!==false,仍然可以遍历 echo $file.'<br>'; } closedir($info); } ?>
Do you know what will be output? Take a look at the output:
Let’s analyze it:
First use opendir($dir)
to open a directory.
Then use readdir($info)
to get the name of the next file or directory in the open directory $info
; because only one A file/directory can be obtained, so you need to use a while() loop to obtain and output all files/directories.
Finally use closedir($info)
to close the directory.
Note: After the operation on a directory is completed, you need to use the closedir() function to close the open directory, that is, to release the resources occupied when operating the directory. Not only directories, but also files need to be closed using the fclose() function after the operation is completed.
Okay, that’s all. If you want to know anything else, you can click this. → →Basic operation of PHP files
## Recommended: 《PHP interview questions summary (collection)》《php video tutorial》
The above is the detailed content of How does php know what files are in the specified directory?. For more information, please follow other related articles on the PHP Chinese website!