Random Image PHP


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

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


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

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.