使用OPENDIR()选择随机文件 [英] Select random file using OPENDIR()

查看:97
本文介绍了使用OPENDIR()选择随机文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试过:

function random_pic($dir = '../myfolder') {
    $files = opendir($dir . '/*.*');
    $file = array_rand($files);
    return $files[$file];
}

此功能使用glob()起作用,但不能使用opendir.

This function works using glob() but not opendir.

这将返回打开目录失败错误.我猜opendir无法接受*.*之类的东西?是否可以选择一个文件夹中的所有文件并随机选择一个?

This returns a failed to open directory error. I guess opendir cannot accept things like *.*? Is it possible to select all files in a folder and randomly choose one?

推荐答案

opendir()函数不会返回文件/文件夹列表.它只会打开closedir()readdir()rewinddir()可以使用的句柄.此处的正确用法是glob(),但是正如我看到的那样,您也可以像下面这样使用scandir():

The opendir() function wont return a list of files/folders. It will only open a handle that can be used by closedir(), readdir() or rewinddir(). The correct usage here would be glob(), but as I see that you don't want that, you could also use scandir() like the following:

<?php
$path = "./";

$files = scandir($path);
shuffle($files);

for($i = 0; ($i < count($files)) && (!is_file($files[$i])); $i++);

echo $files[$i];
?>

在您承认我没有错"之后,我很乐意安排时间,以查看是否需要更长的时间或glob()是否需要更长的时间.

I'd happily do the timing to see if this takes longer or if glob() takes longer after you admit that I'm not "wrong."

这篇关于使用OPENDIR()选择随机文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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