简体   繁体   English

PHP检查文件是否同时存在于多个文件夹中

[英]php check if file exist on multiple folders at the same time

when i want to check if a file exist and if exist add a suffix i use the following code which is working fine 当我想检查文件是否存在以及是否存在时添加后缀时,我使用以下代码可以正常工作

    $increment = ''; //start with no suffix
    while(file_exists($_SERVER["DOCUMENT_ROOT"]."/".$file_name . $increment . '.' . $extension)) 
    {
       $increment++;
    }
    $final_name = $file_name . $increment. '.' . $extension;

Now i have to check if the file exist in more that one folder and the names of the folders are in an array (and i can add or remove folders from this array); 现在,我必须检查文件是否存在于一个以上的文件夹中,并且文件夹的名称在一个数组中(并且我可以从该数组中添加或删除文件夹);

$folders[] = "thumb";
$folders[] = "medium";
$folders[] = "large";
$folders[] = "xlarge";

Now i have to check if the file exist in all these folders. 现在,我必须检查文件是否存在于所有这些文件夹中。

If the file exist in one of this folders i have to add a suffix check again until the file does not exist in all of these folders 如果该文件存在于该文件夹之一中,则必须再次添加后缀检查,直到所有这些文件夹中都不存在该文件为止

Any help appreciated. 任何帮助表示赞赏。

I'll agree with @arkascha 's view that if the file is for internal use, using file name with unique hash will be better. 我同意@arkascha的观点,即如果该文件供内部使用,则使用具有唯一哈希的文件名会更好。

But if it's necessary, Try use foreach() to check those prefix in your array at once. 但是,如果有必要,请尝试使用foreach()一次检查数组中的那些前缀。

function files_suffix_exists($file_name, $folders){
    $root = $_SERVER["DOCUMENT_ROOT"];
    if(file_exists($root."/".$file_name . '.' . $extension){
        return true;
    }
    foreach($folders as $folder){
        if(file_exists($root."/".$folder."/".$file_name . '.' . $extension){
            return true;
        }
    }
    return false;
}

$folders[] = "thumb";
$folders[] = "medium";
$folders[] = "large";
$folders[] = "xlarge";


$increment = ''; //start with no suffix
while(files_suffix_exists($file_name, $folders))
   $increment++;
   $file_name .= $increment;
}

$final_name = $file_name . '.' . $extension;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM