Page 1 of 1

randomly including an image from a directory

Posted: Tue Aug 31, 2004 2:56 pm
by Daisy Cutter
is it possible to randomly include an image from a directory? right now I have to upload the image, then add an entry to my random image script.

My random image script is as follows:

Code: Select all

<?php
  $randimg[] = '/img/image.gif';
  ...
  $randimg[] = '/img/lastimage.gif';

  srand ((double) microtime() * 1000000);
  $random_number = rand(0,count($randimg)-1);
?>
then

Code: Select all

&lt;img src="&lt;?php echo $randimg&#1111;$random_number]; ?&gt;" alt="random image" /&gt;
This would help cut down on code size and increase convenience.

EDIT:
although not my purpose this would also be very convenient for an image gallery.

Posted: Tue Aug 31, 2004 2:58 pm
by feyd
you can use [php_man]glob[/php_man] or [php_man]readdir[/php_man] to get a list of the files in your directory. Then just use [php_man]rand[/php_man] or [php_man]mt_rand[/php_man] to choose the image from the list.

Posted: Tue Aug 31, 2004 3:10 pm
by pickle
This is probably close to what you're looking for

viewtopic.php?t=16746

Posted: Tue Aug 31, 2004 3:41 pm
by Daisy Cutter
I read that thread, pickle and modified the code:

Code: Select all

<?php

// chanage the directory path
$dir = '/home/mcovey/kafene.org/img';

// set valid extensions
$extentions = array('jpg', 'gif', 'png', 'jpeg', 'BMP', 'bmp', 'PNG', 'JPG', 'JPEG', 'GIF');

$images = array();

$dh = opendir($dir);

   while(($file = readdir($dh)) !== false) {

      // check if it's a file, and it has a valid extension
      if (is_file($dir . $file) && in_array(substr($file, -3), $extentions)) {

         // add image to array
         $images[] = $file;

      }

   }

closedir($dh);

// get 1 random key
$selected = array_rand($images, 1);

// set headers
echo ($images[$selected]);

?>
I'm getting the error:

Warning: array_rand(): Second argument has to be between 1 and the number of elements in the array in /home/.halleck/mcovey/kafene.org/randimg.php on line 28

Posted: Tue Aug 31, 2004 3:54 pm
by markl999
$dir = '/home/mcovey/kafene.org/img'; needs a trailing slash:
$dir = '/home/mcovey/kafene.org/img/'; for if (is_file($dir . $file) to work correctly.

Posted: Tue Aug 31, 2004 3:54 pm
by feyd
FYI: do not use substr to blindly "find" the extension. [php_man]pathinfo[/php_man] and/or regular expressions are much better at handling this.

Posted: Tue Aug 31, 2004 4:30 pm
by Daisy Cutter
thanks.

feyd, I'll look into that. I just copied, pasted and modified from pickle's link.

Right now I'm working on getting the images to link to $filename