Posted By

bjarniolsen on 10/07/10


Tagged

php


Versions (?)

Who likes this?

2 people have marked this snippet as a favorite

bjarniolsen
jplr


Show random image in PHP


 / Published in: PHP
 

Change $dir to image folder

  1. <?php
  2. Header("Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0");
  3. Header("Expires: Thu, 19 Nov 1981 08:52:00 GMT");
  4. Header("Pragma: no-cache");
  5. Header("Content-Type: image/gif");
  6.  
  7. $dir = "img/backgrounds";
  8. //$imglist = "";
  9. srand((double)microtime()*1000000);
  10. $i = 0;
  11. if(is_dir($dir)){
  12. if($dh = opendir($dir)){
  13. while(($file = readdir($dh)) !== false){
  14. if($file != '..' && $file != '.'){
  15. $image[$i] = $file;
  16. $i++;
  17. }
  18. }
  19. closedir($dh);
  20. }
  21. }
  22. $n = rand(0,(count($image)-1));
  23.  
  24. if(!readfile($dir."/".$image[$n])) // Read the image
  25. readfile($dir."error/error.gif"); // If the script can't find the directory, display this image
  26. ?>

Report this snippet  

Comments

RSS Icon Subscribe to comments
Posted By: Grandmaster on October 7, 2010

my solution, think it's better and has extension check

$dir = 'i'; $imgext = array('jpg', 'jpeg', 'gif', 'png'); $images = array(); if($handle = opendir($dir)) { while (false !== ($file = readdir($handle))) { $info = pathinfo($dir.'/'.$file); if(inarray($info['extension'], $img_ext)) {
$images[] = $file; } }

closedir($handle);

}

$random = array_rand($images); echo $images[$random];

Posted By: Grandmaster on October 7, 2010

my solution, think it's better and has extension check

$dir = 'i'; $imgext = array('jpg', 'jpeg', 'gif', 'png'); $images = array(); if($handle = opendir($dir)) { while (false !== ($file = readdir($handle))) { $info = pathinfo($dir.'/'.$file); if(inarray($info['extension'], $img_ext)) {
$images[] = $file; } }

closedir($handle);

}

$random = array_rand($images); echo $images[$random];

You need to login to post a comment.