PHP拉从文件夹中随机图像 [英] PHP pull random image from folder
本文介绍了PHP拉从文件夹中随机图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想知道有关从文件夹中提取一个随机图像的更好的方式。
好比说,有PHP只是选择一个随机图像从文件夹而不是寻找和创造它的一个数组。
下面是今天我是怎么做的。
< PHP
$扩展=阵列(JPG,JPEG);
$ images_folder_path = ROOT/网络/文件/头/'。
$图像=阵列();
函数srand((浮点)microtime中()* 10000000); 如果($处理=执行opendir($ images_folder_path)){
而(假的!==($文件= READDIR($处理))){
如果($文件=&放!&放大器;!$文件=..){
$ EXT =用strtolower(SUBSTR(strrchr($文件),1)。);
如果(in_array($分机,$扩展)){
$图像[] = $文件;
}
}
}
closedir($处理);
}
如果(!空($图像)){
$ header_image = $图像[array_rand($图像)];
}其他{
$ header_image ='';
}
?>
解决方案
试试这个:
< PHP$ DIR =图片/;
$图像= SCANDIR($目录);
$ I =兰特(2,sizeof的($图像)-1);
?>< IMG SRC =图像/< PHP的echo $图像[$ i];>中ALT =/>
I am wondering about a "better" way of pulling a random image from a folder.
Like say, to have php just select a random image from folder instead of searching and creating an array of it.
here is how I do it today
<?php
$extensions = array('jpg','jpeg');
$images_folder_path = ROOT.'/web/files/Header/';
$images = array();
srand((float) microtime() * 10000000);
if ($handle = opendir($images_folder_path)) {
while (false !== ($file = readdir($handle))) {
if ($file != "." && $file != "..") {
$ext = strtolower(substr(strrchr($file, "."), 1));
if(in_array($ext, $extensions)){
$images[] = $file;
}
}
}
closedir($handle);
}
if(!empty($images)){
$header_image = $images[array_rand($images)];
} else {
$header_image = '';
}
?>
解决方案
Try this:
<?php
$dir = "images/";
$images = scandir($dir);
$i = rand(2, sizeof($images)-1);
?>
<img src="images/<?php echo $images[$i]; ?>" alt="" />
这篇关于PHP拉从文件夹中随机图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文