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

Asked

Viewed 112 times

1

Guys need to limit the amount of files that will be displayed in a certain directory.

This is my php code 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 sent to this directory ?

1 answer

0

If we consider the file modification date, 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 function of glob do alone what your code does: take the complete list of files. Stick to the character * in its parameter, because it is a joker that causes all files to be listed. If you wanted files from only one specific extension, you could do /arquivos/*.pdf, for example. The function usort sorts the list of files according to the date of file modification, which is recovered through the function filemtime. Finally, only the first five files are extracted from the list.

  • Vlw Anderson is that code anyway, now help me to just display the file name. Ex: With this code it displays: files/doc.txt I need it to display: doc.txt Thanks in advance.

  • Just use the function explode using the character / as delimiter and get the last position of the array. Or rather, use the function pathinfo.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.