Lista wszystkich podfolderów folderów i plików w katalogu za pomocą php
Proszę dać mi rozwiązanie do listowania wszystkich folderów,podfolderów, plików w katalogu za pomocą php. Moja struktura folderów wygląda tak:
Main Dir
Dir1
SubDir1
File1
File2
SubDir2
File3
File4
Dir2
SubDir3
File5
File6
SubDir4
File7
File8
Chcę uzyskać listę wszystkich plików w każdym folderze.
Czy w php jest jakieś polecenie skryptu powłoki?
15 answers
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');
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-05-21 14:16:28
Ten kod wyświetla wszystkie katalogi i pliki w kolejności posortowanej w widoku drzewa. Jest to generator mapy witryny z hiperłączami do wszystkich zasobów witryny. Pełne źródło strony znajduje się tutaj. Musisz zmienić ścieżkę na dziewiątej linii od końca.
<?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>
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-07-15 12:29:36
In case you want to use directoryIterator
Następująca funkcja jest re-implementacją odpowiedzi @ Shef z 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');
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-12-11 14:01:00
Bardzo prosty sposób wyświetlania struktury folderów wykorzystuje klasę RecursiveTreeIterator
(PHP 5 >= 5.3.0, PHP 7) i generuje drzewo graficzne 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
Istnieje również pewna kontrola nad reprezentacją drzewa ASCII poprzez zmianę prefiksów za pomocą RecursiveTreeIterator::setPrefixPart
, na przykład $it->setPrefixPart(RecursiveTreeIterator::PREFIX_LEFT, "|");
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-05-31 14:29:58
Bardzo lubię Biblioteki SPL, oferują Iteratory, w tym RecursiveDirectoryIterator .
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2011-08-19 12:27:17
Spójrz na glob () lub na recursive directory iterator .
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2011-08-19 12:24:43
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2011-08-19 12:25:05
Służy do tworzenia paska menu w formacie katalogu
$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>
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-08-24 12:45:50
function GetDir($dir) {
if(is_dir($dir)) {
if($kami= opendir($dir)){
while($file = readdir($kami)){
if($file != '.' && $file != '..'){
if(is_dir($dir . $file)){
echo $dir . $file;
// since it is a directory we recurse it.
GetDir($dir . $file . '/');
}else{
echo $dir . $file;
}
}
}
}
closedir($kami);
}
}
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-05-06 12:10:00
Jeśli szukasz rekurencyjnego katalogu z listą rozwiązań i ułóż je w wielowymiarową tablicę. Użyj poniższego kodu:
<?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>'
?>
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-05-27 18:33:31
Oto prosta funkcja z scandir
& array_filter
to wystarczy. filtr
potrzebne pliki używając regex. Usunąłem .
..
i ukryte pliki, takie jak .htaccess
, można również dostosować wyjście za pomocą <ul>
i kolorów, a także dostosować błędy w przypadku braku skanowania lub pustych dirs!.
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');
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-07-03 17:01:52
Możesz również spróbować tego:
<?php
function listdirs($dir) {
static $alldirs = array();
$dirs = glob($dir . '/*', GLOB_ONLYDIR);
if (count($dirs) > 0) {
foreach ($dirs as $d) $alldirs[] = $d;
}
foreach ($dirs as $dir) listdirs($dir);
return $alldirs;
}
$directory_list = listdirs('xampp');
print_r($directory_list);
?>
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-04-01 12:04:33
define ('PATH', $_SERVER['DOCUMENT_ROOT'] . dirname($_SERVER['PHP_SELF']));
$dir = new DirectoryIterator(PATH);
echo '<ul>';
foreach ($dir as $fileinfo)
{
if (!$fileinfo->isDot()) {
echo '<li><a href="'.$fileinfo->getFilename().'" target="_blank">'.$fileinfo->getFilename().'</a></li>';
echo '</li>';
}
}
echo '</ul>';
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-04-01 12:31:03
Późno na pokaz, ale aby zbudować zaakceptowaną odpowiedź...
Jeśli chcesz mieć wszystkie pliki i katalogi w tablicy (która może być ładnie upiększona za pomocą JSON.stringify w javascript), możesz zmodyfikować funkcję do:
function listFolderFiles($dir) {
$arr = array();
$ffs = scandir($dir);
foreach($ffs as $ff) {
if($ff != '.' && $ff != '..') {
$arr[$ff] = array();
if(is_dir($dir.'/'.$ff)) {
$arr[$ff] = listFolderFiles($dir.'/'.$ff);
}
}
}
return $arr;
}
Dla początkujących...
Aby użyć wspomnianego JSON.stringify
, twoje JS/jQuery byłoby coś w stylu:
var ajax = $.ajax({
method: 'POST',
data: {list_dirs: true}
}).done(function(msg) {
$('pre').html(
'FILE LAYOUT<br/>' +
JSON.stringify(JSON.parse(msg), null, 4)
);
});
^ zakładając, że masz gdzieś element <pre>
w swoim HTML. Dowolne wystarczy AJAX, ale domyślam się, że większość ludzi używa czegoś podobnego do jQuery powyżej.
I towarzyszące PHP:
if(isset($_POST['list_dirs'])) {
echo json_encode(listFolderFiles($rootPath));
exit();
}
Gdzie już masz listFolderFiles
z przeszłości.
W moim przypadku ustawiłem mój $rootPath
do katalogu głównego strony...
$rootPath;
if(!isset($rootPath)) {
$rootPath = $_SERVER['DOCUMENT_ROOT'];
}
Efekt końcowy jest podobny...
| some_file_1487.smthng []
| some_file_8752.smthng []
| CSS
| | some_file_3615.smthng []
| | some_file_8151.smthng []
| | some_file_7571.smthng []
| | some_file_5641.smthng []
| | some_file_7305.smthng []
| | some_file_9527.smthng []
|
| IMAGES
| | some_file_4515.smthng []
| | some_file_1335.smthng []
| | some_file_1819.smthng []
| | some_file_9188.smthng []
| | some_file_4760.smthng []
| | some_file_7347.smthng []
|
| JSScripts
| | some_file_6449.smthng []
| | some_file_7864.smthng []
| | some_file_3899.smthng []
| | google-code-prettify
| | | some_file_2090.smthng []
| | | some_file_5169.smthng []
| | | some_file_3426.smthng []
| | | some_file_8208.smthng []
| | | some_file_7581.smthng []
| | | some_file_4618.smthng []
| |
| | some_file_3883.smthng []
| | some_file_3713.smthng []
... and so on...
uwaga: twój nie będzie wyglądał dokładnie tak - zmodyfikowałem JSON.stringify
, aby wyświetlać tabulatory( pionowe rury), wyrównywać wszystkie wartości klawiszy, usuwać cytaty z kluczy i kilka innych rzeczy. Będę modyfikować tę odpowiedź z linkiem, jeśli kiedykolwiek dostać się do uploading go, lub uzyskać wystarczająco dużo zainteresowania.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-05-23 12:34:50
Szukałem podobnej funkcji do tej. Potrzebowałem katalogów jako kluczy i podkatalogów jako tablic i plików po prostu być umieszczone jako wartości.
Użyłem następującego kodu:
/**
* Return an array of files found within a specified directory.
* @param string $dir A valid directory. If a path, with a file at the end,
* is passed, then the file is trimmed from the directory.
* @param string $regex Optional. If passed, all file names will be checked
* against the expression, and only those that match will
* be returned.
* A RegEx can be just a string, where a '/' will be
* prefixed and a '/i' will be suffixed. Alternatively,
* a string could be a valid RegEx string.
* @return array An array of all files from that directory. If regex is
* set, then this will be an array of any matching files.
*/
function get_files_in_dir(string $dir, $regex = null)
{
$dir = is_dir($dir) ? $dir : dirname($dir);
// A RegEx to check whether a RegEx is a valid RegEx :D
$pass = preg_match("/^([^\\\\a-z ]).+([^\\\\a-z ])[a-z]*$/i", $regex, $matches);
// Any non-regex string will be caught here.
if (isset($regex) && !$pass) {
//$regex = '/'.addslashes($regex).'/i';
$regex = "/$regex/i";
}
// A valid regex delimiter with different delimiters will be caught here.
if (!empty($matches) && $matches[1] !== $matches[2]) {
$regex .= $matches[1] . 'i'; // Append first delimiter and i flag
}
try {
$files = scandir($dir);
} catch (Exception $ex) {
$files = ['.', '..'];
}
$files = array_slice($files, 2); // Remove '.' and '..'
$files = array_reduce($files, function($carry, $item) use ($regex) {
if ((!empty($regex) && preg_match($regex, $item)) || empty($regex)) {
array_push($carry, $item);
}
return $carry;
}, []);
return $files;
}
function str_finish($value, $cap)
{
$quoted = preg_quote($cap, '/');
return preg_replace('/(?:'.$quoted.')+$/u', '', $value).$cap;
}
function get_directory_tree($dir)
{
$fs = get_files_in_dir($dir);
$files = array();
foreach ($fs as $k => $f) {
if (is_dir(Str::finish($dir, '/').$f)) {
$fs[$f] = get_directory_tree(Str::finish($dir, '/').$f);
} else {
$files[] = $f;
}
unset($fs[$k]);
}
$fs = array_merge($fs, $files);
return $fs;
}
Jest wiele do przyjęcia.
Pierwsza funkcja get_files_in_dir
funkcja została stworzona tak, że mogłem pobrać wszystkie pliki i foldery w katalogu opartym na wyrażeniu regularnym. Używam go tutaj, ponieważ ma pewne sprawdzanie błędów, aby upewnić się, że katalog jest przekonwertowany na tablicę.
Następnie mamy prosta funkcja, która po prostu dodaje ukośnik do końca łańcucha, jeśli jeszcze go nie ma.
Wreszcie, mamy funkcję get_directory_tree
, która będzie iterować przez wszystkie foldery i podfoldery i utworzyć tablicę asocjacyjną, gdzie nazwy folderów są kluczami, a pliki są wartościami (chyba że folder ma podfoldery).
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-08-30 11:52:01