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));
相关推荐
4Forsee4 分钟前
【Android】动态操作 Window 的背后机制
android·java·前端
martian6654 分钟前
深入解析C++驱动开发实战:优化高效稳定的驱动应用
开发语言·c++·驱动开发
HappRobot6 分钟前
python类和对象
开发语言·python
鸡吃丸子17 分钟前
React Native入门详解
开发语言·前端·javascript·react native·react.js
盼哥PyAI实验室20 分钟前
Python YAML配置管理:12306项目的灵活配置方案
开发语言·python
漂亮的小碎步丶21 分钟前
【启】Java中高级开发51天闭关冲刺计划(聚焦运营商/ToB领域)
java·开发语言
华锋202223 分钟前
2025.12首次体验 arkui-x 跨平台开发库
android
hd51cc28 分钟前
MFC运行时
开发语言·mfc
wniuniu_31 分钟前
ceph一些细节处理
开发语言·ceph
hd51cc31 分钟前
异常处理(Exception Handling)
开发语言