如何从目录中随机选择PHP中的文件?
我必须从PHP中的目录中随机选择一个文件,假设有三个文件,比如index.PHP、a.PHP和b.PHP。如何确保我不选择index.php文件,而是随机选择其他文件。 到目前为止,我有以下代码如何从目录中随机选择PHP中的文件?,php,glob,Php,Glob,我必须从PHP中的目录中随机选择一个文件,假设有三个文件,比如index.PHP、a.PHP和b.PHP。如何确保我不选择index.php文件,而是随机选择其他文件。 到目前为止,我有以下代码 $dir = 'uploads'; $files = glob($dir . '/*.php'); $file = array_rand($files); echo $files[$file]; 这应该做到: $dir = 'uploads'; $files = glob($dir . '/*.php
$dir = 'uploads';
$files = glob($dir . '/*.php');
$file = array_rand($files);
echo $files[$file];
这应该做到:
$dir = 'uploads';
$files = glob($dir . '/*.php');
while (in_array($file = array_rand($files),array('index.php')));
echo $files[$file];
可以排除包含“index.php”的数组中的其他文件名
只有当目录中的文件超过'index.php'时,它才起作用。我的随机文件设置,也许你只需要添加文件扩展名,。。但这是肯定的 我不喜欢,因为它会复制阵列,它也使用了大量的CPU和RAM 我得出了这个结果
<?php
$handle = opendir('yourdirname');
$entries = [];
while (false !== ($entry = readdir($handle))) {
if($entry == 'index.php'){
// Sorry now allowed to read this one...
}else{
$entries[] = $entry;
}
}
// Echo a random item from our items in our folder.
echo getrandomelement($entries);
// Not using array_rand because to much CPU power got used.
function getrandomelement($array) {
$pos=rand(0,sizeof($array)-1);
$res=$array[$pos];
if (is_array($res)) return getrandomelement($res);
else return $res;
}
只需构建一个数组来排除并使用array_diff:
…通过在目录中不包含index.php来保存不应返回index.php的随机文件。。。当然可以?添加一个if来检查$files[$file]是否等于index.phpI不能移动index.php检查应该是$dir.index.php==$files[$file]`还是仅仅是index.php==$files[$file]`忘记了一个not:D,我编辑了我以前的评论
$exclude = array("$dir/index.php");
$files = array_diff(glob("$dir/*.php"), $exclude);