메뉴 건너뛰기

프로그램언어

조회 수 653 추천 수 0 댓글 0
?

단축키

Prev이전 문서

Next다음 문서

크게 작게 위로 아래로 댓글로 가기 인쇄
?

단축키

Prev이전 문서

Next다음 문서

크게 작게 위로 아래로 댓글로 가기 인쇄
<?php
class DirectZip
{
    private static $BUFFER_SIZE = 4194304; // 4MiB

    private $currentOffset;
    private $entries;

    public function open($filename)
    {
        set_time_limit(0);
        ini_set('zlib.output_compression', 'Off');
        header('Pragma: no-cache');
        header('Expires: Thu, 01 Jan 1970 00:00:00 GMT');
        header('Cache-Control: no-store');
        header('Content-Type: application/zip');
        header('Content-Disposition: attachment; '
            . 'filename="' . rawurlencode($filename) . '"; '
            . 'filename*=UTF-8\'\'' . rawurlencode($filename));
        $this->currentOffset = 0;
        $this->entries = array();
    }

    public function addEmptyDir($dirname)
    {
        if ($this->addFile('php://temp', $dirname.'/') === false) {
            return false;
        }
    }

    public function addFromString($localname, $contents)
    {
        $tmp = tempnam(sys_get_temp_dir(), __CLASS__);

        $pointer = @fopen($tmp, 'wb');
        if ($pointer === false) {
            @unlink($tmp);
            return false;
        }

        fwrite($pointer, $contents);
        $result = $this->addFile($tmp, $localname);

        fclose($pointer);
        @unlink($tmp);

        if ($result === false) {
            return false;
        }
    }

    public function addFile($filename, $localname = null)
    {
        $entry = new DirectZipEntry($localname ?: basename($filename), $this->currentOffset);
        if ($entry->open($filename) === false) {
            return false;
        }

        $this->entries[] = $entry;

        ob_start();

        self::write(0x504B0304, 'N'); // sig entry
        self::writeEntryStat($entry);
        echo $entry->name;

        $this->currentOffset += strlen(ob_get_flush());

        while (!feof($entry->pointer)) {
            $buffer = @fread($entry->pointer, self::$BUFFER_SIZE);
            echo $buffer;
            flush();
            $this->currentOffset += strlen($buffer);
        }

        $entry->close();
    }

    public function close()
    {
        ob_start();

        foreach ($this->entries as $entry) {
            self::write(0x504B0102, 'N'); // sig index
            self::write(0); // os: fat
            self::writeEntryStat($entry);
            self::write(0); // comment len
            self::write(0); // disk # start
            self::write(0); // internal attr
            self::write(0, 'V'); // external attr
            self::write($entry->offset, 'V');
            echo $entry->name;
        }

        $length = strlen(ob_get_flush());

        self::write(0x504B0506, 'N'); // sig end
        self::write(0); // disk number
        self::write(0); // disk # index start
        self::write(count($this->entries)); // disk entries
        self::write(count($this->entries)); // total entries
        self::write($length, 'V');
        self::write($this->currentOffset, 'V');
        self::write(0); // comment len
        flush();
    }

    private static function writeEntryStat($entry) {
        self::write(substr($entry->name, -1) == '/' ? 20 : 10);
        self::write(2048); // flags: unicode filename
        self::write(0); // compression: store
        self::write($entry->mtime, 'V');
        self::write($entry->crc, 'V');
        self::write($entry->size, 'V'); // compressed size
        self::write($entry->size, 'V'); // uncompressed size
        self::write(strlen($entry->name));
        self::write(0); // extra field len
    }

    private static function write($binary, $format = 'v')
    {
        echo pack($format, $binary);
    }
}

class DirectZipEntry
{
    public $offset;
    public $pointer;

    public $name;
    public $crc;
    public $size;
    public $mtime;

    public function __construct($name, $offset)
    {
        $this->offset = $offset;
        $this->name = $name;
    }

    public function open($filename)
    {
        $this->pointer = @fopen($filename, 'rb');
        if ($this->pointer === false) {
            return false;
        }

        list(, $this->crc) = unpack('N', hash_file('crc32b', $filename, true));

        $fstat = fstat($this->pointer);
        $this->size = $fstat['size'];

        $mtime = $filename == 'php://temp' ? time() : $fstat['mtime'];
        $this->mtime = self::toFAT32Timestamp($mtime);
    }

    public function close()
    {
        fclose($this->pointer);
    }

    private static function toFAT32Timestamp($unixTimestamp)
    {
        list($y, $m, $d, $h, $i, $s) = explode('-', @date('Y-m-d-H-i-s', $unixTimestamp));
        return ($y - 1980) << 25 | $m << 21 | $d << 16
            | $h << 11 | $i << 5 | $s >> 1;
    }
}



<?php
require 'cla_directzip.php';
$zip = new DirectZip();
$zip->open('브라우저로 보낼 압축파일 이름.zip');
$zip->addFile('/tmp/추가할 파일.jpg', '압축파일 내 파일 이름.jpg');
$zip->addEmptyDir('압축파일 내 폴더 이름'); // 안 해도 상관없음.
$zip->addFile('/tmp/추가할 파일2.png', '압축파일 내 폴더 이름/압축파일 내 파일 이름.png');
$zip->addFile('/tmp/추가할 파일3.jpg'); // 압축파일에 파일을 '추가할 파일3.jpg'로 추가
$zip->addFromString('바로 글쓰기.txt', '파일 내용'); // 압축파일에 '파일 내용'을 '바로 글쓰기.txt'로 추가
$zip->close();

/*
브라우저로 보낼 압축파일 이름.zip
│  바로 글쓰기.txt
│  압축파일 내 파일 이름.jpg
│  추가할 파일3.jpg
│
└─압축파일 내 폴더 이름
        압축파일 내 파일 이름.png
*/



List of Articles
번호 제목 날짜 조회 수
140 DB 연동 4단 셀렉트 박스 2018.09.28 6127
139 이미지 땡겨와서 출력하기 2018.09.28 5314
138 자바스크립트 이스케이프 문자열을 PHP로 디코딩 하기 2018.10.27 3285
137 PHP 확장 모듈을 이용한 C 라이브러리 사용 2018.10.27 3816
136 PHP eregi가 빠를까, strpos가 빠를까? 2018.10.27 4122
135 PHP split()와 explode()의 차이점 2018.10.27 3549
134 PHP XML 문서파싱 (SAX 방식 , DOM 방식) file 2018.10.27 3603
133 PHP 랜덤 문자열 생성 2018.10.27 4137
132 PHP 소켓을 이용하여 URL의 응답결과를 문자열로 받기 2018.10.27 3525
131 PHP 랜덤확률 구하기 2018.10.27 4792
130 PHP 문자열에서 검색어를 기준으로 앞뒤로 일정 길이만큼 자르기 2018.10.27 3558
129 디렉토리의 제어 2019.01.08 1234
128 파일 2019.01.08 1233
127 include 와 namespace 2019.01.08 1114
126 배열을 테이블로 만들기 2019.01.08 1641
125 php에서 체크박스 선택한 것 보여주기 file 2019.01.08 1827
124 php/asp에서 가상번호 부여와 가상번호를 거꾸로 적용 2019.01.08 1436
123 디비내용을 엑셀 파일로 다운로드 시키는 방법 2019.01.08 1404
122 사업자번호로 사업자 종류알기 2019.01.08 1237
121 내 계정 용량 체크 2019.01.08 1613
Board Pagination Prev 1 ... 6 7 8 9 10 11 12 13 14 15 ... 17 Next
/ 17

하단 정보를 입력할 수 있습니다

© k2s0o1d4e0s2i1g5n. All Rights Reserved