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

2

I have a project and there are several folders containing image files belonging to the 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, thus becoming: localhost/?g=diretorio1%2Fgaleria1%2F .

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

I do not have much of a PHP notion, preferably guide me through articles or detail the answer so I can understand.

    
asked by anonymous 03.01.2015 / 15:32

2 answers

2

Separating by parts:

How to read URL parameters:

This information you pass in the URL can be captured via $_GET , so 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 directory saved in a variable.

How to read only the 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>';
}
    
03.01.2015 / 15:42
1

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

The way I used glob does not have to enter the path in the url in the image.

<?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 it is JPG, put the extension to use.

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

<?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>';
}
?>
    
03.09.2015 / 17:29