Blog

Tutorial: PHP Random Image

Dev, Web , , , , , ,
0

I was working on a website of mine when I came across the need to be able to have a script randomly pull an image from a specific folder and then display it. Obviously, server side scripting is going to be involved so I decided to write this function in PHP. Let’s take a look!

Source Code

Reviewing Code Line by Line

The first thing we need to do is create a function. We’re going to keep it simple and call it ‘rand_image’. Feel free to change it to whatever you like. We’re going to make this a bit more universal and allow the ability to pass a image folder path to our function.

We’re simply going to set the extensions that we consider to be an image. I know that I only want to grab jpg/gif/png images, because I’ll only ever use those as images.

Now all we need to do is use glob to pull out the images from the path that we specified. Using GLOB_BRACE along with our above $extensions we can grab all of the images we’d like to use from that folder.

Finally, we simply need to return a random image. rand(0, count($images) – 1) says generate a random number between 0 and the size of our images array/list, minus 1. This will yield us an index to use for $images[].

Implementation

Using the PHP code above we can call our new rand_image() function, passing it a folder path. The function will return us a String containing the name and path of the random image which we can use in an echo to create an image that links to itself. This function could be used for a wide variety of purposes.

Add this function to your PHP library, PHP functions file, or the top of any PHP page!

Leave a Reply

Your email address will not be published. Required fields are marked *