This function will take a random image from a directory and display it in your webpage. It can be modified to do many other things and list various other file types besides just images. All this does is print a random file name from your directory, you can do whatever you like with it.
<?php
// print a random image. Don't forget ending slash!
// setting $type to 'all' will return all images.
print getRandomImage('../images/');
function getRandomImage($dir,$type='random')
{
global $errors,$seed;
if (is_dir($dir)) {
$fd = opendir($dir);
$images = array();
while (($part = @readdir($fd)) == true) {
if ( eregi("(gif|jpg|png|jpeg)$",$part) ) {
$images[] = $part;
}
}
// adding this in case you want to return the image array
if ($type == 'all') return $images;
if ($seed !== true) {
mt_srand ((double) microtime() * 1000000);
$seed = true;
}
$key = mt_rand (0,sizeof($images)-1);
return $dir . $images[$key];
} else {
$errors[] = $dir.' is not a directory';
return false;
}
}
?>
Essentially choosing a random image with PHP is pretty easy. In the above snippet of code, eregi looks for images ending with gif,jpg,jpeg or png ... don't hesitate to add others. It's also good to call srand() only once per script call, so if you have multiple random images per page, adjust the function (maybe this should be taken into account).
Of course it doesn't write HTML, that's your job. Here's an example:
<?php
$image = getRandomImage('somedir');
echo "<img src='$image' alt='A random image'>";
?>
I'm working on a PHP function set to deal with images, such as presenting a random one. Many useful features are being created, such as automatic creation/management of titles/alt tags, html links, voting, view all n per page, etc. If you have suggests, please contact me.