PHP从文件夹中提取随机图像

Tom*_*Tom 6 php arrays random directory image

我想知道从文件夹中提取随机图像的"更好"方法.

比如说,让php只从文件夹中选择一个随机图像,而不是搜索并创建它的数组.

这就是我今天的表现

<?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 = ''; 
    }
?>
Run Code Online (Sandbox Code Playgroud)

Nes*_*zon 12

试试这个:

<?php

$dir = "images/";
$images = scandir($dir);
$i = rand(2, sizeof($images)-1);
?>

<img src="images/<?php echo $images[$i]; ?>" alt="" />
Run Code Online (Sandbox Code Playgroud)