duanjing2013
2016-09-21 09:43 阅读 67
已采纳

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

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.

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享

1条回答 默认 最新

  • 已采纳
    dongzhuang6417 dongzhuang6417 2016-09-21 10:19

    I'll agree with @arkascha 's view that if the file is for internal use, using file name with unique hash will be better.

    But if it's necessary, Try use foreach() to check those prefix in your array at once.

    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;
    
    点赞 评论 复制链接分享

相关推荐