How to get random image from directory using PHP

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


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.


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


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

Tags:

Php