随机文件选择程序

问题描述 投票:1回答:4

我正在尝试创建一个php文件,在.php文件所在的目录中找到一个随机文件,获取该文件的名称并将其返回。也就是说,它会返回类似“text45.txt”的内容作为输出。 (不是文件里面的文字只是文件名和扩展名)

我需要它选择一个随机文件,但在选择的目录中选择一个随机文件时,停止选择“results.php”,因为这是用于抓取随机文件的文件。

<?php
$files = glob(realpath('./') . '/*.*');
$file = array_rand($files);
echo basename($files[$file]);
?>
php file random
4个回答
0
投票

用于随机选择文件

function random_files($array_files_list, $no_of_select ){
    if( count($array_files_list) <= $no_of_select ){
        return array_rand($array_files_list, $no_of_select);
    }else{
        return array_rand($array_files_list, count($array_files_list)-1 );
    }
}

0
投票

如果您不需要过滤器文件,则可以使用scandir而不是glob来获取目录中的文件名。这是解决方案

// current directory
$dir = getcwd();
// get all files in directory
$files = scandir($dir);

//filter only files and remove 'results.php' file
$file_arr = array_filter($files, function($file){
     return is_file($file) && $file != "results.php";
});

$file_name = array_rand($file_arr);
echo $file_arr[$file_name];

0
投票

你可以这样做:

<?php

$files = glob(realpath('./') . '/*.*');

// Search the array for the file results.php and return its key
$unwanted_file = array_search(realpath('./results.php'),$files);

//Then remove it from the array
unset($files[$unwanted_file]);

$file = array_rand($files);

echo basename($files[$file]);

?>

0
投票

您可以使用basename(__FILE__)查找当前正在执行的脚本的名称,并将其从文件数组中删除。

<?php
$files = glob(realpath('./') . '/*.*');

// Ensure the current script is not chosen.
$currentFile = basename(__FILE__);
if (array_key_exists($currentFile, $files)) {
    unset($files[$currentFile]);
}

$file = array_rand($files);

echo basename($files[$file]);

更新

上面的代码不起作用,因为$key中的$files是数字。我们需要遍历文件并检查每个文件的basename。如果找到了,请取消设置。有更有效的方法来处理这个问题,但这应该适用于小型(ish)目录。

<?php
$files = glob(realpath('./') . '/*.*');

// Ensure the current script is not chosen.
$currentFile = basename(__FILE__);
foreach ($files as $key => $file) {
    if (basename($file) === $currentFile) {
        unset($files[$key]);
    }
}

$randomFile = array_rand($files);

echo basename($files[$randomFile]);
© www.soinside.com 2019 - 2024. All rights reserved.