메뉴 건너뛰기

프로그램언어

조회 수 619 추천 수 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
번호 제목 날짜 조회 수
220 배열을 테이블로 만들기 2019.01.08 1625
219 공백문자 체크 2019.01.08 1625
218 이미지 사이즈 비율로 조정하기 2019.01.08 1631
217 php에서 체크박스 선택한 것 보여주기 file 2019.01.08 1807
216 dddotag - 허용하지 않는 태그 걸러내기 2019.01.16 1850
215 금액 단위를 만단위부터 표시하는방법 2019.01.16 1912
214 PHP 외부 XML 파싱 하기 2019.06.24 1944
213 메모장소스 2019.01.08 2000
212 PHP http 를 https 로 전환(redirect), http->https 2019.02.19 2183
211 날짜/시간함수 정리 2018.08.29 2429
210 PHP에서 자료, 데이터의 타입을 확인하는 방법, gettype() 2018.08.29 2465
209 PHP에서 모든 세션 정보를 화면에 출력하는 방법 2018.08.29 2694
208 자바스크립트 이스케이프 문자열을 PHP로 디코딩 하기 2018.10.27 3259
207 PHP 소켓을 이용하여 URL의 응답결과를 문자열로 받기 2018.10.27 3502
206 PHP split()와 explode()의 차이점 2018.10.27 3536
205 PHP 문자열에서 검색어를 기준으로 앞뒤로 일정 길이만큼 자르기 2018.10.27 3539
204 PHP에서의 대칭 암호화/복호화 ― 간단한 예제에서 DB 입/출력까지 2018.09.14 3548
203 PHP XML 문서파싱 (SAX 방식 , DOM 방식) file 2018.10.27 3585
202 PHP 확장 모듈을 이용한 C 라이브러리 사용 2018.10.27 3786
201 한글이 깨져서 나올 때 - iconv 2018.08.29 3933
Board Pagination Prev 1 2 3 4 5 6 7 8 9 10 11 ... 17 Next
/ 17

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

© k2s0o1d4e0s2i1g5n. All Rights Reserved