Quick Search:
 
 PHP Code: Random Image from Directory Jump to:  
Category: >> PHP Code >> Random Image from Directory  

<< lastnext >>

Snippet Name: Random Image from Directory

Description: Spits out a random image path from a given directory.

Also see:
» Random banner picker
» Generate random string
» Rounded random numbers
» Random Pronounceable Passwords
» Pick Randomly from Array
» Weighted Random Choice

Comment: (none)

Language: PHP
Highlight Mode: PHP
Last Modified: March 16th, 2009

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


 
   Home |    Search |    Code Library |    Sponsors |    Privacy |    Terms of Use |    Contact Us © 2003 - 2024 psoug.org