-
- /**
- Directory processing function
- */
- function dir_path($path) {
- $path = str_replace('\', '/', $path);
- if (substr($ path, -1) != '/') $path = $path . '/';
- return $path;
- }
- /**
- * List all files in the directory
- *
- * @param str $path directory
- * @param str $exts suffix
- * @param array $list path array
- * @return array Return path array
- */
- function dir_list($path, $exts = '', $list = array()) {
- $path = dir_path($path);
- $files = glob($path . '*');
- foreach($files as $v) {
- if (!$exts || preg_match("/.($exts)/i", $v)) {
- $list[] = $v;
- if (is_dir($v)) {
- $list = dir_list($v, $exts, $ list);
- }
- }
- }
- return $list;
- }
- ?>
Copy code
Usage:
-
- $r = dir_list('dir');
- printf("
The output data is: %s n" , var_export($r, true));
- ?>
Copy code
#-------------------
PHP function-used to list all files in a directory
A function written in PHP to list all files in a specified directory.
The function is followed by a sample code for its use.
Note: If the page is UTF-8, in the Chinese version of Windows system, garbled characters will appear when reading the Chinese file name.
-
- /* Function listDirTree( $dirName = null )
- ** Function lists all files and subdirectories in the directory
- ** Parameter $dirName directory name
- ** Returns the directory structure array false Failed
- */
- function listDirTree( $dirName = null )
- {
- if( empty( $dirName ) )
- exit( "IBFileSystem: directory is empty." );
- if( is_dir( $dirName ) )
- {
- if( $dh = opendir( $dirName ) )
- {
- $tree = array();
- while( ( $file = readdir( $dh ) ) !== false )
- {
- if( $file != ". " && $file != ".." )
- {
- $filePath = $dirName . "/" . $file;
- if( is_dir( $filePath ) ) //For directories, recursively
- {
- $tree[$file ] = listDirTree( $filePath );
- }
- else //For files, add to the current array
- {
- $tree[] = $file;
- }
- }
- }
- closedir( $dh );
- }
- else
- {
- exit( "IBFileSystem: can not open directory $dirName.");
- }
- //Return the current $tree
- return $tree;
- }
- else
- {
- exit( "IBFileSystem: $dirName is not a directory .");
- }
- }
- $files = listDirTree(".");
- //print_r($files);
- $size = count(files);
- //The following code creates a file in this directory List (with link address)
- echo '
';
- for( $i=0; $files[$i] != NULL; $i++ ) {
- echo '
- '.$files[$i].'
';
- }
- echo '< /ol>';
- ?>
Copy code
|