php 解压文件与压缩文件

版权声明:独学而无友,则孤陋寡闻。q群582951247 https://blog.csdn.net/mp624183768/article/details/84135483

配置环境变量

然后cmd 输入 php -m

查看是否有zip 选项 没有的话zip功能将无法使用

function zip_file(string $filename)
{
    if (!is_file($filename)) {
        return false;
    }
    $zip = new ZipArchive();
    $zipName = basename($filename) . '.zip';
    //打开指定压缩包,不存在则创建,存在则覆盖
    if ($zip->open($zipName, ZipArchive::CREATE | ZipArchive::OVERWRITE)) {
//将文件添加到压缩包中
        if ($zip->addFile($filename)) {
            unlink($filename);
        }
        $zip->close();
        return true;
    } else {
        return false;
    }


}

/*
 * 多文件压缩
 */
function zip_files(string $zipName, ...$files)
{
    //检测压缩包名称是否正确
    $zipExt = strtolower(pathinfo($zipName, PATHINFO_EXTENSION));
    if ("zip" !== $zipExt) {
        return false;
    }
    $zip = new ZipArchive();
    if ($zip->open($zipName, ZipArchive::CREATE | ZipArchive::OVERWRITE)) {
        foreach ($files as $file) {
            if (is_file($file)) {
                # $zip->addFile($file);
                //将文件添加到压缩包中
                if ($zip->addFile($file)) {
                    unlink($file);
                }
            }
        }
        return true;

    } else {
        return false;
    }
    $zip . close();

}

/**
 * 解压缩
 * @param string $zipName
 * @param string $dest
 * @return bool
 */
function unzip_file(string $zipName, string $dest)
{
    //检测要解压压缩包是否存在
    if (!is_file($zipName)) {
        return false;
    }
    //检测目标路径是否存在
    if (!is_dir($dest)) {
        mkdir($dest, 0777, true);
    }
    $zip = new ZipArchive();
    if ($zip->open($zipName)) {
        $zip->extractTo($dest);
        $zip->close();
        return true;
    } else {
        return false;
    }

}

猜你喜欢

转载自blog.csdn.net/mp624183768/article/details/84135483