php - 如何防止在此功能中进行双重检查?
问题描述
这是从给定目录中搜索并返回现有文件的代码:
<?php
function getDirContents($directories, &$results = array()) {
$length = count($directories);
for ($i = 0; $i < $length; $i++) {
if(is_file($directories[$i])) {
if(file_exists($directories[$i])) {
$path = $directories[$i];
$directory_path = basename($_SERVER['REQUEST_URI']);
$results[] = 'https://' . $_SERVER['SERVER_NAME'] . str_replace($directory_path, "", $_SERVER['REQUEST_URI']) .$path;
}
} else {
$files = array_diff(scandir($directories[$i]), array('..', '.'));
foreach($files as $key => $value) {
$path = $directories[$i].DIRECTORY_SEPARATOR.$value;
if(is_dir($path)) {
getDirContents([$path], $results);
} else {
$directory_path = basename($_SERVER['REQUEST_URI']);
$results[] = 'https://' . $_SERVER['SERVER_NAME'] . str_replace($directory_path, "", $_SERVER['REQUEST_URI']) .$path;
}
}
}
}
return $results;
}
echo json_encode(getDirContents($_POST['directories']));
因此,您可以传递文件地址和目录的数组并获取这些目录中的文件,请注意,如果您传递的是文件地址而不是目录地址,则函数会检查是否存在这样的文件,如果存在则返回其地址结果 。
问题在于它工作正常的目录,但文件在结果中重复两次,并且对于每个文件,函数会在代码中仔细检查此 if 语句:
if(is_file($directories[$i]))
这是函数注释的结果,contemporary.mp3
并且Japanese.mp3
已重新检查并添加到结果中。
我该如何解决这个问题?
解决方案
如果$directories
同时包含目录和该目录中的文件,您将在文件名的结果中添加该文件,并在扫描目录时添加该文件。
一个简单的解决方法是在添加之前检查文件名是否已经在结果中。
<?php
function getDirContents($directories, &$results = array()) {
foreach ($directories as $name) {
if(is_file($name)) {
$path = $name;
$directory_path = basename($_SERVER['REQUEST_URI']);
$new_path = 'https://' . $_SERVER['SERVER_NAME'] . str_replace($directory_path, "", $_SERVER['REQUEST_URI']) .$path;
if (!in_array($new_path, $results)) {
$results[] = $new_path;
}
} elseif (is_dir($name)) {
$files = array_diff(scandir($name), array('..', '.'));
foreach($files as $key => $value) {
$path = $name.DIRECTORY_SEPARATOR.$value;
if(is_dir($path)) {
getDirContents([$path], $results);
} else {
$directory_path = basename($_SERVER['REQUEST_URI']);
$new_path = 'https://' . $_SERVER['SERVER_NAME'] . str_replace($directory_path, "", $_SERVER['REQUEST_URI']) .$path;
if (!in_array($new_path, $results)) {
$results[] = $new_path;
}
}
}
}
}
return $results;
}
推荐阅读
- python - 如何在 Python 中获取带有请求的文本响应
- azure - 通过安卓设备访问私网
- node.js - 如何使用 node.js 更新 mongo db 集合中的许多记录
- c - 通过类型转换指针将数据从一个结构指针分配给另一个
- javascript - 汉堡图标打不开
- c++ - 为什么我需要很多线程才能将 memcpy() 推到系统的极限?
- php - 如果不是空的 PHP WordPress 语法导致严重错误
- sql - 从 PostgreSQL 查询生成单个复杂的 JSON 对象
- angular - Angular dimamic elementRef 名称(不知道它是如何命名的)
- java - @ManyToMany 关系重复表中的行