Posted By

skywalker on 03/20/08


Tagged

php image random


Versions (?)

Who likes this?

7 people have marked this snippet as a favorite

basicmagic
mrjthethird
oriolfb
gripnrip
vali29
JoF
bug5


Random Image PHP


 / Published in: PHP
 

It gets images randomly from folder that you've pointed.

  1. <?php
  2. /**********************************************
  3. * Yazar : Richard Harris
  4. * Web : www.rtharris.com
  5. * Posta : [email protected]
  6. * Tarih : 16/02/06
  7. * Kullanım :
  8. * <img src=img.php>
  9. * <img src=img.php?folder=images2/>
  10. ***********************************************/
  11.  
  12. if($_GET['folder']){
  13. $folder=$_GET['folder'];
  14. }else{
  15. $folder='/images/';
  16. }
  17.  
  18. //Selected Folder Name
  19. $path = $_SERVER['DOCUMENT_ROOT']."/".$folder;
  20. $files=array();
  21. if ($handle=opendir("$path")) {
  22. while(false !== ($file = readdir($handle))) {
  23. if ($file != "." && $file != "..") {
  24. if(substr($file,-3)=='gif' || substr($file,-3)=='jpg') $files[count($files)] = $file;
  25. }
  26. }
  27. }
  28. closedir($handle);
  29.  
  30. $random=rand(0,count($files)-1);
  31. if(substr($files[$random],-3)=='gif') header("Content-type: image/gif");
  32. elseif(substr($files[$random],-3)=='jpg') header("Content-type: image/jpeg");
  33. readfile("$path/$files[$random]");
  34. ?>
  35.  
  36. Usage :
  37. It's very easy to use. Just copy the code to a new php file and save it "randomImages.php".
  38.  
  39. Then where ever you would like to use and show your random images, use this way and don't forget to add folder name to a string.
  40. <img src=randomImages.php?folder=randomFolder02/>

Report this snippet  

You need to login to post a comment.