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?

Who is Participating?
$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.
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.