How to Display Random Image from Folder in PHP

On 2/26/2018

Hi! This is a quick tutorial about displaying random image from folder in php. It will be useful if you want to include featured section area on websites. Usually site owners will showcase their products or services in the prominent section with attractive pictures. And all these images will come from a folder and rotated through at regular time interval. A random image will be picked up from the lot one at a time and displayed here.

Let's see how to implement this random image selection process. PHP offers a rich set of native functions to handle directory and files. And they are more than enough for the task we are going to do.

php display random image from folder

PHP - Displaying Random Image from Folder:

As for the process goes, we have to use scandir() function to read all the files from a given folder and make a random pick in the lot. Just follow the below steps to choose a random image file in a directory and display it on the browser.

Step-1) First define the path to the image folder.

$dir_path = "images";

Step-2) Next read all the filenames into an array. For this we have to use scandir() method.

$files = scandir($dir_path);

Step-3) Now select a random image file from the array. For this, you have to create a random index using rand() function and get the file name.

$count = count($files);
$index = rand(2, ($count-1));
$filename = $files[$index];

Step-4) Finally display the chosen image in the browser. You must use <img> tag to display the image.

echo '<img src="'.$dir_path."/".$filename.'" alt="'.$filename.'">';

That's it! You have successfully displayed a random image in a directory.

PHP Function:

Here I have created getRandomImage() function to display random picture. It takes up the directory path as a parameter and returns an image from the same directory.

<?php
function getRandomImage($dir_path = NULL){
    if(!empty($dir_path)){
        $files = scandir($dir_path);
        $count = count($files);
        if($count > 2){
            $index = rand(2, ($count-1));
            $filename = $files[$index];
            return '<img src="'.$dir_path."/".$filename.'" alt="'.$filename.'">';
        } else {
            return "The directory is empty!";
        }
    } else {
        return "Please enter valid path to image directory!";
    }
}
?>

Usage:

You have to call the above function like this,

<?php
echo getRandomImage("images");
?>

Every time you run the code, it will select and display some random picture from the folder.

Read Also:

Likewise, you can display random image from the folder in php. To read the filenames, you also can use glob() function which return the filenames from a folder that matches a specific pattern. Hope this post is useful to you. Please share it on social media if you like it.

No comments:

Post a Comment

Contact Form

Name

Email *

Message *