Return to Snippet

Revision: 12095
at March 2, 2009 05:30 by dsntos


Initial 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) ?>;">

Initial URL


Initial Description
Outputs an image path from a defined directory.

Initial Title
Random Image from Directory using PHP

Initial Tags
php, image

Initial Language
PHP