A PHP function to randomly retrieve a filename from a specified directory:
This function accepts a single parameter. $dirIndicates that the file directory path should be selected randomly. The function first uses glob() Use a function to retrieve the file paths of all files in a specified directory, then utilize them. array_rand() The function randomly selects a file from the collection. Finally, the function uses it. basename() The function retrieves the filename of the selected file and returns it.
If no files exist in the specified directory, this function will return. null。
You can call this function using the following methods:
$dir = '/path/to/files';
$filename = getRandomFileName($dir);
if ($filename !== null) {
echo $filename;
} else {
echo '指定目录下没有文件。';
}among,/path/to/files This function randomly selects a file directory path; upon being called, it randomly selects a file and returns its filename. If no files exist in the specified directory, the function returns nothing. null。
Secondary demand
I want to return multiple file names all at once!
This function accepts two parameters: the directory path. $dir Number of files to be retrieved $numIf the directory contains no files, return. nullIf the number of files is insufficient $numThen, it returns the filenames of all files in the directory directly.
If there are enough files, randomly select one from all files. $num Read a file, then collect the filenames of the selected files into an array and return it.
You can call this function using the following methods:
$dir = '/path/to/directory';
$num = 3;
$fileNames = getRandomFileNames($dir, $num);
print_r($fileNames);among,$dir It is the directory path.$num The number of files to retrieve. The function returns an array containing the randomly selected file names.