Show random image(s) from a directory
Posted on September 21, 2008, Filled under PHP,
Bookmark it
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>';
}
?>
Do you wish to receive the latest updates as soon as they are posted? Get our RSS Feed or Subscribe to the Newsletter!
- September 21, 2008
- article by Gabriel C.
- 3 comments
Related Posts
PHP: How to select a random value from an array using a specified rangeat September 20, 2008
How to recursively read a directory with all its contentat September 4, 2008
Creating a Random Quote Scriptat August 29, 2008 with 2 comments
PHP: Calculate the Size, Number of Files & Folders of a Directoryat September 24, 2008 with 3 comments
How to Remove a (non-empty) Directory using PHPat September 28, 2008 with 1 comment



3 Replies to "Show random image(s) from a directory"
September 21, 2008 at 6:29 AM
This could be done with a lot less code.
September 21, 2008 at 6:44 AM
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).
December 21, 2009 at 1:52 PM
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