PHP按日期/时间和文件大小对文件进行排序


PHP Sorting files by Date/time and file size

我正在修改一个简单的网站。此网站有一个页面,显示可供下载的客户端文件(如果适用)。目前,这些文件只是随机排列的,没有具体的细节。我希望能够根据它们提供的时间戳将它们按适当的顺序排列。还包括它们的文件大小。这是使用php来显示文件,在显示它们之前,我需要对目录进行排序吗?如果是的话,那会是一个单独的脚本吗?什么时候运行?或者我可以按照以下代码中显示的方式对它们进行排序吗?

<div id="f2">
<h3>Files Available for Download</h3>
<p>
<?php
// list contents of user directory
if (file_exists($USER_DIRECTORY)) {
    if ($handle = opendir($USER_DIRECTORY)) {
        while (false !== ($entry = readdir($handle))) {
            if ($entry != "." && $entry != "..") {
                echo "<a href='download_file.php?filename=".urlencode($entry)."'>".$entry."</a><br/>";
            }
        }
    closedir($handle);
    }
}
?>
</p>
</div>

php非常新,所以任何帮助都将不胜感激。

这里有一个片段可能会有所帮助

它从指定的每个文件或文件扩展名中生成一个href。修改以适应。

  • 它目前被编码为使用asort()函数。请参阅PHP手册

可以很容易地将其更改为usort()。请参阅PHP手册。

另请参见arsort()函数。请参阅PHP手册。

文件大小也包括在内,但它没有格式化为字节、kb等。有一些函数可以根据需要对其进行格式化谷歌";文件大小格式php"此链接包含该信息

<?php
// You can use the desired folder to check and comment the others.
// foreach (glob("../downloads/*") as $path) { // lists all files in sub-folder called "downloads"
foreach (glob("test/*") as $path) { // lists all files in folder called "test"
//foreach (glob("*.php") as $path) { // lists all files with .php extension in current folder
    $docs[$path] = filectime($path);
} asort($docs); // sort by value, preserving keys
foreach ($docs as $path => $timestamp) {
    print date("d M. Y: ", $timestamp);
    print '<a href="'. $path .'">'. basename($path) .'</a>' . " Size: " . filesize($path) .'<br />';
}
?>

从链接中拉出http://codebyte.dev7studios.com/post/1590919646/php-format-filesize,如果它不再存在:

function filesize_format($size, $sizes = array('Bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'))
{
    if ($size == 0) return('n/a');
    return (round($size/pow(1024, ($i = floor(log($size, 1024)))), 2) . ' ' . $sizes[$i]);
}