php lists the code for all files in a directory

  • 2020-05-26 08:03:29
  • OfStack

 
<?php 
function dir_path($path) { 
$path = str_replace('\\', '/', $path); 
if (substr($path, -1) != '/') $path = $path . '/'; 
return $path; 
} 
/** 
*  Lists all files in the directory  
* 
* @param str $path  directory  
* @param str $exts  The suffix  
* @param array $list  Path to the 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; 
} 
?> 

Usage:
 
<?php 
$r = dir_list('dir'); 
printf("<p> The output data is: </p><pre>%s</pre>\n", var_export($r , true)); 
?> 


PHP function - lists all files in the directory 2

The function written by PHP lists all the files in the specified directory.
The function is followed by a sample code for use.
Note: if the page is utf-8, in the window Chinese version of the system, when reading the Chinese file name will appear scrambled.
 
<?php 
/*  function  listDirTree( $dirName = null ) 
**  function   Lists all files and subdirectories in the directory  
**  parameter  $dirName  Directory name  
**  return   Directory structure array  false For 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 a directory , recursive  
{ 
$tree[$file] = listDirTree( $filePath ); 
} 
else // As a file , Add to the current array  
{ 
$tree[] = $file; 
} 
} 
} 
closedir( $dh ); 
} 
else 
{ 
exit( "IBFileSystem: can not open directory $dirName."); 
} 
// Returns the current $tree 
return $tree; 
} 
else 
{ 
exit( "IBFileSystem: $dirName is not a directory."); 
} 
} 
$files = listDirTree("."); 
//print_r($files); 
$size = count(files); 
// The following code is created 1 List of files in this directory (with link address)  
echo '<ol>'; 
for( $i=0; $files[$i] != NULL; $i++ ) { 
echo '<li><a href="'.($files[$i]).'" target="_blank">'.$files[$i].'</a></li>'; 
} 
echo '</ol>'; 
?> 

Related articles: