A function that returns the list of files in the queried directory and the array of folders. The array will distinguish whether the file is a directory or a file, and the total number of directories and files in the directory under query.
The code is as follows:
/*
* param string $dir directory name
* Return array $dirList query result
*/
function Listdir ($dir) {
if (!file_exists ($dir) | |! Is_dir ($dir)) {
Return ';
}
$dirList =array (' Dirnum ' =>0, ' FileNum ' =>0, ' lists ' + = ');
$dir =opendir ($dir);
$i = 0;
while ($file =readdir ($dir)) {
if ($file!== '. ' && $file!== ' ... ') {
$dirList [' lists '] [$i] [' name ']= $file;
if (Is_dir ($file)) {
$dirList [' lists '] [$i] [' Isdir ']=true;
$dirList [' Dirnum ']++;
}else{
$dirList [' lists '] [$i] [' Isdir ']=false;
$dirList [' FileNum ']++;
}
$i + +;
};
};
Closedir ($dir);
return $dirList;
}
Use the following, for example, to query the file under directory D:\PHPnow-1.5.6\htdocs and directory list:
Echo '
Print_r (Listdir (' D:\PHPnow-1.5.6\htdocs '));
Description: In this code, the main use of PHP directory Functions opendir (), Readdir (), Closedir (), explained below:
1, the Opendir function is used to open the specific directory visited, The function parameter is the directory name, note that if the PHP execution file and browse the home directory at the same level, the parameters passed can be just the directory name, if not at the same level or read the multilevel directory, you need to bring a specific directory path or file path.
2, after reading the home directory through the Opendir function, through the while loop to further read the main directory of the multi-level directory and files, the PHP directory function used here is Readdir, this function reads the directory or the file name from the directory, when there is no readable directory or file, Return FALSE, note that the Read directory contains. And: In this example tutorial, because it is a level down reading directory, the directory information read is. and. When you jump out of this loop, continue reading the next level of directory.
3, after reading all the subdirectories and files of the home directory, through the PHP directory function closedir to close the directory handle, similar to the Fclose function close the file.