$r = dir_list('dir');
printf("
The output data is:
%s
n", var_export($r , true));
?>
A function written in PHP to list all files in a specified directory.
The function is followed by a sample code of 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 list all files and subdirectories in the directory
** Parameter $dirName directory name
** Return directory structure array false means failure
*/
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 list of files in this directory (with link address)
echo '
';
for( $i=0; $files [$i] != NULL; $i++ ) {
echo '- '.$ files[$i].'
';
}
echo '
';
?>