Hongmu Notes
Home Language Notes Selects a random file from a specified folder and returns its file name.
Language Notes PHP

Selects a random file from a specified folder and returns its file name.

Selects a random file from a specified folder and returns its file name.

A PHP function to randomly retrieve a filename from a specified directory:

 隐藏内容:登录后可查看
function getRandomFileName($dir) {
  // 获取目录下所有文件
  $files = glob($dir . '/*.*');

  if (empty($files)) {
    return null;
  }

  // 随机选择一个文件
  $file = $files[array_rand($files)];

  // 返回文件名
  return basename($file);
}

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!

 隐藏内容:登录后可查看
function getRandomFileNames($dir, $num) {
  // 获取目录下所有文件
  $files = glob($dir . '/*.*');

  if (empty($files)) {
    return null;
  }

  $count = count($files);

  // 如果文件数量不足 $num,则直接返回所有文件名
  if ($count <= $num) {
    $fileNames = array_map('basename', $files);
    return $fileNames;
  }

  // 随机选择 $num 个文件
  $randomIndexes = array_rand($files, $num);

  // 获取选中文件的文件名
  $fileNames = array();
  foreach ($randomIndexes as $index) {
    $fileNames[] = basename($files[$index]);
  }

  return $fileNames;
}

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.

微信赞赏

WeChat

支付宝赞赏

Alipay

✍️ Author: Hong Mu

webmaster · Thanks for reading, stay tuned for more exciting content

Author homepage View home page →

Related articles

PHP ob function record

PHP ob function record Language Notes PHP

Usage of the following three functions ob_get_contents(); ob_end_clean(); ob_start(); You can use these functions to buffer local files and execute local script code. Use ob_start() to save the output code into the buffer, and the page will not be displayed; then use ob_get_contents to get the data in the buffer. o…
👁 141
PHP preg

PHP preg Language Notes PHP

The preg_match_all function is used to perform a global regular expression match. preg_match_all() Syntax int preg_match_all ( string $pattern , string $subject [, array &$matches [, int $flags = PREG…
👁 169
Detailed explanation of PHP ternary operator and if

Detailed explanation of PHP ternary operator and if Language Notes PHP

Ternary operator condition ? Result 1 : Result 2 Explanation: The position in front of the question mark is the condition for judgment. If the condition is met, the result is 1, and if it is not met, the result is 2. This article compares and explains the ternary operator and if...else... in detail. I hope it will be helpful to everyone. Today when I was revising my paper online, I encountered a statement that I couldn’t understand: $if_summary = $row['IF_SUMMARY']=…
👁 189
PHP cast type

PHP cast type Language Notes PHP PHP collection PHP and mysql

Get the data type 1. If you want to check the value and type of an expression, use var_dump(). 2. If you just want to get an easy-to-read type expression for debugging, use gettype(). 3. To check a certain type, do not use gettype(), but use the is_type() function. Converting Strings to Numbers When a string is evaluated as a number, the result is determined according to the following rules...
👁 232

Recommended reading

Responsive Advertising Design Creative Agency Website Template 0243

Responsive Advertising Design Creative Agency Website Template 0243 Practical Collection Yiyou template

This EyouCMS responsive template is ideal for advertising design and creative agencies. Its innovative visual design style is perfect for showcasing advertising projects, creative case studies, brand strategy initiatives, and service offerings. It helps advertising agencies demonstrate their professional expertise online and attract brand clients. Template Display | Installation Instructions | Website Backend: /login.php | Username: admin | Password: admin | Related Articles: Summary of Common Installation Issues for EyouCMS | EyouCMS...
👁 42
(Adaptive mobile version) Wide-screen, blue, sophisticated mechanical gear-themed PBootCMS template; Responsive hardware bearing manufacturing website source code download – 0338

(Adaptive mobile version) Wide-screen, blue, sophisticated mechanical gear-themed PBootCMS template; Responsive hardware bearing manufacturing website source code download – 0338 Practical Collection pbootcms Template

This adaptive mobile-friendly website template for PbootCMS is designed with a spacious, professional, and precise aesthetic, ideal for showcasing industrial products such as gears and bearings. It enables machinery manufacturing enterprises to demonstrate their technical expertise online and attract industrial clients. Template Overview | Installation Instructions | Website Backend: /admin.php | Username: admin | Password: admin | Extraction Password: www.4s5...
👁 57
Empire Toolbox V1.0

Empire Toolbox V1.0 Practical Collection empire plugin

As a webmaster who frequently uses Empire CMS, I often find certain operations to be particularly cumbersome! For example, I might want to change the Empire CMS database table prefix; or perhaps I want to batch modify the thumbnails for all articles collected from an external source; or if the images in the collected articles have become invalid, I might want to randomly replace them with new images; or I might want to batch delete other unnecessary tables from the Empire CMS database; or perhaps I've forgotten my Empire CMS admin panel password...
👁 443
Responsive Web Design – Advertising Design Agency Website Template 0244

Responsive Web Design – Advertising Design Agency Website Template 0244 Practical Collection Yiyou template

An eyouCMS responsive website template designed specifically for web design and advertising agencies. Its creative and professional design style is ideal for showcasing website designs, advertising creatives, brand visuals, and case studies. This template helps design firms demonstrate their expertise online and attract corporate clients. Template Overview | Installation Instructions | Website Backend: /login.php | Username: admin | Password: admin | Related Articles: Summary of Common Installation Issues for YouYouCMS | YouYouCMS...
👁 48
(Adaptive mobile version) Production website template for household goods (paper plates, boxes, cups, toilet paper, and tissue products) – PBootCMS; Download source code for a household goods manufacturer's website – 0339

(Adaptive mobile version) Production website template for household goods (paper plates, boxes, cups, toilet paper, and tissue products) – PBootCMS; Download source code for a household goods manufacturer's website – 0339 Practical Collection pbootcms Template

An adaptive PbootCMS website template designed for home goods (paper plates and cups) and daily necessities production. The design features a fresh and practical style, making it ideal for showcasing paper products, disposable tableware, and general household items. This template helps manufacturers of daily-use goods showcase their product lines online and expand their wholesale distribution channels. Template Preview | Installation Instructions | Website Backend: /admin.php | Username: admin | Password: admin | Extraction Password: www.4s5...
👁 53
PHP: Delete all files in a specified directory.

PHP: Delete all files in a specified directory. Language Notes PHP

You can use PHP's `glob()` function to find all files in the current directory, then use a loop to check whether each file name should be deleted, and use the `unlink()` function to remove the unwanted files. Here is an example code: `<?php $files = glob("*"); // 查找当前目录下的所有文件 foreach($ $file)...`
👁 148