php 使用php列出目录中的所有文件夹子文件夹和文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7121479/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Listing all the folders subfolders and files in a directory using php
提问by Warrior
Please give me a solution for listing all the folders,subfolders,files in a directory using php. My folder structure is like this:
请给我一个使用php列出目录中所有文件夹,子文件夹,文件的解决方案。我的文件夹结构是这样的:
Main Dir
Dir1
SubDir1
File1
File2
SubDir2
File3
File4
Dir2
SubDir3
File5
File6
SubDir4
File7
File8
I want to get the list of all the files inside each folder.
我想获取每个文件夹中所有文件的列表。
Is there any shell script command in php?
php中是否有任何shell脚本命令?
回答by Shef
function listFolderFiles($dir){
$ffs = scandir($dir);
unset($ffs[array_search('.', $ffs, true)]);
unset($ffs[array_search('..', $ffs, true)]);
// prevent empty ordered elements
if (count($ffs) < 1)
return;
echo '<ol>';
foreach($ffs as $ff){
echo '<li>'.$ff;
if(is_dir($dir.'/'.$ff)) listFolderFiles($dir.'/'.$ff);
echo '</li>';
}
echo '</ol>';
}
listFolderFiles('Main Dir');
回答by nbauers
This code lists all directories and files in sorted order in a tree view. It's a site map generator with hyper-links to all the site resources. The full web page source is here. You'll need to change the path on the ninth line from the end.
此代码在树视图中按排序顺序列出所有目录和文件。它是一个站点地图生成器,带有指向所有站点资源的超链接。完整的网页来源在这里。您需要更改从末尾算起的第九行的路径。
<?php
$pathLen = 0;
function prePad($level)
{
$ss = "";
for ($ii = 0; $ii < $level; $ii++)
{
$ss = $ss . "| ";
}
return $ss;
}
function myScanDir($dir, $level, $rootLen)
{
global $pathLen;
if ($handle = opendir($dir)) {
$allFiles = array();
while (false !== ($entry = readdir($handle))) {
if ($entry != "." && $entry != "..") {
if (is_dir($dir . "/" . $entry))
{
$allFiles[] = "D: " . $dir . "/" . $entry;
}
else
{
$allFiles[] = "F: " . $dir . "/" . $entry;
}
}
}
closedir($handle);
natsort($allFiles);
foreach($allFiles as $value)
{
$displayName = substr($value, $rootLen + 4);
$fileName = substr($value, 3);
$linkName = str_replace(" ", "%20", substr($value, $pathLen + 3));
if (is_dir($fileName)) {
echo prePad($level) . $linkName . "<br>\n";
myScanDir($fileName, $level + 1, strlen($fileName));
} else {
echo prePad($level) . "<a href=\"" . $linkName . "\" style=\"text-decoration:none;\">" . $displayName . "</a><br>\n";
}
}
}
}
?><!DOCTYPE HTML>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Site Map</title>
</head>
<body>
<h1>Site Map</h1>
<p style="font-family:'Courier New', Courier, monospace; font-size:small;">
<?php
$root = '/home/someuser/www/website.com/public';
$pathLen = strlen($root);
myScanDir($root, 0, strlen($root)); ?>
</p>
</body>
</html>
回答by jim_kastrin
A very simple way to show folder structure makes use of RecursiveTreeIterator
class (PHP 5 >= 5.3.0, PHP 7) and generates an ASCII graphic tree.
显示文件夹结构的一种非常简单的方法是使用RecursiveTreeIterator
类(PHP 5 >= 5.3.0,PHP 7)并生成 ASCII 图形树。
$it = new RecursiveTreeIterator(new RecursiveDirectoryIterator("/path/to/dir", RecursiveDirectoryIterator::SKIP_DOTS));
foreach($it as $path) {
echo $path."<br>";
}
http://php.net/manual/en/class.recursivetreeiterator.php
http://php.net/manual/en/class.recursivetreeiterator.php
There is also some control over the ASCII representation of the tree by changing the prefixes using RecursiveTreeIterator::setPrefixPart
, for example $it->setPrefixPart(RecursiveTreeIterator::PREFIX_LEFT, "|");
RecursiveTreeIterator::setPrefixPart
例如,通过使用 更改前缀,还可以对树的 ASCII 表示进行一些控制$it->setPrefixPart(RecursiveTreeIterator::PREFIX_LEFT, "|");
回答by WonderLand
In case you want to use directoryIterator
如果您想使用 directoryIterator
Following function is a re-implementation of @Shef answer with directoryIterator
以下功能是@Shef answer的重新实现 directoryIterator
function listFolderFiles($dir)
{
echo '<ol>';
foreach (new DirectoryIterator($dir) as $fileInfo) {
if (!$fileInfo->isDot()) {
echo '<li>' . $fileInfo->getFilename();
if ($fileInfo->isDir()) {
listFolderFiles($fileInfo->getPathname());
}
echo '</li>';
}
}
echo '</ol>';
}
listFolderFiles('Main Dir');
回答by Wesley van Opdorp
I'm really fond of SPL Library, they offer iterator's, including RecursiveDirectoryIterator.
我真的很喜欢 SPL 库,他们提供迭代器,包括RecursiveDirectoryIterator。
回答by Venkatesh Parihar
It will use to make menu bar in directory format
它将用于以目录格式制作菜单栏
$pathLen = 0;
function prePad($level)
{
$ss = "";
for ($ii = 0; $ii < $level; $ii++)
{
$ss = $ss . "| ";
}
return $ss;
}
function myScanDir($dir, $level, $rootLen)
{
global $pathLen;
if ($handle = opendir($dir)) {
$allFiles = array();
while (false !== ($entry = readdir($handle))) {
if ($entry != "." && $entry != "..") {
if (is_dir($dir . "/" . $entry))
{
$allFiles[] = "D: " . $dir . "/" . $entry;
}
else
{
$allFiles[] = "F: " . $dir . "/" . $entry;
}
}
}
closedir($handle);
natsort($allFiles);
foreach($allFiles as $value)
{
$displayName = substr($value, $rootLen + 4);
$fileName = substr($value, 3);
$linkName = str_replace(" ", " ", substr($value, $pathLen + 3));
if (is_dir($fileName))
{
echo "<li ><a class='dropdown'><span>" . $displayName . " </span></a><ul>";
myScanDir($fileName, $level + 1, strlen($fileName));
echo "</ul></li>";
}
else {
$newstring = substr($displayName, -3);
if($newstring == "PDF" || $newstring == "pdf" )
echo "<li ><a href=\"" . $linkName . "\" style=\"text-decoration:none;\">" . $displayName . "</a></li>";
}
$t;
if($level != 0)
{
if($level < $t)
{
$r = int($t) - int($level);
for($i=0;$i<$r;$i++)
{
echo "</ul></li>";
}
}
}
$t = $level;
}
}
}
?>
<li style="color: #ffffff">
<?php
// ListFolder('D:\PDF');
$root = 'D:\PDF';
$pathLen = strlen($root);
myScanDir($root, 0, strlen($root));
?>
</li>
回答by Faisal
If you're looking for a recursive directory listing solutions and arrange them in a multidimensional array. Use below code:
如果您正在寻找递归目录列出解决方案并将它们排列在多维数组中。使用以下代码:
<?php
/**
* Function for recursive directory file list search as an array.
*
* @param mixed $dir Main Directory Path.
*
* @return array
*/
function listFolderFiles($dir)
{
$fileInfo = scandir($dir);
$allFileLists = [];
foreach ($fileInfo as $folder) {
if ($folder !== '.' && $folder !== '..') {
if (is_dir($dir . DIRECTORY_SEPARATOR . $folder) === true) {
$allFileLists[$folder] = listFolderFiles($dir . DIRECTORY_SEPARATOR . $folder);
} else {
$allFileLists[$folder] = $folder;
}
}
}
return $allFileLists;
}//end listFolderFiles()
$dir = listFolderFiles('your searching directory path ex:-F:\xampp\htdocs\abc');
echo '<pre>';
print_r($dir);
echo '</pre>'
?>
回答by pritaeas
Have a look at glob()or the recursive directory iterator.
回答by Rijk
回答by lotfio
Here is A simple function with scandir
& array_filter
that do the job. filter
needed files using regex. I removed .
..
and hidden files like .htaccess
, you can also customise output using <ul>
and colors and also customise errors in case no scan or empty dirs!.
这是一个使用scandir
&array_filter
完成工作的简单函数。使用正则表达式过滤需要的文件。我删除.
..
和隐藏文件,例如.htaccess
,您还可以使用<ul>
和颜色自定义输出,并在没有扫描或空目录的情况下自定义错误!。
function getAllContentOfLocation($loc)
{
$scandir = scandir($loc);
$scandir = array_filter($scandir, function($element){
return !preg_match('/^\./', $element);
});
if(empty($scandir)) echo '<li style="color:red">Empty Dir</li>';
foreach($scandir as $file){
$baseLink = $loc . DIRECTORY_SEPARATOR . $file;
echo '<ol>';
if(is_dir($baseLink))
{
echo '<li style="font-weight:bold;color:blue">'.$file.'</li>';
getAllContentOfLocation($baseLink);
}else{
echo '<li>'.$file.'</li>';
}
echo '</ol>';
}
}
//Call function and set location that you want to scan
getAllContentOfLocation('../app');