Home  >  Article  >  Backend Development  >  PHP 获取目录下的图片并随机显示的代码_PHP

PHP 获取目录下的图片并随机显示的代码_PHP

WBOY
WBOYOriginal
2016-06-01 12:22:31889browse

当时想做一个随机更换背景图片的功能,用JavaScript写的话,程序流程应该是:建立一个图片数组->随机选择数组里其中一个值->生成样式并写入body标签。
可是用JS做的话,有以下缺点:
1.万一浏览器禁用了JS的话就失效了,而且写代码是需要考虑兼容性。
2.维护比较麻烦,图片的位置都存放在数组里。
于是我提议用PHP处理,可是我和她对PHP都是半桶水的,一时之间也想不出怎么做。今天时运高,看到一个PHP随机显示目录下图片的源码,学习一下,并分享之。 

先看看原理:从一个目录里获取某类型文件的清单(用在WEB的话一般是jpg/gif/png)->通过随机函数选一个图片->输出代码。
PHP代码如下:
复制代码 代码如下:
$imglist='';
//用$img_folder变量保存图片所在目录,必须用“/”结尾
$img_folder = "images/tutorials/";
mt_srand((double)microtime()*1000);
//使用目录类
$imgs = dir($img_folder);
//检查目录下是否有图片,并生成一个清单
while ($file = $imgs->read()) {
if (eregi("gif", $file) || eregi("jpg", $file) || eregi("png", $file))
$imglist .= "$file ";
} closedir($imgs->handle);
//把清单里的项都放到一个数组里
$imglist = explode(" ", $imglist);
$no = sizeof($imglist)-2;
//生成一个介于0和图片数量之间的随机数
$random = mt_rand(0, $no);
$image = $imglist[$random];
//输出结果
echo '';

如果要通过这个函数变换页面背景的话,可以把最后一句改为:
复制代码 代码如下:
echo '

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn