One of the principles of creating a popular site is dynamism: making the front page look different each time a user visits. Obviously the most rewarding way to do this is by adding fresh new content as frequently as possible, but that is not always possible, especially if the site is maintained by only one person.
An alternative approach is to create dynamism via randomness: rebuilding pieces of content and showing these to the visitor randomly on entry, creating the appearance of change. While this concept could be applied to any kind of content, we will use a set of images for our example.
Note: The lesson that we are about to do will be most effective if you have a large number of images (three or more) that are all the same size.
First, place the images into their own folder. I’ve created a folder called random inside the images folder to store the images I want to use.
Next, create your code. I intend to make my random image appear on a page called random.php, which is beside the images folder. The first thing we have to do is tell PHP the location of the folder we wish to use, and place that location as the value of a variable we can reference later. At the same time, I’ll set a variable called $count
that will be used later:
$randomdir = dir('images/random');
$count = 1;
Next, I want to read in the contents of the random
folder. To do this, I’ll use a while
loop:
while($file = $randomdir->read()) { }
Essentially what this loop does is read the content of the directory specified by $randomdir
, and place the name of each file it encounters into a variable called $file
. It will continue to do this until all files have been read in.
Our action – what we want to have happen each time a file is encountered – is specified between the curly braces. For now, simply echo
the $file
variable.
while($file = $randomdir->read()) { echo $file; }
The result should look something like this: . .. pic1.jpg pic2.jpg pic3.jpg
The while
loop is obviously picking up other content from the random
folder, including hidden files. There is no filter present: $file
could equally contain a Word document or a JPEG. There’s also currently no method of preserving the filenames $file
collects: whatever $file
contains at one iteration is replaced by the name of another file the next time the while loop goes around.
To get around this, we’ll create a filter, in the form of a variable that contains a simple regular expression:
$pattern="/(gif|jpg|jpeg|png)/";
gif, jpeg, jpg or png are the extensions that may occur in the pattern: the vertical lines (pipes, on the top right of your keyboard) mean “or”.
There is a lot more we could do with this filter in PHP: you should know by now that simply seeing a .jpg extension on the end of a file does not guarantee that it is a actually a JPEG file. Many of these possibilities will be discussed in the entry on uploading files with PHP, to come shortly. For now, let’s trust in the fact that the images in the random folder are named and formatted correctly. We’ll make sure that we are looking at the file extension, rather than the start of the file name, by using the pathinfo
function.
To preserve the filenames that pass this filter, we’ll store them inside an array, indexed with the $count
variable. Obviously, we’ll also need to increment $count
as we encounter each new filtered file, otherwise we’ll keep placing each filename into the first slot in the array.
Our code now becomes:
<?php $randomdir = dir('images/random');
$count = 1;
$pattern="/(gif|jpg|jpeg|png)/";
while($file = $randomdir->read()) {
$ext = pathinfo($file, PATHINFO_EXTENSION);
if (preg_match($pattern, $ext)) {
$imagearray[$count] = $file;
$count++;
}
} ?>
($count++
just means “increment the current value of $count by 1”).
Now we should have an array called $imagearray
filled with the filtered contents of the random folder. To test this, use print_r()
to print the contents of $imagearray
onto the page, just before the closing PHP tag:
print_r($imagearray);
Next, we need to generate a random number between 1 and however many slots are in $imagearray
:
$random = mt_rand(1, $count - 1);
Finally, we can use this random number to pull out an image from $imagearray
. The entire code:
<?php $randomdir = dir('images/random');
$count = 1;
$pattern="/(gif|jpg|jpeg|png)/";
while($file = $randomdir->read()) {
$ext = pathinfo($file, PATHINFO_EXTENSION);
if (preg_match($pattern, $ext)) {
$imagearray[$count] = $file;
$count++;
}
}
$random = mt_rand(1, $count - 1);
echo '<img src="images/random/'.$imagearray[$random].'" alt />';
?>
You could use a part of the filename for the alt
attribute value, but in this case I have left it blank.
By drawing a random image into a page with each visit we can give the impression of change and new content with very little extra work. This solution is also dynamic in the sense that adding, changing or removing content from the random images folder will alter the images shown on random.php.
Enjoy this piece? I invite you to follow me at twitter.com/dudleystorey to learn more.