John
John

Reputation:

How to get random image from directory using PHP

I have one directory called images/tips.

Now in that directory I have many images which can change.

I want the PHP script to read the directory, to find the images, and out of those images found to pick a random image.

Any idea on how to do this?

Upvotes: 19

Views: 64820

Answers (10)

Czlowiekwidmo
Czlowiekwidmo

Reputation: 1135

Load folder with images:

$folder = opendir(images/tips/);

Build table out of files/images from directory:

$i = 0;
while(false !=($file = readdir($folder))){
if($file != "." && $file != ".."){
    $images[$i]= $file;
    $i++;
    }
}

Pick random:

$random_img=rand(0,count($images)-1);

Show on page:

echo '<img src="images/tips'.$images[$random_img].'" alt="" />';

Upvotes: -1

Alessandro
Alessandro

Reputation: 908

I wrote a simple php script for my personal use. Now I want share it with stackoverflow's community. Usage is simple: create a folder "php" into root of your Web Server and put inside this file php rotate.php... now create two folders into your root called "pic" and "xmas"... you can adjust the folder names by editing the var $my_folder_holiday and $my_folder_default...

<?php
  ##########################################################
  # Simple Script Random Images Rotator • 1.4 • 04.01.2020 #
  # Alessandro Marinuzzi [alecos] • https://www.alecos.it/ #
  ##########################################################
  function rotate($folder) {
    if ((file_exists($_SERVER['DOCUMENT_ROOT'] . "/$folder")) && (is_dir($_SERVER['DOCUMENT_ROOT'] . "/$folder"))) {
      $list = scandir($_SERVER['DOCUMENT_ROOT'] . "/$folder");
      $fileList = array();
      $img = '';
      foreach ($list as $file) {
        if ((file_exists($_SERVER['DOCUMENT_ROOT']  . "/$folder/$file")) && (is_file($_SERVER['DOCUMENT_ROOT']  . "/$folder/$file"))) {
          $ext = strtolower(pathinfo($file, PATHINFO_EXTENSION));
          if ($ext == 'gif' || $ext == 'jpeg' || $ext == 'jpg' || $ext == 'png') {
            $fileList[] = $file;
          }
        }
      }
      if (count($fileList) > 0) {
        $imageNumber = time() % count($fileList);
        $img = $folder . '/' . $fileList[$imageNumber];
      }
      return $img;
    } else {
      mkdir($_SERVER['DOCUMENT_ROOT'] . "/$folder", 0755, true);
    }
  }
  $my_gallery_month = date('m');
  $my_folder_default = 'pic';
  $my_folder_holiday = 'xmas';
  if ($my_gallery_month == 12) {
    $my_gallery = rotate($my_folder_holiday);
  } else {
    $my_gallery = rotate($my_folder_default);
  }
?>

This script was tested under PHP 7.0/7.1/7.2/7.3 and PHP 7.4 and works fine. Usage (for example in root you may have a folder "pic" and "xmas" containing your images):

<a href="/<?php include("php/rotate.php"); echo $my_gallery; ?>"><img src="/<?php echo $my_gallery; ?>" alt="Random Gallery" width="90" height="67"></a>

Other usage using FancyBox library:

<a href="/<?php include("php/rotate.php"); echo $my_gallery; ?>" data-fancybox><img src="/<?php echo $my_gallery; ?>" alt="Random Gallery" width="90" height="67"></a>

Hope this Helps.

Upvotes: 0

stalin wesley
stalin wesley

Reputation: 165

$folder = "images";
$results_img_arr = array();
if (is_dir($folder))
{
        if ($handle = opendir($folder))
        {
                while(($file = readdir($handle)) !== FALSE)
                {
                    if(!in_array($file,array(".","..")))
                        $results_img_arr[] = $folder."/".$file;
               }
         closedir($handle);
        }
}
$ran_img_key  = array_rand($results_img_arr);

$img_path = $results_img_arr[$ran_img_key];

Upvotes: 1

Sajjad Hossain
Sajjad Hossain

Reputation: 193

Agreed with alexa. Use simple function.

function RandImg($dir)
{
$images = glob($dir . '*.{jpg,jpeg,png,gif}', GLOB_BRACE);

$randomImage = $images[array_rand($images)];
return $randomImage;
}

$the_image = RandImg('images/tips/');
echo $the_image;

Upvotes: 1

aditya7822
aditya7822

Reputation: 23

function get_rand_img($dir)
{
    $arr = array();
    $list = scandir($dir);
    foreach($list as $file)
    {
        if(!isset($img))
        {
            $img = '';
        }
        if(is_file($dir . '/' . $file))
        {
            $ext = end(explode('.', $file));
            if($ext == 'gif' || $ext == 'jpeg' || $ext == 'jpg' || $ext == 'png' || $ext == 'GIF' || $ext == 'JPEG' || $ext == 'JPG' || $ext == 'PNG')
            {
                array_push($arr, $file);
                $img = $file;
            }
        }
    }
    if($img != '')
    {
        $img = array_rand($arr);
        $img = $arr[$img];
    }
    $img = str_replace("'", "\'", $img);
    $img = str_replace(" ", "%20", $img);
    return $img;
}


echo get_rand_img('images');

replace 'images' with your folder.

Upvotes: 1

Paolo Euvrard
Paolo Euvrard

Reputation: 17

Simpler:

$directory = "medias/photos/";
$img = glob($directory . "*.jpg");
shuffle($img);

Upvotes: 0

Makarand Mane
Makarand Mane

Reputation: 503

<?php
   foreach (glob("gallery/*") as $filename) {
         echo '<li><a href="'.$filename.'" title=""><img src="'.$filename.'" alt="" /></a> </li>';      
       }
?>

Look at this code, use it definitely if useful for you. It loads all files from folder and prints them in above format. I made this code to use with lightbox.

Upvotes: 1

alex
alex

Reputation: 490567

$imagesDir = 'images/tips/';

$images = glob($imagesDir . '*.{jpg,jpeg,png,gif}', GLOB_BRACE);

$randomImage = $images[array_rand($images)]; // See comments

You can send a 2nd argument to array_rand() to get more than 1.

Upvotes: 63

keithjgrant
keithjgrant

Reputation: 12769

You can use opendir() to read in the filenames from that directory, storing each filename in an array. Then use rand() with a min and max corresponding to your array keys to select an item from the array.

Upvotes: 0

Ignas R
Ignas R

Reputation: 3409

$images = glob('images/tips/*');
return $images[rand(0, count($images) - 1)];

However, this doesn't ensure that the same image isn't picked twice consecutively.

Upvotes: 4

Related Questions