• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 2598
  • Last Modified:

PHP - read directory of photos - loop code to display all

I have a directory in the "./images/" folder. Let's call it "2006".
The directory contains a lot of thumbnail photos. The directory will be updated for more photos in the future.

Let's say all of the files are called "photo_001_tn.jpg" (with the number changing for each pic)

I want a script to display all of the images in this folder with a link to the large pic for that thumbnail.
We will assume the larger version has the same name as the thumbnail, minus the "_tn" part.
So a large pic of the above thumbnail would be "photo_001.jpg".

I need the script to only display "jpg", "gif", and "png" files.
I need a variable at the top of the script so I can change this.

I want the script to end up displaying this HTML code.
(This is cut down just to explain the point. I will probably change this up a little.)

<a href="./images/2006/photo_001.jpg">
<img src="./images/2006/photo_001_tn.jpg" alt="Photo from 2006" hspace="2" vspace="2">

But...(important)... I would like it to do 4 pics on the first row, then move to another row.
Instead of just displaying them all together. I only have room for 4 per row.
And how would I make this changable, in case I need 3 per row, etc. Can there be a variable at the beginning of the script?

3 Solutions
$files = glob('{images/2006/*_tn.jpg,images/2006/*_tn.gif,images/2006/*_tn.png}',GLOB_BRACE);
$num_cols = 4;
$column = 1;

foreach($files AS $thumb)
      if($column == 1)
            echo "<tr>";
      $image = str_replace('_tn','',$thumb);
      echo "<td><a href=\"$image\"><img src=\"$thumb\" alt=\"Photo from 2006\" hspace=\"2\" vspace=\"2\"></a></td>";
      $column %= $num_cols;
           echo "</tr>";
for($column--; $column < $num_cols; $column++)
      echo "<td></td>";
echo "</tr>";
There are a large number of existing PHP scripts that can do what you need. You can start your search here:


If you need a developer to design a new script to your specifications, you may wish to contact one of the experts via email to discuss the details of your request.

If you have already started your script, and need assistance with a specific piece of code, please provide the details and we will be happy to help.

Here's a previous solution which might prove helpful.


Featured Post

Free Tool: Port Scanner

Check which ports are open to the outside world. Helps make sure that your firewall rules are working as intended.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now