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

时间:2013-08-07 16:40:53

标签: php datetime timestamp filesize

我正在修改一个简单的网站。该网站有一个页面,显示可供下载的客户端文件(如果适用)。目前这些文件只是随机顺序,没有具体细节。我希望能够根据它们提供的时间戳以降序排列它们。还包括他们的文件大小。这是使用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,所以感谢任何帮助。

1 个答案:

答案 0 :(得分:1)

这是一个可能有帮助的片段。

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

可以轻松更改为usort()Consult the PHP manual.

另请参阅arsort()函数。 Consult the PHP manual.

文件大小也包括在内,但它没有格式化为字节,kb等。有些功能可以将其格式化以适应。 Google “filesize format php”。 This link has that information.

<?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]);
}