Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP pull random image from folder

I am wondering about a "better" way of pulling a random image from a folder.

Like say, to have php just select a random image from folder instead of searching and creating an array of it.

here is how I do it today

<?php
    $extensions = array('jpg','jpeg');
    $images_folder_path = ROOT.'/web/files/Header/';
    $images = array();
    srand((float) microtime() * 10000000);

    if ($handle = opendir($images_folder_path)) {
        while (false !== ($file = readdir($handle))) {
            if ($file != "." && $file != "..") {
                $ext = strtolower(substr(strrchr($file, "."), 1));
                if(in_array($ext, $extensions)){
                $images[] = $file;
                }
            }
        }
    closedir($handle);
    }
    if(!empty($images)){
        $header_image = $images[array_rand($images)];
    } else {
        $header_image = ''; 
    }
?>
like image 917
Tom Avatar asked Apr 21 '12 18:04

Tom


2 Answers

Try this:

<?php

$dir = "images/";
$images = scandir($dir);
$i = rand(2, sizeof($images)-1);
?>

<img src="images/<?php echo $images[$i]; ?>" alt="" />
like image 140
Nesim Razon Avatar answered Sep 22 '22 13:09

Nesim Razon


Below code validate image list by image extension.


<?php

function validImages($image)
{
    $extensions = array('jpg','jpeg','png','gif');
    if(in_array(array_pop(explode(".", $image)),   $extensions))
    {
    return $image;
    }
}

$images_folder_path = ROOT.'/web/files/Header/';
$relative_path = SITE_URL.'/web/files/Header/';

$images = array_filter(array_map("validImages", scandir($images_folder_path)));

$rand_keys = array_rand($images,1);

?>

<?php if(isset($images[$rand_keys])): ?>
    <img src="<?php echo $relative_path.$images[$rand_keys]; ?>" alt="" />
<?php endif; ?>
like image 43
Fazle Elahee Avatar answered Sep 21 '22 13:09

Fazle Elahee