duanjing2013 2016-09-21 09:43
浏览 69
已采纳

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 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;
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 R语言Rstudio突然无法启动
  • ¥15 关于#matlab#的问题:提取2个图像的变量作为另外一个图像像元的移动量,计算新的位置创建新的图像并提取第二个图像的变量到新的图像
  • ¥15 改算法,照着压缩包里边,参考其他代码封装的格式 写到main函数里
  • ¥15 用windows做服务的同志有吗
  • ¥60 求一个简单的网页(标签-安全|关键词-上传)
  • ¥35 lstm时间序列共享单车预测,loss值优化,参数优化算法
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值