自学内容网 自学内容网

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));


原文地址:https://blog.csdn.net/qq_39634880/article/details/140712797

免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!