Easy to use PHP function to show random image from a particular directory

In this post, we are going to see a PHP function that is very easy to use and can be used to show a random image from a particular directory on our web page.

Below is the code of our PHP function:

function random_img_from_dir($dir)

  // Initiate array where image name will be put
  $imgs_arr = array();

  // Check if our directory exists
  if (file_exists($dir) && is_dir($dir) ) {
      // Get files from the directory as an array
      $dir_arr = scandir($dir);
      $arr_files = array_diff($dir_arr, array('.','..') );

      foreach ($arr_files as $file) {
        //Get the file path
        $file_path = $dir."/".$file;
        // Get the file extension
        $ext = pathinfo($file_path, PATHINFO_EXTENSION);

        if ($ext=="jpg" || $ext=="png" || $ext=="JPG" || $ext=="PNG") {
          array_push($imgs_arr, $file);

      $count_img_index = count($imgs_arr) - 1;
      return $imgs_arr[rand( 0, $count_img_index )];



We have created the function. Now let’s see the usage of this function.

Get random word from English dictionary in PHP tutorial

Get random text by line number from a text file in PHP

To use this function we just need to pass our directory path as the parameter to the function and our function will return a random image name that is inside the directory. Using the HTML img tag we can display the random image on our web page. Below is the code of usage of this function:

  $dir = 'my_image_directory';
  $img = random_img_from_dir($dir);

<img src="<?php echo $dir."/".$img ?>">

In the above code, we have set the directory “my_image_directory” which contains JPG and PNG images. The code will display a random image from the directory.

If the directory contains other files that are other than JPG and PNG type image, then there is no problem. Our function can automatically filter the files from the directory and take only JPG and PNG type images. So we don’t have to worry about that.

Leave a Reply

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