Php script for Listing files based on last modified time

josejohnson63

New Member
Messages
9
Reaction score
0
Points
1
Here is the php script to list the files in a folder based on the modified date

Using the below script you can list files from older to latest or latest to oldest

<?php
// list from a given folder $folder="test/";

$files = glob( $folder."*.*" ); // to avoid hidden files


// Sort files by modified time, latest to oldest


array_multisort(array_map( 'filemtime', $files ),SORT_NUMERIC,SORT_DESC,$files);


// Use SORT_ASC in place of SORT_DESC for oldest to latest
//array_multisort(array_map( 'filemtime', $files ),SORT_NUMERIC,SORT_ASC,$files);


// display the file names
if(count($files)){


for( $i=0 ; $i < count($files) ; $i++ ){


echo(basename($files[$i])." <a href='".$folder.$files[$i]."'>Link to the file</a><br>");


}


}

?>
 

misson

Community Paragon
Community Support
Messages
2,572
Reaction score
72
Points
48
Please use
PHP:
, [html] or [code] tags (as appropriate) to separate and format code.

[quote="josejohnson63, post: 890847"][PHP]<?php
  $files = glob( $folder."*.*" );   // to avoid  hidden files
[/QUOTE]
glob won't list dotfiles by default, no matter the platform. You have to force it to include the by using a pattern that explicitly includes them (e.g. glob('.*') or glob('{.,}*', GLOB_BRACE)). This will include the current (".") and parent ("..") directories, which is why dotfiles are hidden on all platforms in the first place.

You may as well pass GLOB_NOSORT to glob, since the script sorts the files according to its own purposes.

PHP:
  // display the file names 
  if(count($files)){
In the script as written, there's no need for this test as the loop won't be entered when count($files) < 1.

PHP:
    echo(basename($files[$i])."   <a  href='".$folder.$files[$i]."'>Link to the file</a><br>");
<br/> isn't being used semantically; use something more appropriate, such as a paragraph or list element.

Link text should describe specifically what is linked to. "Link to the file" is too generic. Instead, you can use the file name as the link text.

PHP:
<ol>
  <?php foreach ($files as $file): ?>
    <li><a href="<?php echo $folder, $file ?>"><?php echo $file ?></a></li>
  <?php endforeach; ?>
</ol>
 
Top