search
HomeBackend DevelopmentPHP TutorialHow to package zip image download in php

How to package zip image download in php

Jul 05, 2018 pm 03:34 PM
zipImage download

这篇文章主要介绍了关于php打包zip图片下载的方法,有着一定的参考价值,现在分享给大家,有需要的朋友可以参考一下

1.引入类包 zipfile

class zipfile {
    var $datasec = array ();
    var $ctrl_dir = array ();
    var $eof_ctrl_dir = "\x50\x4b\x05\x06\x00\x00\x00\x00";
    var $old_offset = 0;
    
    function unix2_dostime($unixtime = 0){
        $timearray = ($unixtime == 0) ? getdate () : getdate($unixtime);        
        if ($timearray [&#39;year&#39;] < 1980){
            $timearray [&#39;year&#39;] = 1980;
            $timearray [&#39;mon&#39;] = 1;
            $timearray [&#39;mday&#39;] = 1;
            $timearray [&#39;hours&#39;] = 0;
            $timearray [&#39;minutes&#39;] = 0;
            $timearray [&#39;seconds&#39;] = 0;
        }
        return (($timearray [&#39;year&#39;] - 1980) << 25) | ($timearray [&#39;mon&#39;] << 21) | ($timearray [&#39;mday&#39;] << 16) | ($timearray [&#39;hours&#39;] << 11) | ($timearray [&#39;minutes&#39;] << 5) | ($timearray [&#39;seconds&#39;] >> 1);
    }
    function add_file($data, $name, $time = 0){
        $name = str_replace(&#39;\\&#39;, &#39;/&#39;, $name);
        
        $dtime = dechex($this->unix2_dostime($time));
        $hexdtime = &#39;\x&#39; . $dtime [6] . $dtime [7] . &#39;\x&#39; . $dtime [4] . $dtime [5] . &#39;\x&#39; . $dtime [2] . $dtime [3] . &#39;\x&#39; . $dtime [0] . $dtime [1];
        eval(&#39;$hexdtime = "&#39; . $hexdtime . &#39;";&#39;);
        
        $fr = "\x50\x4b\x03\x04";
        $fr .= "\x14\x00";
        $fr .= "\x00\x00";
        $fr .= "\x08\x00";
        $fr .= $hexdtime;
        
        $unc_len = strlen($data);
        $crc = crc32($data);
        $zdata = gzcompress($data);
        $zdata = substr(substr($zdata, 0, strlen($zdata)- 4), 2);
        $c_len = strlen($zdata);
        $fr .= pack(&#39;V&#39;, $crc);
        $fr .= pack(&#39;V&#39;, $c_len);
        $fr .= pack(&#39;V&#39;, $unc_len);
        $fr .= pack(&#39;v&#39;, strlen($name));
        $fr .= pack(&#39;v&#39;, 0);
        $fr .= $name;
        
        $fr .= $zdata;
        $fr .= pack(&#39;V&#39;, $crc);
        $fr .= pack(&#39;V&#39;, $c_len);
        $fr .= pack(&#39;V&#39;, $unc_len);
        
        $this->datasec [] = $fr;
        
        $cdrec = "\x50\x4b\x01\x02";
        $cdrec .= "\x00\x00";
        $cdrec .= "\x14\x00";
        $cdrec .= "\x00\x00";
        $cdrec .= "\x08\x00";
        $cdrec .= $hexdtime;
        $cdrec .= pack(&#39;V&#39;, $crc);
        $cdrec .= pack(&#39;V&#39;, $c_len);
        $cdrec .= pack(&#39;V&#39;, $unc_len);
        $cdrec .= pack(&#39;v&#39;, strlen($name));
        $cdrec .= pack(&#39;v&#39;, 0);
        $cdrec .= pack(&#39;v&#39;, 0);
        $cdrec .= pack(&#39;v&#39;, 0);
        $cdrec .= pack(&#39;v&#39;, 0);
        $cdrec .= pack(&#39;V&#39;, 32);
        
        $cdrec .= pack(&#39;V&#39;, $this->old_offset);
        $this->old_offset += strlen($fr);
        
        $cdrec .= $name;
        
        $this->ctrl_dir[] = $cdrec;
    }
    function add_path($path, $l = 0){
        $d = @opendir($path);
        $l = $l > 0 ? $l : strlen($path) + 1;
        while($v = @readdir($d)){
            if($v == &#39;.&#39; || $v == &#39;..&#39;){
                continue;
            }
            $v = $path . &#39;/&#39; . $v;
            if(is_dir($v)){
                $this->add_path($v, $l);
            } else {
                $this->add_file(file_get_contents($v), substr($v, $l));
            }
        }
    }
    function file(){
        $data = implode(&#39;&#39;, $this->datasec);
        $ctrldir = implode(&#39;&#39;, $this->ctrl_dir);
        return $data . $ctrldir . $this->eof_ctrl_dir . pack(&#39;v&#39;, sizeof($this->ctrl_dir)) . pack(&#39;v&#39;, sizeof($this->ctrl_dir)) . pack(&#39;V&#39;, strlen($ctrldir)) . pack(&#39;V&#39;, strlen($data)) . "\x00\x00";
    }
    
    function add_files($files){
        foreach($files as $file){
            if (is_file($file)){
                $data = implode("", file($file));
                $this->add_file($data, $file);
            }
        }
    }
    function output($file){
        $fp = fopen($file, "w");
        fwrite($fp, $this->file ());
        fclose($fp);
    }
}

2.实例

$dfile =  tempnam(&#39;/tmp&#39;, &#39;tmp&#39;);//产生一个临时文件,用于缓存下载文件
$zip = new \Org\Util\Zipfile();
//----------------------
$filename = &#39;二维码&#39;.date("Y-m-d H:i",time()).&#39;.zip&#39;; //下载的默认文件名
//以下是需要下载的图片数组信息,将需要下载的图片信息转化为类似即可
$params[&#39;ids&#39;] = explode(&#39;,&#39;,$params[&#39;ids&#39;]);

//获取图片
$image = array(
     array(&#39;image_src&#39; => &#39;pic1.jpg&#39;, &#39;image_name&#39; => &#39;图片1.jpg&#39;),
     array(&#39;image_src&#39; => &#39;pic2.jpg&#39;, &#39;image_name&#39; => &#39;pic/图片2.jpg&#39;),
);

foreach($image as $v){
    $zip->add_file(file_get_contents($v[&#39;image_src&#39;]),  $v[&#39;image_name&#39;]);
    // 添加打包的图片,第一个参数是图片内容,第二个参数是压缩包里面的显示的名称, 可包含路径
    // 或是想打包整个目录 用 $zip->add_path($image_path);
}
//----------------------
$zip->output($dfile);

// 下载文件
ob_clean();
header(&#39;Pragma: public&#39;);
header(&#39;Last-Modified:&#39;.gmdate(&#39;D, d M Y H:i:s&#39;) . &#39;GMT&#39;);
header(&#39;Cache-Control:no-store, no-cache, must-revalidate&#39;);
header(&#39;Cache-Control:pre-check=0, post-check=0, max-age=0&#39;);
header(&#39;Content-Transfer-Encoding:binary&#39;);
header(&#39;Content-Encoding:none&#39;);
header(&#39;Content-type:multipart/form-data&#39;);
header(&#39;Content-Disposition:attachment; filename="&#39;.$filename.&#39;"&#39;); //设置下载的默认文件名
header(&#39;Content-length:&#39;. filesize($dfile));
$fp = fopen($dfile, &#39;r&#39;);
while(connection_status() == 0 && $buf = @fread($fp, 8192)){
    echo $buf;
}
fclose($fp);
@unlink($dfile);
@flush();
@ob_flush();
exit();

值得一提的是 打包下载时中文文件夹或中文名出现乱码时可用下面方法解决

$name = iconv(&#39;utf-8&#39;,&#39;gb2312&#39;,$name);

以上就是本文的全部内容,希望对大家的学习有所帮助,更多相关内容请关注PHP中文网!

相关推荐:

php web请求安全处理

php cocket的使用方法

The above is the detailed content of How to package zip image download in php. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Explain the concept of a PHP session in simple terms.Explain the concept of a PHP session in simple terms.Apr 26, 2025 am 12:09 AM

PHPsessionstrackuserdataacrossmultiplepagerequestsusingauniqueIDstoredinacookie.Here'showtomanagethemeffectively:1)Startasessionwithsession_start()andstoredatain$_SESSION.2)RegeneratethesessionIDafterloginwithsession_regenerate_id(true)topreventsessi

How do you loop through all the values stored in a PHP session?How do you loop through all the values stored in a PHP session?Apr 26, 2025 am 12:06 AM

In PHP, iterating through session data can be achieved through the following steps: 1. Start the session using session_start(). 2. Iterate through foreach loop through all key-value pairs in the $_SESSION array. 3. When processing complex data structures, use is_array() or is_object() functions and use print_r() to output detailed information. 4. When optimizing traversal, paging can be used to avoid processing large amounts of data at one time. This will help you manage and use PHP session data more efficiently in your actual project.

Explain how to use sessions for user authentication.Explain how to use sessions for user authentication.Apr 26, 2025 am 12:04 AM

The session realizes user authentication through the server-side state management mechanism. 1) Session creation and generation of unique IDs, 2) IDs are passed through cookies, 3) Server stores and accesses session data through IDs, 4) User authentication and status management are realized, improving application security and user experience.

Give an example of how to store a user's name in a PHP session.Give an example of how to store a user's name in a PHP session.Apr 26, 2025 am 12:03 AM

Tostoreauser'snameinaPHPsession,startthesessionwithsession_start(),thenassignthenameto$_SESSION['username'].1)Usesession_start()toinitializethesession.2)Assigntheuser'snameto$_SESSION['username'].Thisallowsyoutoaccessthenameacrossmultiplepages,enhanc

What are some common problems that can cause PHP sessions to fail?What are some common problems that can cause PHP sessions to fail?Apr 25, 2025 am 12:16 AM

Reasons for PHPSession failure include configuration errors, cookie issues, and session expiration. 1. Configuration error: Check and set the correct session.save_path. 2.Cookie problem: Make sure the cookie is set correctly. 3.Session expires: Adjust session.gc_maxlifetime value to extend session time.

How do you debug session-related issues in PHP?How do you debug session-related issues in PHP?Apr 25, 2025 am 12:12 AM

Methods to debug session problems in PHP include: 1. Check whether the session is started correctly; 2. Verify the delivery of the session ID; 3. Check the storage and reading of session data; 4. Check the server configuration. By outputting session ID and data, viewing session file content, etc., you can effectively diagnose and solve session-related problems.

What happens if session_start() is called multiple times?What happens if session_start() is called multiple times?Apr 25, 2025 am 12:06 AM

Multiple calls to session_start() will result in warning messages and possible data overwrites. 1) PHP will issue a warning, prompting that the session has been started. 2) It may cause unexpected overwriting of session data. 3) Use session_status() to check the session status to avoid repeated calls.

How do you configure the session lifetime in PHP?How do you configure the session lifetime in PHP?Apr 25, 2025 am 12:05 AM

Configuring the session lifecycle in PHP can be achieved by setting session.gc_maxlifetime and session.cookie_lifetime. 1) session.gc_maxlifetime controls the survival time of server-side session data, 2) session.cookie_lifetime controls the life cycle of client cookies. When set to 0, the cookie expires when the browser is closed.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor