无尽目录列表php


endless directory list php

我有这个php代码来列出目录中的所有文件,并输出文件大小和下载链接。

<?
function human_filesize($bytes, $decimals = 2) {
$size = array(' B',' kB',' MB',' GB',' TB',' PB',' EB',' ZB',' YB');
$factor = floor((strlen($bytes) - 1) / 3);
return sprintf("%.{$decimals}f", $bytes / pow(1024, $factor)) . @$size[$factor];
}
$excludedFiles = array('.','..');
$excludedExtensions = array ('html','htm','php');
// Convert to lower case so we are not case-sensitive
for ($i = 0; isset($excludedFiles[$i]); $i++) $excludedFiles[$i] = strtolower(ltrim($excludedFiles[$i],'.'));
for ($i = 0; isset($excludedExtensions[$i]); $i++) $excludedExtensions[$i] = strtolower($excludedExtensions[$i]);

// Define the full path to your folder from root
$dir = "./";
// Open the folder
$dir_handle = @opendir($dir) or die("Unable to open $dir");
// Loop through the files
while ($file = readdir($dir_handle)) {
$extn = explode('.',$file);
$extn = array_pop($extn);
if (!in_array(strtolower($file),$excludedFiles) && !in_array(strtolower($extn),$excludedExtensions)){
if($file == "." || $file == ".." )

continue;
echo "<tr>
      <td>
     <a class='Testo' href='"$file'" download>$file</a></td>
     <td><font class='TestoPiccoloBo'>[" . human_filesize(filesize($file)) . "]</font></td>
    </tr>";
 }
 }
// Close
closedir($dir_handle);

?>

我希望列表按字母顺序排列,所以我添加了

$files = scandir($dir);

$dir线和之后

foreach ($files as $file){

while ($file = readdir($dir_handle)) {线之后

} 

closedir($dir_handle);线之前

现在文件按字母顺序列出,但列表是无穷无尽的。这个列表一次又一次地开始,就像一个循环。我做错了什么?这是实现这一目标的正确方法吗?任何帮助都将不胜感激。谢谢

您可以将文件夹放在一个数组中,并使用php排序函数对其进行排序。然后打印:

<?
function human_filesize($bytes, $decimals = 2) {
$size = array(' B',' kB',' MB',' GB',' TB',' PB',' EB',' ZB',' YB');
$factor = floor((strlen($bytes) - 1) / 3);
return sprintf("%.{$decimals}f", $bytes / pow(1024, $factor)) . @$size[$factor];
}
$excludedFiles = array('.','..');
$arrayFiles = array();
$excludedExtensions = array ('html','htm','php');
// Convert to lower case so we are not case-sensitive
for ($i = 0; isset($excludedFiles[$i]); $i++) $excludedFiles[$i] = strtolower(ltrim($excludedFiles[$i],'.'));
for ($i = 0; isset($excludedExtensions[$i]); $i++) $excludedExtensions[$i] = strtolower($excludedExtensions[$i]);

// Define the full path to your folder from root
$dir = "./";
// Open the folder
$dir_handle = @opendir($dir) or die("Unable to open $dir");
// Loop through the files
while ($file = readdir($dir_handle)) {
$extn = explode('.',$file);
$extn = array_pop($extn);
if (!in_array(strtolower($file),$excludedFiles) && !in_array(strtolower($extn),$excludedExtensions)){
if($file == "." || $file == ".." )
continue;
$arrayFiles[] =  $file;
 }
 } // dunno what are these } so i put my loop after
// Close
closedir($dir_handle);
sort($arrayFiles);
foreach ($arrayFiles as $file) {
    echo "<tr>
      <td>
     <a class='Testo' href='"$file'" download>$file</a></td>
     <td><font class='TestoPiccoloBo'>[" . human_filesize(filesize($file)) . "]</font></td>
    </tr>";
}
?>