PHP中的文件查找可以使用目录/文件相关的函数实现,具体步骤如下:
- 使用opendir打开目录。
- 使用readdir依次读取目录中的文件或子目录。
- 若是文件则判断是否符合查找条件,若是子目录则同样使用opendir、readdir处理。
下面以查找图片文件为例,给出代码实现:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 |
/** * @param string $path 要扫描的路径 * @param array $result 存放结果文件 */ function find_img($path, &$result) { // 处理目录 if (is_dir($path)) { // 使用opendir打开目录 if ($handle = opendir($path)) { // 使用readdir依次读取目录中的所有文件或子目录 while (($file = readdir($handle)) !== false) { if ($file != '.' && $file != '..') { // 递归处理子目录或文件 find_img($path . '/' . $file, $result); } } } else { echo "打开目录'{$path}'失败\n"; } } else if (is_file($path)) { // 处理文件,检测文件是否符合查找条件 $ext = pathinfo($path, PATHINFO_EXTENSION); if (in_array($ext, array('gif', 'jpg', 'png', 'bmp'))) { $result[] = $path; } } else { echo "'{$path}'打开失败\n"; } } find_img('./path_to_search', $result); var_dump($result); |