On my website I want to display a grid with images and their names to the gallery. Through html, displaying 600+ images is somehow wrong, but through php images is output. But how to display their names under them?

<?php $directory = "../img"; $allowed_types=array("jpg", "png", "gif"); $file_parts = array(); $ext=""; $title=""; $i=0; $dir_handle = @opendir($directory) or die("Ошибка при открытии папки !!!"); while ($file = readdir($dir_handle)) { if($file=="." || $file == "..") continue; $file_name = basename($directory,".png"); $file_parts = explode(".",$file); $ext = strtolower(array_pop($file_parts)); if(in_array($ext,$allowed_types)) { echo '<img src="'.$directory.'/'.$file.'" class="pimg" title="'.$file.'" /><br><p>'+$file_name+'</p>'; $i++; } } closedir($dir_handle); ?> 
  • So output $file - Let's say Pie
  • if I print the $ file variable, then images disappear in the container and only 000 appear (three zeros) - Alex Novozhilov

1 answer 1

Try this option:

 $catalog = '../img/'; $all_files = glob("{$catalog}*.{jpg,png,gif}", GLOB_BRACE); for ($i = 0; $i < count($all_files); ++$i) { $image_name = $all_files[$i]; $supported_format = ['gif','jpg','png']; $ext = strtolower(pathinfo($image_name, PATHINFO_EXTENSION)); $name_d[] = explode($catalog, $image_name)[1]; if (in_array($ext, $supported_format)) { echo ' <img src="'.$image_name.'" class="pimg" alt="'.$name_d[$i].'" /> <br><p>'.$name_d[$i].'</p> '; } else { continue; } } 
  • It worked. Thank you, but there is another question. How to remove the file format? I have a number of Tavars in the photo as in the magazine-catalog - Alexey Novozhilov
  • @ Alexey Novozhilov, are you talking about the name of the images? Or about what format is it? - Let's say Pie
  • the name of the images. it is being written at the moment (title.png) - Alexey Novozhilov
  • one
    @ Alexey preg_replace('~(.+)(?:\.(gif|jpg|png))~', '$1', $name_d[$i]); , you can use preg_replace('~(.+)(?:\.(gif|jpg|png))~', '$1', $name_d[$i]); - Let's say Pie