Frage

I am working on modifying a simple website. This website has a page that shows a clients files available for download(if applicable). At the moment these files are just in random order with no specific details. I would like to be able to have them in decending order based on time stamp that they were made available. Also including their file size. This is using php to show the files, do I need to have the directory already sorted before displaying them? if so would that be a separate script and when would it be run? Or can I sort them as they are displayed in the follwoing code?

<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>

Very new to php, so any help is appreciated.

War es hilfreich?

Lösung

Here's a snippet which could be of help.

It makes an href out of each file or file extension specified. Modify to suit.

It can easily be changed to usort(). Consult the PHP manual.

See also the arsort() function. Consult the PHP manual.

The filesize is also included, yet it is not formatted as bytes, kb etc. There are functions out there that will format it to suit. 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 />';
}
?>

Pulled from that link http://codebyte.dev7studios.com/post/1590919646/php-format-filesize, should it ever cease to exist:

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]);
}
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top