php判断某个目录下是否存在文件

复制代码
/**
 * 判断字符串是否以什么结尾
 * @param  String  $haystack 字符串
 * @param  String  $needle 结尾
 * @return Boolean
 */
function endWith($haystack, $needle) {
    $length = strlen($needle);
    if ($length == 0) {
        return true;
    }
    return (substr($haystack, -$length) === $needle);
}
/**
 * 判断目录下是否存在文件
 * @param  String  $path 目录路径
 * @param  String  $recursive 是否递归(false情况下只判断第一级目录,true递归目录下所有文件判断)
 * @return Boolean
 */
function dirExistFile($path,$recursive = false) {
    if (!is_dir($path)) {
        return false;
    }

    // 目录相隔符号,linux是 /,window一般是\
    if(!(endWith($path, '/') || endWith($path, '\\'))){
        $path .= '/';
    }

    if($recursive){
        // 递归遍历目录
        $files = new \RecursiveIteratorIterator(
            new \RecursiveDirectoryIterator($path),
            \RecursiveIteratorIterator::LEAVES_ONLY
        );

        $isExistFile = false;

        foreach ($files as $file) {
            if ($file->isFile()) {
                $isExistFile = true;
                break;
            }
        }

        return $isExistFile;
    }else{
        $files = scandir($path);

        // 删除  "." 和 ".."
        unset($files[0]);
        unset($files[1]);

        $isExistFile = false;

        foreach ($files as $fileName) {
            $fileNamePath = $path.$fileName;
            if(is_file($fileNamePath)){
                $isExistFile = true;
                break;
            }
        }

        return $isExistFile;
    }
}

var_dump(dirExistFile('C:\test',true));
相关推荐
H309198 分钟前
vue3+dhtmlx-gantt实现甘特图展示
android·javascript·甘特图
像风一样自由8 分钟前
【001】renPy android端启动流程分析
android·gitee
DanB241 小时前
Java笔记4
java·开发语言·笔记
Dddle11 小时前
C++:this指针
java·c语言·开发语言·c++
studyer_domi1 小时前
Matlab 234-锂电池充放电仿真
开发语言·matlab
yuanpan1 小时前
.net/C#进程间通信技术方案总结
开发语言·c#·.net
吃面不喝汤661 小时前
破解 Qt QProcess 在 Release 模式下的“卡死”之谜
开发语言·qt
@十八子德月生2 小时前
8天Python从入门到精通【itheima】-1~5
大数据·开发语言·python·学习
jiunian_cn2 小时前
【c++】异常详解
java·开发语言·数据结构·c++·算法·visual studio
martian6652 小时前
信创生态核心技术栈:数据库与中间件
开发语言·中间件·系统架构·系统安全·创业创新