19

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?

10 Answers 10

63
$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.

Sign up to request clarification or add additional context in comments.

2 Comments

Actually, you'd have to do $randomImage=$images[array_rand($images)]; From the manual: "array_rand() returns the key for a random entry."
thank buddy , that worked perfectly This webiste is great for getting help. Is there any option that when some comment is posted or answers is given i get email because i had three answers and i didn't get email , i ticked the notify box but still could not get email
4
$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.

2 Comments

Adding that insurance would detract from the randomness. It also might introduce bugs.
I had no clue that glob() function existed. Nice.
1
<?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.

Comments

1
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.

Comments

1

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;

Comments

1
$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];

Comments

0

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.

Comments

0

Simpler:

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

1 Comment

Problem is, this would only find jpg images, and it does a lot of unnecessary work by shuffling the whole array (may or may not be a problem, depending on how many images you have in the folder).
0

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.

Comments

-1

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="" />';

1 Comment

Two issues. Don't you need another slash after tips? And why not just do $images[] = $file and forget the counter?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.