PHP:压缩 Zip

文章来源:http://www.cnblogs.com/hello-tl/p/7661222.html

<?php

# 文件字符集
header("Content-type: text/html; charset=utf-8");

class TL_ZIP{
    # web 跟
    private $TL_ROOT;

    # zip包 目录
    private $TL_DOWNLOAD;

    # zip文件名
    private $TL_zipName;

    public function __construct(){
        # 设置web根目录
        $this->TL_ROOT = str_replace("\\", '/', dirname(__FILE__) . "/");

        # 设置zip目录
        $this->TL_DOWNLOAD = str_replace("\\", '/', dirname(__FILE__)) . "/DOWNLOAD/";
    }

    # 设置 压缩包名称
    public function getZipName($zipName){
        # 判断一下文件名是否合法
        $this->TL_zipName = $this->TL_DOWNLOAD . $zipName . ".zip";
        return true;
    }

    # 获取 压缩包名称
    public function setZipName(){
        return $this->TL_zipName;
    }

    # 生成压缩包
    public function createZip($arrFiles){
        # 判断是否是数组
        if(!is_array($arrFiles)){
            return false;
        }

        # 判断是否设置文件名  如果没有设定文件名 我就自己生成一个 哼!!!!
        if(!$this->TL_zipName){
            $this->TL_zipName = $this->TL_DOWNLOAD . date('YmdHis') . rand(111111111,999999999) . ".zip";
        }

        # 定义zip文件名
        $zipName = $this->TL_zipName;

        # 调用zip类
        $zipClass = new ZipArchive();
        if($zipClass->open($zipName, ZIPARCHIVE::CREATE) !== TRUE) {
            return false;
        }
        foreach($arrFiles as $path){

            # 判断是否是文件
            if(is_file($this->TL_ROOT.$path)){

                # 把文件加入到压缩包中
                $zipClass->addFile($this->TL_ROOT.$path, basename($this->TL_ROOT.$path));
            }
        }
        $zipClass->close();
        return $zipName;
    }
}


$zipObj = new TL_ZIP();
$zipObj->createZip(
    array(
        '从设定的跟目录开始写文件地址',
        '从设定的跟目录开始写文件地址',
        '从设定的跟目录开始写文件地址'
    )
);

文章来源:http://www.cnblogs.com/hello-tl/p/7661222.html

posted @ 2017-10-13 14:59  小田吃饺子  阅读(311)  评论(0编辑  收藏  举报