Show random image(s) from a directory

Posted on September 21, 2008, under PHP 

Hi,

If you need to show images randomly from a directory then this script can help you.

index.php

Let’s configure some variables: $extensions, $images_folder_path & $url_to_images_folder.

<?php
// extensions to be checked

$extensions = array('jpg','jpeg','gif','png','bmp');

// images folder

$images_folder_path = '/home/site/public_html/images/';

// url to folder

$url_to_folder = 'http://www.yoursitename.com/images/';

Create the array with the URLs to the images:

// Images Array (SRC value)

$images = array();

srand((float) microtime() * 10000000); // IF PHP Version < 4.2.0

// Open directory and read images

if ($handle = opendir($images_folder_path)) {
    while (false !== ($file = readdir($handle))) {
        if ($file != "." && $file != "..") {
            
			// get file extension
			$ext = strtolower(substr(strrchr($file, "."), 1));

			if(in_array($ext, $extensions))
			{
			$images[] = $url_to_folder.$file;
			}

        }
    }
    closedir($handle);
}

Are there any images in the directory? Select randomly 2 distinctive values. If there are no images in the folder, notify the user with a message.

if(!empty($images)) // Do we have something to show?
{
$rand_key = array_rand($images, 1);

$src = $images[$rand_key];

echo "<img src='".$src."' align='absmiddle'>";

/* 
Show second image; Make sure it will not be the same as the first one;
We will remove the element of the first image from the array. This way the script will not reselect it 
*/

unset($images[$rand_key]);

$rand_key = array_rand($images, 1);

$src = $images[$rand_key];

echo "<br /><br /><img src='".$src."' align='absmiddle'>";
}
else
{
echo 'No images were found in <strong>'.$images_folder_path.'</strong>';
}
?>


Comment via Facebook

comments

6 Replies to "Show random image(s) from a directory"

  1. This could be done with a lot less code.

  2. A lot less code? Could be, but think how many beginners would actually understand a similar script with less code. The current application is well commented and gives the user an idea of how this script is actually working (step by step).

  3. Good basic script.

    You can: Make your rand_key array equal to the number of images that you want to show, then create a loop to display each image. This simple change makes this much more versatile.

    Cheers

  4. Hello, does anybody know how to show 6 random images? Thanks for a help.

  5. Sorry but it can be better! Nice script, made some tweaks.
    It now gets every photo out of the folder.. and shows them

    <?php
    # Credits: Rickdegraaff.nl

    // extensions to be checked

    $extensions = array('jpg','jpeg');

    // images folder

    $images_folder_path = 'images/projects/';

    // url to folder

    $url_to_folder = 'http://'.$_SERVER['SERVER_NAME'].'/porto/images/projects/';

    // Images Array (SRC value)

    $images = array();

    srand((float) microtime() * 10000000); // IF PHP Version < 4.2.0

    // Open directory and read images

    if ($handle = opendir($images_folder_path)) {
    while (false !== ($file = readdir($handle))) {
    if ($file != "." && $file != "..") {

    // get file extension
    $ext = strtolower(substr(strrchr($file, "."), 1));

    if(in_array($ext, $extensions))
    {
    $images[] = $url_to_folder.$file;
    }

    }
    }
    closedir($handle);
    }
    foreach ($images as $imgvalue) {
    print '
    ';
    }
    ?>

    1. The part:

      foreach ($images as $imgvalue) {
      print '
      ';
      }

      i

      is incomplete. Make sure you make the code postable first before submitting it inside a comment: http://www.elliotswan.com/postable/

      Thanks for your suggested code!

Leave a Reply


* = required fields

  (will not be published)


XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Note: If you want to post CODE Snippets, please make them postable first!
(e.g. <br /> should be converted to &lt;br /&gt;)

POSTING RULES:

  • The comment must be relevant with the topic of the post.
  • Only comments with real email addresses will get approved. So, emails like 'abc@domain.com' will not be accepted.
  • Do not post the same message in multiple articles through the site.
  • Do not post advertisements, junk mail or pyramid schemes.
  • In case you post a link to another site, please explain briefly where the link goes as a courtesy to other users.
  • Do not post comments such as: "Thank you", "Awesome", "Nice tutorial", "Merci", etc.