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));
相关推荐
Ulyanov3 小时前
高保真单脉冲雷达导引头回波生成:Python建模与实践
开发语言·python·仿真·系统设计·单脉冲雷达
程序员陆业聪4 小时前
2025 年客户端技术盘点与 2026 年技术展望
android
阿猿收手吧!4 小时前
【C++】jthread:优雅终止线程新方案
开发语言·c++
lly2024064 小时前
《JavaScript 实例》
开发语言
十五年专注C++开发4 小时前
C++中各平台表示Debug的宏
开发语言·c++·debug
张小凡vip5 小时前
Python异步编程实战:基于async/await的高并发实现
开发语言·python
玩c#的小杜同学5 小时前
源代码保卫战:给C# 程序(混淆、加壳与反逆向实战)
开发语言·笔记·c#
xhBruce5 小时前
Android USB 存储 冷启动(开机自动插着 U 盘)场景
android·usb·vold
CheungChunChiu5 小时前
在 Android 14 上使用 scrcpy 的投屏问题与解决方案
android·adb
阿猿收手吧!6 小时前
【C++】Ranges:彻底改变STL编程方式
开发语言·c++