Random Image from Directory using PHP


/ Published in: PHP
Save to your folder(s)

Outputs an image path from a defined directory.


Copy this code and paste it in your HTML
  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

You need to login to post a comment.