How to Sort Files by Date in PHP

How to sort files by date in PHP

You need to put the files into an array in order to sort and find the last modified file.

$files = array();
if ($handle = opendir('.')) {
while (false !== ($file = readdir($handle))) {
if ($file != "." && $file != "..") {
$files[filemtime($file)] = $file;
}
}
closedir($handle);

// sort
ksort($files);
// find the last modification
$reallyLastModified = end($files);

foreach($files as $file) {
$lastModified = date('F d Y, H:i:s',filemtime($file));
if(strlen($file)-strpos($file,".swf")== 4){
if ($file == $reallyLastModified) {
// do stuff for the real last modified file
}
echo "<tr><td><input type=\"checkbox\" name=\"box[]\"></td><td><a href=\"$file\" target=\"_blank\">$file</a></td><td>$lastModified</td></tr>";
}
}
}

Not tested, but that's how to do it.

Sort file list by date

You could use PHP's glob function and a custom sorting function like this:

<?php
$sub = ($_GET['dir']);
$path = 'groundfish-meetings/';
$path = $path . "$sub";
$file_list = glob($path."*.pdf");

function sort_by_mtime($file1,$file2) {
$time1 = filemtime($file1);
$time2 = filemtime($file2);
if ($time1 == $time2) {
return 0;
}
return ($time1 < $time2) ? 1 : -1;
}
usort($file_list ,"sort_by_mtime");
$i = 1;
foreach($file_list as $file)
{
echo "$i. <option value='" . home_url('/groundfish-meetings/' . $file) .
"'>$file</option>";
$i++;
}

Sorting files by creation/modification date in PHP

save their information to an array, sort the array and then loop the array

if($h = opendir($dir)) {
$files = array();
while(($file = readdir($h) !== FALSE)
$files[] = stat($file);

// do the sort
usort($files, 'your_sorting_function');

// do something with the files
foreach($files as $file) {
echo htmlspecialchars($file);
}
}

How to sort by date files in a directory using php

Give this a try.

First we make an array with all the file names in it. Then we make one query and use the WHERE IN clause to find all the results. We tell the query to organize those results in a descending order from the date they were uploaded.

We then use a proper parameterized Mysqli query to get the results from the database.

Once we have the results we loop through them and populate your table rows.

Don't forget to replace the field value in the query with the correct column name other wise this will not work correctly.

$path = $dpath . $lpath;

if ($handle = opendir($path)) {

while (false !== ($file = readdir($handle))) {

$dbfname = $path.$file;
if ($file != "." && $file != "..") {

$fileNames[] = $dbfname;

}

}

closedir($handle);

}

if($fileNames){

$clause = implode(',', array_fill(0, count($fileNames), '?'));
$types = str_repeat('s', count($fileNames));
//You will need to change date_field to the column that has the upload dateTime value stored in it.
$sql = "SELECT uploader, course, date_field, filename FROM assignments WHERE filename IN ($clause) ORDER BY date_field DESC";
$stmt = $conn->prepare($sql);
$stmt->bind_param($types, ...$fileNames);
$stmt->execute();
$results = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);

}

if($results){

foreach($results as $row){

echo
'<tr>

<td>
<a href="' . $row['filename'] . '"' . 'download="' . basename($row['filename']) . '">' . basename($row['filename']) . '</a>
</td>' .

'<td>' . $row['course'] . '</td>' .

'<td>' . $row['uploader'] . '</td>' .

'<td>' . date('d M Y [H:i:s]', strtotime($row['date_field'])) . '</td>' . //The date_time field is used here too.

'<td>' . filesize($row['filename']) . '</td>' .

'</tr>';


}

}else{

echo
'<tr><td>No results were found</td></tr>';

}

PHP Sorting files by Date/time and file size

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 is presently coded to use the asort() function. Consult the PHP manual.

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

Sort files by date added Laravel PHP

Something like this should do the trick:

public function getPhotos($nav, $page = false)
{
$dir = 'img/' . $nav;

if ($page !== false) {
$dir .= '/' . $page;
}

return $files = collect(File::allFiles($dir))
->filter(function ($file) {
return in_array($file->getExtension(), ['png', 'gif', 'jpg']);
})
->sortBy(function ($file) {
return $file->getCTime();
})
->map(function ($file) {
return $file->getBaseName();
});

}

Hope this helps!

Sort files with filemtime

function scan_dir($dir) {
$ignored = array('.', '..', '.svn', '.htaccess');
$files = array();
foreach (scandir($dir) as $file) {
if (in_array($file, $ignored)) {
continue;
}
$filemtime = filemtime($dir . '/' . $file);
$files[$file] = $filemtime;
}

arsort($files);
$files = array_keys($files);

return ($files) ? $files : false;
}

$src_folder = 'gallery';

$files = scan_dir($src_folder);

foreach($files as $file) {
echo $file . ' - ' . date ("F d Y H:i:s.", filemtime($src_folder.'/'.$file)) . '<br>';
}


Related Topics



Leave a reply



Submit