php删除指定文件或者指定文件夹下所有的文件

话不多说,直接上代码

if (!function_exists('delete_dir')) {
    
    /**
     * 删除指定文件夹下文件
     * Author:刘星麟
     * @param $path 待删除目录路径或者文件路径
     * @param bool $delDir 是否删除目录,true删除目录,false只删除文件保留目录(包含子目录名称)
     * @return bool
     */
    function delete_dir($path, $delDir = false)
    {
        if (is_dir($path)) {
            $handle = opendir($path);
            if ($handle) {
                while (false !== ($item = readdir($handle))) {
                    if ($item != "." && $item != "..")
                        is_dir("$path/$item") ? delete_dir("$path/$item", $delDir) : unlink("$path/$item");
                }
                closedir($handle);
                if ($delDir) {
                    return rmdir($path);
                }
            } else {
                if (file_exists($path)) {
                    return unlink($path);
                } else {
                    return false;
                }
            }
        } else {
            return true;
        }
    }
}

猜你喜欢

转载自blog.csdn.net/liuxl57805678/article/details/103122572