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));
相关推荐
bksczm13 分钟前
Linux之信号量(POSIX标准)
java·开发语言
吠品24 分钟前
PHP里取月份最后一天的几种方式
java·开发语言·eureka
CallmeFoureyes25 分钟前
使用 C# 提取 Word 文档中的表格数据
开发语言·c#·word
浪客川35 分钟前
AOSP源码隐藏状态栏
android·aosp
gugucoding42 分钟前
2. 【Java】搭建Java开发环境
java·开发语言
多加点辣也没关系42 分钟前
JavaScript|第9章:对象 — 基础
开发语言·javascript·ecmascript
2601_949818091 小时前
Vector从入门到应用(C++ STL动态数组万字全解
开发语言·c++
没有了遇见1 小时前
AI Agent 是什么?—— 一文理解 LLM、Memory、Skills、Tools、MCP、Workflow,Context
android·前端·程序员
汤米粥2 小时前
Python爬虫中Xpath用法之——normalize-space()
开发语言·python
御坂嘀喵2 小时前
Speed Tools:一套低侵入的 Android 插件化 + 动态换肤 + 字体切换框架
android·gitee