How to list files in PHP with a specific name?

Asked

Viewed 1,285 times

3

Good Morning I held the code below.

 <?php
 $diretorio = "../../arquivos/nest"; 
 $ponteiro  = opendir($diretorio);
 while ($nome_itens = readdir($ponteiro)) {
$itens[] = $nome_itens;
}
sort($itens);
foreach ($itens as $listar) {
if ($listar!="." && $listar!=".."){ 
            if (is_dir($listar)) { 
                    $pastas[]=$listar; 
            } else{ 
                    $arquivos[]=$listar;
            }
   }
}
if ($pastas != "" ) { 
foreach($pastas as $listar){
print "<img src='pasta.png'> <a href='$diretorio/$listar'download>$listar</a><br>";} 
   }
if ($arquivos != "") {
foreach($arquivos as $listar){
print "<a href='$diretorio/$listar' download>$listar</a><br>";}
}
?>

The Code works correctly, my doubt is. I want to create a variable that will have a specific text and that will serve as a filter to show the files you have in the directory with the variable in question.

Example: In the variable contain the information "Cars", when generating the listing only appear the files in the directories that have the file name "Cars".

  • 1

    This code there I think is from the site PHP Brazil. It’s a little outdated

1 answer

7


I think you did it in the most complicated way possible.

It was simpler to use the function glob containing the desired expression:

 $expr = '/caminho/para/pasta/Carros*.txt';

 foreach (glob($expr) as $path) {
       echo $path;
 }

Another way is by using the function strpos to know if you have the desired part in the file name.

In case, I will use a more current way to list directories, which is through the FileSystemIterator

$arquivos = array();
$termo = 'Carros';
$iterator = new FileSystemIterator('diretório/desejado/aqui');
foreach ($iterator as $file) {

      $filename = $file->getRealpath();

      if (strpos($filename, $termo) !== false) {
         $arquivos[] = $filename;
      }
}
  • Thanks for the return, the first worked right, but shows all the path of the directory, The most current form your is appearing error, PHP Parse error: syntax error, unexpected '[' in the row of the variable $files.

  • 1

    @Junior this is because your php version is old, do $arquivos = array();

  • Thank you, @Miguel, that’s right. I even changed the answer so he understands better

  • @Nothing wallacemaxters, I saw it could only be that. Good morning

  • my version of PHP 5.2

Browser other questions tagged

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