TypechoJoeTheme

Dcr163的博客

统计

PHP解压zip压缩包

2021-06-03
/
0 评论
/
1,012 阅读
/
正在检测是否收录...
06/03

PHP解压zip压缩包

有些虚拟空间不支持解压.zip压缩文件,这里使用PHP语言解压,直接在浏览器执行即可解压压缩包,直接上代码

<?php
/**
 * php zip文件解压库
 * Created by dcr163.
 * Author: Dcr163
 * Date: 2021/6/3
 * Time: 10:45
 */

class unzip{
    public $file;       //解压的文件名
    public $dist;       //解压的目录
    public function __construct($file,$dist)
    {
        if( !$file || !$dist ) throw new ErrorException('参数不能为空');
        $this->file = $file;
        $this->dist = $dist;
    }
    /**
     * 解压zip文件
     * @param $file zip文件
     * @param $dist 解压的目录
     */
    function index(){
        if(!class_exists('ZipArchive')) throw new ErrorException('ZipArchive:扩展不存在');
        $zip = new ZipArchive();
        $openRes = $zip->open($this->file);
        if( $openRes === true) {
            $stime = $this->formatMicotime(microtime()); //
            $res = $zip->extractTo($this->dist);
            $etime = $this->formatMicotime(microtime());
            if( $res ) {
                throw new ErrorException('解压成功,总花费:'.round($etime-$stime,2).'S');
            }
            $zip->close();
        } else {
            throw new ErrorException('zip文件打开失败,错误代码:'.$this->zipErrorMsg($openRes));
        }
    }
    /**
     * 错误提示
     * @param $code
     * @return mixed|string
     */
    protected function zipErrorMsg($code){
        $errorCode = array(
            4=>'Seek error',
            5=>' Read error',
            9=>'No such file.',
            10=>'File already exists.',
            11=>'Can\'t open file.',
            14=>'Malloc failure.',
            18=>'Invalid argument.',
            19=>'Not a zip archive.',
            21=>'Zip archive inconsistent',
        );
        return array_key_exists($code,$errorCode) ? $errorCode[$code] : '未知错误';
    }
    /**
     * 格式化时间戳和微秒数
     * @param $microtime
     * @return mixed
     */
    protected function formatMicotime($microtime){
        list($usec,$sec) = explode(' ',$microtime);
        return  $sec+$usec;
    }
}
try{
    //需要解压的文件
    $file = './phpmyadmin4.9.7.zip';
    //解压的目录
    $dist = 'ad';
    $zip = new unzip($file,$dist);
    $zip->index();
}catch (Exception $e){
    exit($e->getMessage());
}

使用方法

把代码复制,保存到一个文件里,例如:/unzip.php,最后在浏览器运行文件即可。

朗读
赞(0)
版权属于:

Dcr163的博客

本文链接:

https://dcr163.cn/476.html(转载时请注明本文出处及文章链接)

评论 (0)