php zip 文件解压

php zip 文件解压

/**
 * @param string $zipFile 需要解压的文件
 * @param string $unZipDir 解压后的文件夹路径
 * @return bool
 */
function unZip($zipFile, $unZipDir)
{
    $zip = new \ZipArchive;
    if ($zip->open($zipFile) === TRUE) {
        is_dir_mkdir($unZipDir);
        
        $docNum = $zip->numFiles;
        for ($i = 0; $i < $docNum; $i++) {
            $statInfo = $zip->statIndex($i, \ZipArchive::FL_ENC_RAW);
            // 此处如果 php >= 7.1 则无需调用 transcoding() 函数,如果为了兼容 php 旧版本,可以调用该函数
            $filename = transcoding($statInfo['name']);
            if ($statInfo['crc'] == 0) {
                //新建目录
                $newFileDir = $unZipDir . DIRECTORY_SEPARATOR . substr($filename, 0, -1);
                is_dir_mkdir($newFileDir);
            } else {
                //拷贝文件
                $source = 'zip://' . $zipFile . '#' . $zip->getNameIndex($i);
                $dest = $unZipDir . DIRECTORY_SEPARATOR . $filename;
                copy($source, $dest);
            }
        }
        
        $zip->close();

        return true;
    } else {
        return false;
    }
}

/**
 * 判断文件路径是否存在,不存在则生成
 * @param string $filePath 文件路径
 */
function is_dir_mkdir($filePath)
{
    if (!is_dir($filePath)) {
        mkdir($filePath, 0755, true);
    }
}

/**
 * 根据php版本以及系统环境决定是否编码转换,以 php 版本 7.1 为分界线
 * @param string $codeWords 需要编码转换检测的文字
 * @return false|string
 */
function transcoding($codeWords)
{
    if (version_compare(PHP_VERSION, '7.1') === -1) {
        $encoding = mb_detect_encoding($codeWords, ['ASCII', 'UTF-8', 'GBK', 'GB2312', 'BIG5', 'CP936']);
        if (DIRECTORY_SEPARATOR == '/') {    //linux
        	// 这里转换也建议使用 mb_detect_encoding() 函数
            $codeWords = iconv($encoding, 'UTF-8', $codeWords);
        } else {  //win
        	// 这里转换也建议使用 mb_detect_encoding() 函数
            $codeWords = iconv($encoding, 'GBK//ignore', $codeWords);
        }
    } else {
        if (DIRECTORY_SEPARATOR == '/') {    //linux
            $codeWords = $codeWords;
        } else {  //win
            $codeWords = $codeWords;
        }
    }

    return $codeWords;
}
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值