如何修改PHP代码让文件地址获取接口同时支持文件和文件夹查询?
问题原因
原有代码默认传入的路径数组所有元素均为目录,直接调用scandir()读取目录内容,当元素是存在的文件路径时,scandir()执行失败,无法生成对应访问地址,因此无返回结果。
修改后完整PHP代码
<?php function getDirContents($directories, &$results = array()){ // 提前提取公共URL前缀,避免循环中重复计算 $directory_path = basename($_SERVER['REQUEST_URI']); $url_prefix = 'https://' . $_SERVER['SERVER_NAME'] . str_replace($directory_path, "", $_SERVER['REQUEST_URI']); $length = count($directories); for ($i = 0; $i < $length; $i++) { $current_path = $directories[$i]; // 路径不存在直接跳过,避免报错 if (!file_exists($current_path)) { continue; } // 判断为单个文件直接生成URL加入结果 if (is_file($current_path)) { $results[] = $url_prefix . $current_path; continue; } // 目录场景走原有遍历逻辑 $files = array_diff(scandir($current_path), array('..', '.')); foreach($files as $key => $value){ $path = $current_path . DIRECTORY_SEPARATOR . $value; if(is_dir($path)) { getDirContents([$path], $results); } else { $results[] = $url_prefix . $path; } } } return $results; } echo json_encode(getDirContents($_POST['directories']));
主要修改点
- 新增路径存在性校验,避免传入无效路径时抛出异常
- 增加
is_file()判断逻辑,若传入路径是已存在的单个文件,直接生成访问地址加入结果集 - 将URL前缀计算逻辑提到循环外,减少重复运算,提升执行效率
- 修复原代码中多余分号的语法冗余问题
修改后完全兼容原有目录遍历的功能,同时支持传入单个文件路径返回对应访问地址。
内容的提问来源于stack exchange,提问作者Sara Ree
相关产品推荐
相关产品推荐

