Random Images Script


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

Put your images in a folder called 'random' in your ROOT directory.

Please this script at the top of your page:


Copy this code and paste it in your HTML
  1. <?php function RandomFile($folder='', $extensions='.*'){
  2. // fix path:
  3. $folder = trim($folder);
  4. $folder = ($folder == '') ? './' : $folder;
  5.  
  6. // check folder:
  7. if (!is_dir($folder)){ die('invalid folder given!'); }
  8.  
  9. // create files array
  10. $files = array();
  11.  
  12. // open directory
  13. if ($dir = @opendir($folder)){
  14.  
  15. // go trough all files:
  16. while($file = readdir($dir)){
  17.  
  18. if (!preg_match('/^\.+$/', $file) and
  19. preg_match('/\.('.$extensions.')$/', $file)){
  20.  
  21. // feed the array:
  22. $files[] = $file;
  23. }
  24. }
  25. // close directory
  26. closedir($dir);
  27. }
  28. else {
  29. die('Could not open the folder "'.$folder.'"');
  30. }
  31.  
  32. if (count($files) == 0){
  33. die('No files where found :-(');
  34. }
  35.  
  36. // seed random function:
  37. mt_srand((double)microtime()*1000000);
  38.  
  39. // get an random index:
  40. $rand = mt_rand(0, count($files)-1);
  41.  
  42. // check again:
  43. if (!isset($files[$rand])){
  44. die('Array index was not found! very strange!');
  45. }
  46.  
  47. // return the random file:
  48. return $folder . "/" . $files[$rand];
  49.  
  50. }
  51.  
  52.  
  53. $random1 = RandomFile("random");
  54. while (!$random2 || $random2 == $random1) {
  55. $random2 = RandomFile("random");
  56. }
  57. while (!$random3 || $random3 == $random1 || $random3 == $random2) {
  58. $random3 = RandomFile("random");
  59. }
  60. while (!$random4 || $random4 == $random1 || $random4 == $random2 || $random4 == $random3) {
  61. $random4 = RandomFile("random");
  62. }
  63. ?>
  64.  
  65. // place this section where you'd like to display the images:
  66.  
  67. <div id="random_images">
  68. <img src="/<?php echo $random1; ?>" alt="image alt" />
  69. <img src="/<?php echo $random2; ?>" alt="image alt" />
  70. <img src="/<?php echo $random3; ?>" alt="image alt" />
  71. <img src="/<?php echo $random4; ?>" alt="image alt" />
  72. </div>

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.