如何列出目录中的文件和文件夹(PHP)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4050511/
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
How to list files and folder in a dir (PHP)
提问by Rickstar
Hi I am trying to show all files and folders in a dir with php
嗨,我正在尝试使用 php 显示目录中的所有文件和文件夹
e.g
例如
Dir: system/infomation/
目录:系统/信息/
Folder- User
文件夹- 用户
Files From User- User1.txt
来自用户的文件- User1.txt
Files From User- User2.txt
来自用户的文件- User2.txt
Files From User- User3.txt
来自用户的文件- User3.txt
Files From User- User4.txt
来自用户的文件- User4.txt
Folder - Players
文件夹 -玩家
Files From Players- Player1.txt
来自玩家的文件- Player1.txt
Files From Players- Player2.txt
来自玩家的文件- Player2.txt
Files From Players- Player3.txt
来自玩家的文件- Player3.txt
Files From Players- Player4.txt
来自玩家的文件- Player4.txt
Can someone lead me down the right street please
有人能带我走正确的街道吗
Thank You
谢谢你
回答by Pekka
PHP 5 has the RecursiveDirectoryIterator
.
PHP 5 具有RecursiveDirectoryIterator
.
The manual has a basic example:
该手册有一个基本示例:
<?php
$directory = '/system/infomation/';
$it = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($directory));
while($it->valid()) {
if (!$it->isDot()) {
echo 'SubPathName: ' . $it->getSubPathName() . "\n";
echo 'SubPath: ' . $it->getSubPath() . "\n";
echo 'Key: ' . $it->key() . "\n\n";
}
$it->next();
}
?>
Edit-- Here's a slightly more advanced example (only slightly) which produces output similar to what you want (i.e. folder names then files).
编辑- 这是一个稍微更高级的示例(只是稍微),它产生的输出类似于您想要的(即文件夹名称然后是文件)。
// Create recursive dir iterator which skips dot folders
$dir = new RecursiveDirectoryIterator('./system/information',
FilesystemIterator::SKIP_DOTS);
// Flatten the recursive iterator, folders come before their files
$it = new RecursiveIteratorIterator($dir,
RecursiveIteratorIterator::SELF_FIRST);
// Maximum depth is 1 level deeper than the base folder
$it->setMaxDepth(1);
// Basic loop displaying different messages based on file or folder
foreach ($it as $fileinfo) {
if ($fileinfo->isDir()) {
printf("Folder - %s\n", $fileinfo->getFilename());
} elseif ($fileinfo->isFile()) {
printf("File From %s - %s\n", $it->getSubPath(), $fileinfo->getFilename());
}
}
回答by Lokesh
//path to directory to scan
$directory = "../data/team/";
//get all text files with a .txt extension.
$texts = glob($directory . "*.txt");
//print each file name
foreach($texts as $text)
{
echo $text;
}
回答by mario
You can use:
您可以使用:
foreach (new DirectoryIterator("./system/information/") as $fn) {
print $fn->getFilename();
}
You'll have to use it twice for each subdir, Players and User.
您必须为每个子目录、玩家和用户使用它两次。
回答by T.Todua
LIST FILES IN FOLDER - 1 solution
列出文件夹中的文件 - 1 个解决方案
<?php
// open this directory
$myDirectory = opendir(".");
// get each entry
while($entryName = readdir($myDirectory)) {
$dirArray[] = $entryName;
}
// close directory
closedir($myDirectory);
// count elements in array
$indexCount = count($dirArray);
Print ("$indexCount files<br>\n");
// sort 'em
sort($dirArray);
// print 'em
print("<TABLE border=1 cellpadding=5 cellspacing=0 class=whitelinks>\n");
print("<TR><TH>Filename</TH><th>Filetype</th><th>Filesize</th></TR>\n");
// loop through the array of files and print them all
for($index=0; $index < $indexCount; $index++) {
if (substr("$dirArray[$index]", 0, 1) != "."){ // don't list hidden files
print("<TR><TD><a href=\"$dirArray[$index]\">$dirArray[$index]</a></td>");
print("<td>"); print(filetype($dirArray[$index])); print("</td>");
print("<td>"); print(filesize($dirArray[$index])); print("</td>");
print("</TR>\n");
}
}
print("</TABLE>\n");
?>
2 solution
2 解决方案
<?PHP
# The current directory
$directory = dir("./");
# If you want to turn on Extension Filter, then uncomment this:
### $allowed_ext = array(".sample", ".png", ".jpg", ".jpeg", ".txt", ".doc", ".xls");
## Description of the soft: list_dir_files.php
## Major credits: phpDIRList 2.0 -(c)2005 Ulrich S. Kapp :: Systemberatung ::
$do_link = TRUE;
$sort_what = 0; //0- by name; 1 - by size; 2 - by date
$sort_how = 0; //0 - ASCENDING; 1 - DESCENDING
# # #
function dir_list($dir){
$i=0;
$dl = array();
if ($hd = opendir($dir)) {
while ($sz = readdir($hd)) {
if (preg_match("/^\./",$sz)==0) $dl[] = $sz;$i.=1;
}
closedir($hd);
}
asort($dl);
return $dl;
}
if ($sort_how == 0) {
function compare0($x, $y) {
if ( $x[0] == $y[0] ) return 0;
else if ( $x[0] < $y[0] ) return -1;
else return 1;
}
function compare1($x, $y) {
if ( $x[1] == $y[1] ) return 0;
else if ( $x[1] < $y[1] ) return -1;
else return 1;
}
function compare2($x, $y) {
if ( $x[2] == $y[2] ) return 0;
else if ( $x[2] < $y[2] ) return -1;
else return 1;
}
}else{
function compare0($x, $y) {
if ( $x[0] == $y[0] ) return 0;
else if ( $x[0] < $y[0] ) return 1;
else return -1;
}
function compare1($x, $y) {
if ( $x[1] == $y[1] ) return 0;
else if ( $x[1] < $y[1] ) return 1;
else return -1;
}
function compare2($x, $y) {
if ( $x[2] == $y[2] ) return 0;
else if ( $x[2] < $y[2] ) return 1;
else return -1;
}
}
##################################################
# We get the information here
##################################################
$i = 0;
while($file=$directory->read()) {
$file = strtolower($file);
$ext = strrchr($file, '.');
if (isset($allowed_ext) && (!in_array($ext,$allowed_ext)))
{
// dump
}
else {
$temp_info = stat($file);
$new_array[$i][0] = $file;
$new_array[$i][1] = $temp_info[7];
$new_array[$i][2] = $temp_info[9];
$new_array[$i][3] = date("F d, Y", $new_array[$i][2]);
$i = $i + 1;
}
}
$directory->close();
##################################################
# We sort the information here
#################################################
switch ($sort_what) {
case 0:
usort($new_array, "compare0");
break;
case 1:
usort($new_array, "compare1");
break;
case 2:
usort($new_array, "compare2");
break;
}
###############################################################
# We display the infomation here
###############################################################
$i2 = count($new_array);
$i = 0;
echo "<table border=1>
<tr>
<td width=150> File name</td>
<td width=100> File Size</td>
<td width=100>Last Modified</td>
</tr>";
for ($i=0;$i<$i2;$i++) {
if (!$do_link) {
$line = "<tr><td align=right>" .
$new_array[$i][0] .
"</td><td align=right>" .
number_format(($new_array[$i][1]/1024)) .
"k";
$line = $line . "</td><td align=right>" . $new_array[$i][3] . "</td></tr>";
}else{
$line = '<tr><td align=right><A HREF="' .
$new_array[$i][0] . '">' .
$new_array[$i][0] .
"</A></td><td align=right>";
$line = $line . number_format(($new_array[$i][1]/1024)) .
"k" . "</td><td align=right>" .
$new_array[$i][3] . "</td></tr>";
}
echo $line;
}
echo "</table>";
?>
回答by Abooddy Hello
use this function http://www.codingforums.com/showthread.php?t=71882
使用这个功能http://www.codingforums.com/showthread.php?t=71882
function getDirectory( $path = '.', $level = 0 ){
$ignore = array( 'cgi-bin', '.', '..' );
// Directories to ignore when listing output. Many hosts
// will deny PHP access to the cgi-bin.
$dh = @opendir( $path );
// Open the directory to the handle $dh
while( false !== ( $file = readdir( $dh ) ) ){
// Loop through the directory
if( !in_array( $file, $ignore ) ){
// Check that this file is not to be ignored
$spaces = str_repeat( ' ', ( $level * 4 ) );
// Just to add spacing to the list, to better
// show the directory tree.
if( is_dir( "$path/$file" ) ){
// Its a directory, so we need to keep reading down...
echo "<strong>$spaces $file</strong><br />";
getDirectory( "$path/$file", ($level+1) );
// Re-call this same function but on a new directory.
// this is what makes function recursive.
} else {
echo "$spaces $file<br />";
// Just print out the filename
}
}
}
closedir( $dh );
// Close the directory handle
}
and call the function like that
并像这样调用函数
getDirectory( "." );
// Get the current directory
getDirectory( "./files/includes" );
// Get contents of the "files/includes" folder
回答by Kel
You may use Directory Functions: http://php.net/manual/en/book.dir.php
您可以使用目录功能:http: //php.net/manual/en/book.dir.php
Simple example from opendir()function description:
来自opendir()函数描述的简单示例:
<?php
$dir_path = "/path/to/your/dir";
if (is_dir($dir_path)) {
if ($dir_handler = opendir($dir_path)) {
while (($file = readdir($dir_handler)) !== false) {
echo "filename: $file : filetype: " . filetype($dir_path . $file) . "\n";
}
closedir($dir_handler);
}
}
?>
回答by Mathias
Use glob. There are comprehensive guide how to open all files from dir: PHP: Using functional programming for listing files and directories
使用全局。有全面的指南如何从 dir 打开所有文件: PHP:使用函数式编程列出文件和目录
回答by joni
Use the Dir class or opendir()
and readdir()
in a recursive function.
在递归函数中使用 Dir 类或opendir()
和readdir()
。
http://www.php.net/manual/en/class.dir.php
http://www.php.net/manual/en/class.dir.php
http://ch2.php.net/manual/en/function.opendir.php
http://ch2.php.net/manual/en/function.opendir.php
回答by jLuengas
I've found in www.laughing-buddha.net/php/lib/dirlist/ a function that returns an array containing a list of a directory's contents.
我在 www.laughing-buddha.net/php/lib/dirlist/ 中找到了一个函数,该函数返回一个包含目录内容列表的数组。
Also look at php.net http://es.php.net/manual/es/ref.filesystem.phpwhere you'll find additional functions for working with files in php.
另请查看 php.net http://es.php.net/manual/es/ref.filesystem.php,您将在其中找到用于在 php 中处理文件的其他功能。
回答by Menios
Have a look at building a simple directory browser using php RecursiveDirectoryIterator
看看使用 php RecursiveDirectoryIterator 构建一个简单的目录浏览器
Also, as you mentioned you want to list you can also look at some ready made libraries that create file/folder explorers e.g.:
此外,正如您提到的,您想列出您还可以查看一些创建文件/文件夹资源管理器的现成库,例如: