Check and list the files of a directory with PHP

0

I recently picked up a maintenance system developed in PHP. The previous colleague did not store upload images in the database or directory. To list the images, the reasoning is more or less this way:

Images are stored in the directory:

imagens/noticias/noticia_11.jpg
imagens/noticias/noticia_11_1.jpg
imagens/noticias/noticia_12.jpg

Where is 11 and 12, I was able to identify what the News ID is in the database, and 11_1 is another ID 11 photo. As there is a lot of news, I would have to redo the whole system, but that is not the client then I need to bring those images to the site. How would I list the ID images? Some news has no photo, so I'm doing it like this:

Upload allows up to 10 images:

public function listarFotos($idNoticia)
{
   ....
   for($foto = 1; $foto <= 10; $foto++)   
   {
     $foto = 'imagens/noticias/noticia/'.$idNoticia.'_'.$foto.'.jpg';
     if(file_exists($foto))
     {
       $visualizar .= '<img src="'.$foto.'">';
     }
  }
 return $visualizar;
}

It's just not working.

    
asked by anonymous 26.12.2018 / 19:08

1 answer

1

You can use the glob function to list the files from a regular expression:

$id = 11;
$imagens = glob("imagens\/noticias\/noticia_{$id}(_\d+)?\.jpg");

foreach ($imagens as $imagem) {
    // ...
}
    
26.12.2018 / 19:15