函数功能
- 指定目录、扩展名模式(正则)
- 自动过滤
. .. 及隐藏文件
- 使用
mt_rand 均匀随机选取
- 返回完整路径
完整代码
<?php
function RandomFile($folder = '', $extensions = '.*') {
// 规范化路径
$folder = trim($folder);
$folder = ($folder === '') ? './' : rtrim($folder, '/\\') . DIRECTORY_SEPARATOR;
if (!is_dir($folder)) {
throw new InvalidArgumentException("Invalid folder: $folder");
}
$files = array();
$pattern = '/\.(' . $extensions . ')$/i';
if ($handle = @opendir($folder)) {
while (($file = readdir($handle)) !== false) {
if ($file[0] === '.') continue; // 跳过隐藏文件
if (preg_match($pattern, $file)) {
$files[] = $file;
}
}
closedir($handle);
} else {
throw new RuntimeException("Cannot open directory: $folder");
}
if (empty($files)) {
throw new RuntimeException("No matching files in $folder");
}
// 种子已由 PHP 自动播种(PHP 4.2+),无需 mt_srand
$idx = mt_rand(0, count($files) - 1);
return $folder . $files[$idx];
}
// 使用示例
try {
// 随机一张图片
echo '<img src="' . RandomFile('images/', 'jpg|png|gif|webp') . '" />';
// 随机任意文件
echo RandomFile('downloads/', '.*');
// 仅数字扩展名(如 backup.1, backup.2)
echo RandomFile('backups/', '[0-9]+');
} catch (Exception $e) {
echo 'Error: ' . $e->getMessage();
}
进阶:权重随机 / 最近最少使用
// 按文件大小加权随机(大文件概率高)
function WeightedRandomFile($folder, $ext) {
$files = glob($folder . '/*.' . $ext);
$weights = array_map('filesize', $files);
$total = array_sum($weights);
$rand = mt_rand(1, $total);
foreach ($files as $i => $f) {
$rand -= $weights[$i];
if ($rand <= 0) return $f;
}
return $files[0];
}
安全提示
- 严禁直接暴露用户上传目录为随机读取源,防止遍历下载敏感文件。
- 生产环境应维护“已审核文件清单”数据库表,从表中随机抽取 ID 再拼接路径。
- 输出前设置
Content-Disposition: attachment 强制下载,防止 XSS/脚本执行。