PHP - Getting all images from a directory and generating in HTML

Asked

Viewed 5,843 times

2

I have a project and there are several folders containing image files belonging to gallery: I need to optimize this by getting all the images from a given directory and generating them in HTML.

Basically the project receives the directory in a parameter of the URL, being thus below: localhost/?g=diretorio1%2Fgaleria1%2F.

In this case all files in the directory 'directory1/galeria1/' will be filtered to accept only image files and soon after the HTML code will be generated <a href=""><img src="diretorio1/galeria1/x" /></a>. Where x = name and extension of each image file.

I don’t have much notion of PHP, preferably orient me with articles or detail the answer so I can understand.

2 answers

2


Parting:

How to read URL parameters:

This information you pass in the URL can be captured via $_GET, then you’ll have to decode using rawurldecode().

For example:

$parametro_g = $_GET['g'];
$diretoria = rawurldecode($parametro_g); // que é o mesmo que rawurldecode('diretorio1%2Fgaleria1%2F'); no exemplo que deste

So you have the board stored in a variable.

How to read only images in the directory and generate HTML

$diretoria = "diretorio1/galeria1/"; // esta linha não precisas é só um exemplo do conteudo que a variável vai ter

// selecionar só .jpg
$imagens = glob($diretoria . "*.jpg");

// fazer echo de cada imagem
foreach($imagens as $imagem){
  echo '<a href=""><img src="diretorio1/galeria1/'.$imagem.'" /></a>';
}
  • It worked perfectly! Thank you :-)

  • I could understand most of it, in this case how can I add the png extension (*. png) ? It would be glob($directory . " *. jpg", $directory . " *. png") ?

  • I found it. It’s glob($directory . " *. {jpg,png,gif}", GLOB_BRACE);

  • The correct thing would be to only list images that are in the directory.

1

Instead of using $_GET, utilize $_REQUEST, with it the same url supports POST and GET.

The way I used glob does not need to inform the path in the url in img.

<?php

    $caminho = rawurldecode($_REQUEST['g']);
        $img = glob($caminho."*.{jpg}", GLOB_BRACE);
        $contador = count($img);

foreach($img as $img){
  echo '<a href=""><img src="'.$img.'" /></a>';
}
?>

Note: Example above, if you are JPG, put the extension you are going to use.

If you want to read all image files, even from other extensions you can group them.

<?php

    $caminho = rawurldecode($_REQUEST['g']);
        $img = glob($caminho."*.{jpg,png,gif}", GLOB_BRACE);
        $contador = count($img);

foreach($img as $img){
  echo '<a href=""><img src="'.$img.'" /></a>';
}
?>
  • As quoted above, rawurldecode decodes the browser-encoded URL.

Browser other questions tagged

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