Posted By

dsntos on 03/02/09


Tagged

php image random


Versions (?)

Who likes this?

4 people have marked this snippet as a favorite

luman
vali29
pster
JoF


Random Image from Directory using PHP


 / Published in: PHP
 

Outputs an image path from a defined directory.

  1. <?php
  2.  
  3. $path_to_images = "/images/"; // path to your images
  4. $default_img = "image.gif"; // image to display if directory listing fails
  5.  
  6. function getRandomImage($thispath, $img) {
  7. if ( $list = getImagesList($thispath) ) {
  8. mt_srand( (double)microtime() * 1000000 );
  9. $num = array_rand($list);
  10. $img = $list[$num];
  11. }
  12. return $thispath . $img;
  13. }
  14. function getImagesList($thispath) {
  15. $ctr = 0;
  16. if ( $img_dir = @opendir($thispath) ) {
  17. while ( false !== ($img_file = readdir($img_dir)) ) {
  18. // can add checks for other image file types here
  19. if ( preg_match("/(\.gif|\.jpg)$/", $img_file) ) {
  20. $images[$ctr] = $img_file;
  21. $ctr++;
  22. }
  23. }
  24. closedir($img_dir);
  25. return $images;
  26. }
  27. return false;
  28. }
  29.  
  30.  
  31. ?>
  32.  
  33. <img src="<?php echo getRandomImage($path_to_images, $default_img) ?>;">

Report this snippet  

Comments

RSS Icon Subscribe to comments
Posted By: reptkeu on February 26, 2010

Hello, I can not get this to work, can you help please? this is the page: http://bertrandclerc.com/autres/random_images/script3.php

You need to login to post a comment.