Limit the amount of files that will be displayed in a directory

1

I need to limit the amount of files that will be displayed in a given directory.

This is my code in php that lists the files in my directory:

<?php 

$diretorio = getcwd(). "/arquivos" ; 

$ponteiro  = opendir($diretorio);

while ($nome_itens = readdir($ponteiro)) 

  $itens[] = $nome_itens;

sort ($itens);

foreach ( $itens as $listar )

if ( $listar!="." && $listar!="..")

print '.$listar.';

?>

Is there any way to increment this code so that it displays only the last 5 files uploaded to this directory?

    
asked by anonymous 06.04.2017 / 19:30

1 answer

0

If we consider the date of modification of the file, we can do the following:

// Recupera a lista de todos os arquivos:
$files = glob("/arquivos/*");

// Ordena os arquivos pela data de modificacão:
usort($files, function ($a, $b) { return filemtime($a) < filemtime($b); });

// Pega apenas os cinco últimos modificados:
$files = array_slice($files, 0, 5);

Basically, the glob function does itself what its code does: it takes the complete list of files. Notice the * character in your parameter, since it is a wildcard that causes all files to be listed. If you wanted files of only one specific extension, you could do /arquivos/*.pdf , for example. The usort function sorts the file list according to the file modification date, which is retrieved through the filemtime function. Finally, only the first five files in the list are extracted.

    
06.04.2017 / 19:47