Show random image in PHP


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

Change $dir to image folder


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

You need to login to post a comment.