Home >Backend Development >PHP Tutorial >What folder is lost.dir? Function code for traversing folders and subdirectories using PHP
The function we are going to use is Scandir, which lists the files and directories in a specified path, just like Dir.
> and the more powerful Glob() function, which returns the file names or directories matching the specified pattern in the form of an array.
> Friendly reminder, don’t stay in front of the computer for too long like Xiaoxie, otherwise you will suffer from high blood sugar like Xiaoxie.
1. Traverse single-layer folders:
> The problem with scanning single-layer folders is that although the results of the two functions are different, the performance is not much different.
> The Scandir function will provide two extra lines, namely "." and "..", while Glob does not.
Copy code The code is as follows:
function get_dir_scandir(){
$tree = array();
foreach(scandir('./') as $single){
echo $single."< br/>rn";
}
}
get_dir_scandir();
function get_dir_glob(){
$tree = array();
foreach(glob('./*') as $single){
echo $single ."
rn";
}
}
get_dir_glob();
Copy the code The code is as follows:
//Update at 2010.07.25 - The following code is invalid
$path = '..';
function get_filetree_scandir($path){
$tree = array();
foreach(scandir($path) as $single){
if(is_dir('../'.$single)){
$tree = array_merge($tree,get_filetree($single));
}
else{
$tree[] = '../'.$single;
}
}
return $tree;
}
print_r(get_filetree_scandir($path));
//Update at 2010.07.25 - The following is the new code
$path = './';
function get_filetree_scandir($path){
$result = array();
$temp = array();
if (!is_dir($path)||!is_readable($path)) return null; //Check the validity of the directory
$allfiles = scandir($path); //Get all files and folders in the directory
foreach ($allfiles as $filename) { //Traverse the files and folders in the directory
if (in_array($filename,array('.','..'))) continue; //Ignore. and..
$fullname = $path.'/'.$filename; //Get the full file path
if (is_dir($fullname)) { //If it is a directory, continue the recursion
$result[$filename] = get_filetree_scandir($fullname); //The recursion starts
}
else {
$temp[] = $filename; / /If it is a file, store it in the array
}
}
foreach ($temp as $tmp) { //Save the contents of the temporary array into the array that holds the result
$result[] = $tmp; //This allows Folders are arranged in the front, files are in the back
}
return $result;
}
print_r(get_filetree_scandir($path));
Copy the code The code is as follows:
$path = '..';
function get_filetree($path){
$tree = array();
foreach(glob($path.'/*' ) as $single){
if(is_dir($single)){
$tree = array_merge($tree,get_filetree($single));
}
else{
$tree[] = $single;
}
}
return $tree;
}
print_r(get_filetree($path));
The above has introduced the function code of what folder lost.dir is and uses PHP to traverse folders and subdirectories, including the content of what folder lost.dir is. I hope it will be helpful to friends who are interested in PHP tutorials.