Thursday, July 8, 2010

PHP - Printing a random file from a folder

This is one of the easiest ways to ad management out there. It selects a random file from the directory you chose and displays them randomly.
This code is useful if you have ad codes in different files and want to randomly rotate them.




  1. $rmdlist='';


  2. //$rmd_folder is the variable that choses the directory that the files will be in. Mine is images/rmd-img/

  3. // Make sure you DO NOT forget about the "/" at the end or this will not work.

  4. $rmd_folder = "images/rmd-img/";


  5. mt_srand((double)microtime()*1000);


  6. //use the directory class

  7. $imgs = dir($rmd_folder);


  8. //reads all the files from the directory you chose and ads them to a list.

  9. while ($file = $imgs->read()) {

  10. if (eregi("gif", $file) || eregi("jpg", $file) || eregi("png", $file))

  11. $rmdlist .= "$file ";


  12. } closedir($imgs->handle);


  13. //now, put all the images into a array

  14. $rmdlist = explode(" ", $rmdlist);

  15. $no = sizeof($rmdlist)-2;


  16. //now, generate a randon number from 0 - the number of images in the directory you chose.

  17. $random = mt_rand(0, $no);

  18. $image = $rmdlist[$random];


  19. //display's the image.

  20. echo '';

  21. ?>


No comments: