Screenshot of a PHP auto-gallery example

So far our have required us to write new HTML code in order to present an image in the gallery, or at least the thumbnail thereof. This means that every time that we upload a new image to the site, we would have to write more HTML to add it to our page.

But our random image lesson showed that we can read images from a directory… so it follows that we should be able to automate the entire process of presenting a gallery of images with PHP.

Let’s take the core of the random image code:

<?php $imagedir = dir('assets/images');
$count = 1;
while(($file = $imagedir->read())) {
	if (preg_match($pattern, $file)) {
		$imagearray[$count] = $file;
} ?>

This creates our array as before. But this time, we’re not getting a random image from $imagearray, but the first image. Doing that alone would be easy:

<img src="assets/images/<?php echo $imagearray[1]; ?>" alt>

Rather than leaving the alt attribute value blank, you should fill it with something. Ideally, you could use a variation of the string manipulation techniques I introduced in the self-made pages lesson to create values based on the file name of the image.

We want to make what selects the image a variable, so let’s create one called $pic and set it to a default value of 1 if no value for it exists:

<?php if (!$pic) { $pic = 1; } ?> 
<img src="assets/images/<?php echo $imagearray[$pic]; ?>" alt>

Now we want to allow the user to change the value of $pic. The easiest way to do that is via clicking on a link which passes a GET variable back to the page. First, we’ll add a line of code to the section above:

<?php $pic = $_GET['pic'];
if (!$pic) { $pic = 1; } ?> 
<img src="assets/images/<?php echo $imagearray[$pic]; ?>" alt>

Then create our link, which will increment whatever value $pic has by 1:

<a href="?pic=<?php echo ($pic + 1); ?>">Next</a>

This will advance our images through the array with each click on the Next link. (As always, one of the easiest ways to understand this is to look at the source code delivered from the browser). There’s just one problem: we can keep clicking the Next button past the actual number of images we have.

Interface Design Rule No. 1

If an interface element can’t be used, or if it isn’t appropriate at a certain point, it shouldn’t be seen. To solve this issue, we’ll make the appearance of the Next button conditional:

<?php if ($pic < $count - 1) { ?>
	<a href="?pic=<?php echo ($pic + 1); ?>">Next</a>
?php } ?>