Random Image & Directory images

Discussion in 'PHP' started by BenSeagrave, Feb 17, 2009.

  1. #1
    Hello, How would i make a random image be chosen from a directory of images, and is there a way to show all of the images, Like a thumbnail, But it shows all the images in a certain directory?

    thanks
     
    BenSeagrave, Feb 17, 2009 IP
  2. Ozz

    Ozz Peon

    Messages:
    112
    Likes Received:
    2
    Best Answers:
    0
    Trophy Points:
    0
    #2
    If you want advice on how to do it I would recommend to use the dir class and filter ., .. , and all images / files you don't want to display. The example in that page will give you all that you need to get the files from the folder you want.
     
    Ozz, Feb 17, 2009 IP
  3. BenSeagrave

    BenSeagrave Peon

    Messages:
    8
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #3
    Thanks, But what about the random image?
     
    BenSeagrave, Feb 18, 2009 IP
  4. Danltn

    Danltn Well-Known Member

    Messages:
    679
    Likes Received:
    36
    Best Answers:
    0
    Trophy Points:
    120
    #4
    http://php.fm/random-image

    Tweaked to what I think you need.

    <?php
    
    /**
     * Danltn | http://danltn.com/
     * No warranty is given to code used
     */
    
    chdir( '/directory/with/images' );
    
    $images = glob( '*.{gif,jpeg,jpg,png}', GLOB_BRACE );
    $image = $images[rand( 0, count($images) - 1 )];
    
    switch ( strtolower(substr($image, -4, 4)) )
    {
        case "jpeg":
        case ".jpg":
            $ctype = "image/jpg";
            break;
        case ".gif":
            $ctype = "image/gif";
            break;
        case ".png":
            $ctype = "image/png";
            break;
    }
    
    $file = file_get_contents( $image );
    $len = strlen( $file );
    
    if ( !@headers_sent() )
    {
        header( "Pragma: public" );
        header( "Expires: 0" );
        header( "Cache-Control: must-revalidate, post-check=0, pre-check=0" );
        header( "Cache-Control: public" );
        header( "Content-Type: $ctype" );
        header( "Content-Length: " . $len );
    
        echo $file;
    }
    
    PHP:
     
    Danltn, Feb 18, 2009 IP