0

I am using this script to display random images from a folder. I have hundreds of images with significant filenames, So I’m looking for a way to display each image file name as an image caption. Is this possible?

this is the script Im using:

<?php
/*
By Matt Mullenweg > http://photomatt.net
Inspired by Dan Benjamin > http://hiveware.com/imagerotator.php
Latest version always at:

http://photomatt.net/scripts/randomimage

*/// Make this the relative path to the images, like "../img" or "random/images/".
// If the images are in the same directory, leave it blank.
$folder = '';

// Space seperated list of extensions, you probably won't have to change this.
$exts = 'jpg jpeg png gif';

$files = array(); $i = -1; // Initialize some variables
if ('' == $folder) $folder = './';

$handle = opendir($folder);
$exts = explode(' ', $exts);
while (false !== ($file = readdir($handle))) {
foreach($exts as $ext) { // for each extension check the extension
if (preg_match('/\.'.$ext.'$/i', $file, $test)) { // faster than ereg, case insensitive
$files[] = $file; // it's good
++$i;
}
}
}
closedir($handle); // We're not using it anymore
mt_srand((double)microtime()*1000000); // seed for PHP < 4.2
$rand = mt_rand(0, $i); // $i was incremented as we went along

header('Location: '.$folder.$files[$rand]); // Voila!
?>
Nizarnav
  • 167
  • 6

1 Answers1

0

If all you want to do is continue to display a single random image then remove (or comment out so you can restore it if you later want to) the header line and at the end of the file add the following lines underneath it:

//header('Location: '.$folder.$files[$rand]); // Voila!
echo $files[$rand];
?>
<br />
<img src="<?php echo $folder.$files[$rand] ?>" />

You might want to add some css styling to set the display size of the image, and to format the caption above it.

user1207727
  • 1,543
  • 1
  • 15
  • 18
  • Hi This Works fine in the browser. Thank you a lot. But won’t work if we call the script like a normal image, for example: A Random Image, which is the normal way to display the random image in my site. – Nizarnav Feb 13 '12 at 22:52
  • Ok I see. Is the page with the img tags a php script? If it's not then without using an iframe rather than just an img tag you won't be able to display both the image and its caption – user1207727 Feb 13 '12 at 23:02
  • Im using it in a Drupal block, I can set the input format to PHP or HTML,but for unknown reasons, using the script directly in a PHP block cause my site to crash; So I will try the iframe solution. – Nizarnav Feb 13 '12 at 23:39