Check and list files from a PHP directory

Asked

Viewed 33 times

0

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

The images are stored in the directory:

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

Where it is 11 and 12, I was able to identify that is the ID of the news in the database and 11_1 is another photo of ID 11. As there is a lot of news, I would have to redo the whole system, but this is not the proposal of the client so I need to bring these images to the site. How would I list the ID images? Some news doesn’t have a photo, so I’m doing it this way:

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;
}

Only it’s not working.

1 answer

1


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

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

foreach ($imagens as $imagem) {
    // ...
}
  • Thank you again Anderson.

Browser other questions tagged

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