6

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 = ''; 
    }
?>

4 Answers 4

12

Try this:

<?php

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

<img src="images/<?php echo $images[$i]; ?>" alt="" />
Sign up to request clarification or add additional context in comments.

1 Comment

your answer is nice and short! yet there is an issue! if images directory contains a big number of images (1K), scandir will load all of them into an array. While you need only one image. Is there a way to improve your answer? And if you can wrap it in a function with the option to get a limited number of images. i.e $returned_images_count=10;, What I mean is partially explained in this question. + opendir looks faster in profiling.
1

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

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

0

I searched the internet for hours on end to implement the code to what I wanted. I put together bits of various answers I found online. Here is the code:

<?php
    $folder = opendir("Images/Gallery Images/");
    $i = 1;
    while (false != ($file = readdir($folder))) {
        if ($file != "." && $file != "..") {
            $images[$i] = $file;
            $i++;
        }
    }
    //This is the important part... 
    for ($i = 1; $i <= 5; $i++) { //Starting at 1, count up to 5 images (change to suit)
        $random_img = rand(1, count($images) - 1);
        if (!empty($images[$random_img])) { //without this I was sometimes getting empty values
            echo '<img src="Images/Gallery Images/' . $images[$random_img] . '" alt="Photo ' . pathinfo($images[$random_img], PATHINFO_FILENAME) . '" />';
            echo '<script>console.log("' . $images[$random_img] . '")</script>'; //Just to help me debug
            unset($images[$random_img]); //unset each image in array so we don't have double images
        }
    }
?>

Using this method I was able to implement opendir with no errors (as glob() wasn't working for me), I was able to pull 5 images for a carousel gallery, and get rid of duplicate images and sort out the empty values. One downside to using my method, is that the image count varies between 3 and 5 images in the gallery, probably due to the empty values being removed. Which didn't bother me too much as it works as needed. If someone can make my method better, I welcome you to do so. Working example (the first carousel gallery at top of website): Eastfield Joinery

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.