我想知道从文件夹中提取随机图像的更好"方法.
I am wondering about a "better" way of pulling a random image from a folder.
比如,让 php 只需从文件夹中选择一个随机图像,而不是搜索和创建它的数组.
Like say, to have php just select a random image from folder instead of searching and creating an array of it.
这就是我今天的做法
<?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 = '';
}
?>
试试这个:
<?php
$dir = "images/";
$images = scandir($dir);
$i = rand(2, sizeof($images)-1);
?>
<img src="images/<?php echo $images[$i]; ?>" alt="" />
这篇关于PHP 从文件夹中提取随机图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!