Display Random Image from a Directory

This script outputs random image from a defined directory.

Make sure to change the path to your images directory and also an image to display if directory listing fails. I have found this piece of code handy to use to create random headers, logos when designing web pages.

 

Code:

 

<?php

 

    $path_to_images = /images/ // path to your images

    $default_img = image.gif// image to display if directory listing fails

 

    function getRandomImage($thispath, $img) {

        if ( $list = getImagesList($thispath) ) {

            mt_srand( (double)microtime() * 1000000 );

            $num = array_rand($list);

            $img = $list[$num];

        }

        return $thispath . $img;

    }

    function getImagesList($thispath) {

        $ctr = 0;

        if ( $img_dir = @opendir($thispath) ) {

            while ( false !== ($img_file = readdir($img_dir)) ) {

                // can add checks for other image file types here

                if ( preg_match(“/(\.gif|\.jpg)$/”, $img_file) ) {

                    $images[$ctr] = $img_file;

                    $ctr++;

                }

            }

            closedir($img_dir);

            return $images;

        }

        return false;

    }

 

 

?>

 

<img src=”<?php echo getRandomImage($path_to_images, $default_img) ?>;”>

 

 

 

About Bulent

Yes, my name is Bulent. I am originally from Turkey but now reside in United Kingdom. I have been working as a designer for over 8 years and have been very fortunate to have worked on a wide variety of projects. I have recently developed one of the most succesfull recruitment portal for nearly a million Turkish speaking community in UK within few months we had reached to nearly 65,000 users and stil growing. Thank you for stopping by!

Leave a comment

You must be logged in to post a comment.