四海人民公摄 - 海外华人摄影爱好者论坛

 找回密码
 注册
搜索
热搜: 活动 交友 discuz
查看: 1117|回复: 0

Random images from a directory 2

[复制链接]
发表于 2009-12-18 14:59:58 | 显示全部楼层 |阅读模式
Have a bunch of images in a directory you want to display? Well, PHP can help you in doing it.
This PHP tutorial is a variation of the Randomizing With PHP. So I will not repeat whatever is explained there.



  1. <?php

  2. // LOCATION OF IMAGE DIRECTORY
  3. // DO NOT FORGET TO BEGIN AND END WITH A /
  4. $imageDirectory = "/images/directory/";

  5. // OPENS IMAGES DIRECTORY
  6. $dirHandle = opendir($_SERVER['DOCUMENT_ROOT'].$imageDirectory);

  7. // READS FILES IN THE DIRECTORY
  8. while (false !== ($dirFile = readdir($dirHandle)))
  9. {
  10.         // STRIPS . AND .. FROM FILES IN DIRECTORY
  11.         // DON'T REMOVE IF YOU WANT THIS SCRIPT TO WORK
  12.         if ($dirFile != "." && $dirFile != "..")
  13.         {
  14.                 // PUTS FILES INSIDE THE DIRECTORY IN AN ARRAY
  15.                 $randomFile[] = $dirFile;
  16.         }
  17. }

  18. // DISPLAYS RANDOM IMAGE FROM THE DIRECTORY
  19. // READ Randomizing With PHP TUTORIAL
  20. echo "<img src="".$imageDirectory.$randomFile[rand(0,count($randomFile)-1)]."" alt="Random Image">\n";

  21. // CLOSES DIRECTORY
  22. closedir($dirHandle);

  23. ?>

复制代码



Comments are placed on the code to explain what each part of the PHP code does.
The only thing you really need to change is the location of the image directory. Example, if your random images are located in http://www.blinding-light.com/images/random, the value for $imageDirectory variable becomes /images/random/.
Conclusion
Quite simple, huh? Just remember that with this code, all the files and folders in the directory you put in will be displayed as images so make sure all the files in the directory are image files and that there are no folders within it.
您需要登录后才可以回帖 登录 | 注册

本版积分规则

小黑屋|手机版|Archiver|四海人民公摄 - 海外华人摄影爱好者网站

GMT+8, 2024-5-4 15:57

Powered by Discuz! X3.5

Copyright © 2001-2023 Tencent Cloud.

快速回复 返回顶部 返回列表