简体   繁体   English

在PHP中随机选择文件

[英]Randomly select file in PHP

I'd like to use the 'include' keyword in php to randomly select a file from a folder and output the contents. 我想在php中使用'include'关键字从文件夹中随机选择一个文件并输出内容。 How would I do this? 我该怎么做?

Thanks. 谢谢。

Assuming you know the folder where the files are and that the files are PHP files: 假设您知道文件所在的文件夹,并且这些文件是PHP文件:

$phpFiles = glob('/path/to/files/*.php');

if (empty($phpFiles) === false)
{
    $randomFile = $phpFiles[array_rand($phpFiles)];
    include($randomFile);
}

glob() would read filenames into array. glob()会将文件名读入数组。
and then you can shuffle this array and pick a random item. 然后您可以随机播放此数组并选择一个随机项目。

use glob to get an array of files. 使用glob获取文件数组。 shuffle the array. 随机排列数组。 array_shift the first file off of the array. array_shift将第一个文件移出数组。 Include it. 包括它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM