How to get random image from directory using PHP

    |
  • Added:
  • |
  • In: Basic 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?

This Question Has 8 Answeres | Orginal Question | John

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;

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.

Simpler:

$directory = "medias/photos/";
$img = glob($directory . "*.jpg");
shuffle($img);
<?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.

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

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

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

Hope it helps. Of course enclose it in <?php ?>.

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.


Search
Meet with owner

Sajjad Hossain

Hey, I am Sajjad, working in web development sector since 2012. I love to do amazing things. Let's do a project together.
Connect Social With PHPAns
Top