Code Snippet: Get a random image from a directory.

by John Email

This can be useful for banner ads.

function getRandomImage( ) {

$path = ""; // Replace with your path

$img_list = array();

$dir = opendir( $path );

// Get all the files in the directory

while( $img = readdir($dir) )
{
if( $img != "." && $img != "..")
{
$img_list[] = $img;
}
}

closedir($dir);

// Randomly select a file from the list
$rand_img = rand(0, count($img_list)-1 );

$rand_img = $img_list[$rand_img];

return $rand_img;
}

No feedback yet

Leave a comment


Your email address will not be revealed on this site.

Your URL will be displayed.
PoorExcellent
(Line breaks become <br />)
(Name, email & website)
(Allow users to contact you through a message form (your email will not be revealed.)