首页 > 解决方案 > 如何防止在此功能中进行双重检查?

问题描述

这是从给定目录中搜​​索并返回现有文件的代码:

<?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

已重新检查并添加到结果中。

在此处输入图像描述

我该如何解决这个问题?

标签: php

解决方案


如果$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;
}

推荐阅读