Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP & HTML: how to loop through a directory with images?

very simple folderstructure like this …

  • index.php
  • img
    • someimage1.jpg
    • someimage2.png
    • someimage3.jpg

I wonder how difficult it is to use php to read this img folder and create a microsite that loops through this images with "prev" and "next" links.

So I don't want to manually specify what the filenames of the images are. I just want to add images to the folder and a php script runs through them and creates a navigation like that

<a href="nextimage-link" class="next">Next Image</a>
<a href="previmage-link" class="prev">Previous Image</a>

So whenever I click on the "Next Image" link it updates the site and shows the next image.

Is that complicated to build? Any ideas on that? Thank you in advance for your tipps and help.

like image 443
matt Avatar asked Jul 21 '12 11:07

matt


1 Answers

Consider the following, I am assuming the img folder is in /var/www folder:

$dir = "/var/www/img/*.jpg";
//get the list of all files with .jpg extension in the directory and safe it in an array named $images
$images = glob( $dir );

//extract only the name of the file without the extension and save in an array named $find
foreach( $images as $image ):
    echo "<img src='" . $image . "' />";
endforeach;

For a better UI, you can create an array of image paths and store them in a JavaScript array. Then use the Previous and Next button to change the index of the image array and display the current in the single img tag.

like image 125
M. Ahmad Zafar Avatar answered Nov 14 '22 23:11

M. Ahmad Zafar