使用 php 压缩和下载文件 [英] zip and download files using php

查看:27
本文介绍了使用 php 压缩和下载文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从名为上传"的文件夹中压缩和下载文件.正在下载 Zip 文件,但我无法打开(提取)它.我收到类似存档格式未知或已损坏"之类的错误.

I am trying to zip and download files from a folder named "upload". Zip file is downloading but I couldn't open (extract) it. I am getting an error like "The archive is either in unknown format or damaged".

我找到了以下代码来压缩文件夹.

I have found the following code to zip the folder.

<?php
    $files = "upload/".array('Dear GP.docx','ecommerce.doc');
    $zipname = 'filename.zip';
    $zip = new ZipArchive;
    $zip->open($zipname, ZipArchive::CREATE);
    foreach ($files as $file) {
      $zip->addFile($file);
    }
    $zip->close();
    header('Content-Type: application/zip');
    header('Content-disposition: attachment; filename=filename.zip');
    header('Content-Length: ' . filesize($zipfilename));
    readfile($zipname);
?>

推荐答案

感谢您的回答.

<?php
    $files = array('Dear GP.docx','ecommerce.doc');

    # create new zip opbject
    $zip = new ZipArchive();

    # create a temp file & open it
    $tmp_file = tempnam('.','');
    $zip->open($tmp_file, ZipArchive::CREATE);

    # loop through each file
    foreach($files as $file){

        # download file
        $download_file = file_get_contents($file);

        #add it to the zip
        $zip->addFromString(basename($file),$download_file);

    }

    # close zip
    $zip->close();

    # send the file to the browser as a download
    header('Content-disposition: attachment; filename=Resumes.zip');
    header('Content-type: application/zip');
    readfile($tmp_file);
 ?>

这篇关于使用 php 压缩和下载文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆