Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/235.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何从目录中随机选择PHP中的文件?_Php_Glob - Fatal编程技术网

如何从目录中随机选择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

我必须从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');
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);