PHP 从文件夹中提取随机图像 [英] PHP pull random image from folder

查看:27
本文介绍了PHP 从文件夹中提取随机图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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 从文件夹中提取随机图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆