目录类似于:

home/
    file1.html
    file2.html
Another_Dir/
    file8.html
    Sub_Dir/
        file19.html

我使用的是PHPMyAdminhttp://trac.seagullproject.org/browser/branches/0.6-bugfix/lib/other/Zip.php中使用的相同PHP Zip类.我不确定如何压缩目录,而不仅仅是压缩文件.以下是我目前掌握的情况:

$aFiles = $this->da->getDirTree($target);
/* $aFiles is something like, path => filetime
Array
(
    [home] => 
    [home/file1.html] => 1251280379
    [home/file2.html] => 1251280377
    etc...
)

*/
$zip = & new Zip();
foreach( $aFiles as $fileLocation => $time ){
    $file = $target . "/" . $fileLocation;
    if ( is_file($file) ){
        $buffer = file_get_contents($file);
        $zip->addFile($buffer, $fileLocation);
    }
}
THEN_SOME_PHP_CLASS::toDownloadData($zip); // this bit works ok

但是当我try 解压缩相应的下载zip文件时,我得到"不允许操作"

只有当我试图在mac上解压时,当我通过命令行解压文件解压时,才会发生此错误.我需要在下载时发送特定的内容类型吗,当前为"应用程序/zip"

推荐答案

下面是一个简单的函数,它可以递归地压缩任何文件或目录,只需要加载zip扩展名.

function Zip($source, $destination)
{
    if (!extension_loaded('zip') || !file_exists($source)) {
        return false;
    }

    $zip = new ZipArchive();
    if (!$zip->open($destination, ZIPARCHIVE::CREATE)) {
        return false;
    }

    $source = str_replace('\\', '/', realpath($source));

    if (is_dir($source) === true)
    {
        $files = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($source), RecursiveIteratorIterator::SELF_FIRST);

        foreach ($files as $file)
        {
            $file = str_replace('\\', '/', $file);

            // Ignore "." and ".." folders
            if( in_array(substr($file, strrpos($file, '/')+1), array('.', '..')) )
                continue;

            $file = realpath($file);

            if (is_dir($file) === true)
            {
                $zip->addEmptyDir(str_replace($source . '/', '', $file . '/'));
            }
            else if (is_file($file) === true)
            {
                $zip->addFromString(str_replace($source . '/', '', $file), file_get_contents($file));
            }
        }
    }
    else if (is_file($source) === true)
    {
        $zip->addFromString(basename($source), file_get_contents($source));
    }

    return $zip->close();
}

可以这样称呼:

Zip('/folder/to/compress/', './compressed.zip');

Php相关问答推荐

Woocommerce显示特定产品的自定义 checkout 字段

如何使用Ubuntu在同一台服务器上为多个版本构建相同的php扩展?

WooCommerce拆分运输包裹上的商品数量增加运输成本

累加平面数组中数字子集的所有组合,以生成组合及其乘积的二维数组

在函数内部获取一致的单选按钮值以更新WordPress用户数据

在Laravel Eloquent中实现一对多关系

在PHP中,如何将介于0和1之间(包括0和1)的浮点概率转换为数组索引?

在laravel 9或10 php中向中间件响应添加自定义数据

如何使用定制的StateProvider设置JsonLd@上下文?

PHP:为什么递归需要这么长时间

PHP SimpleXML:按属性值访问 node

无法在Laravel中将日志(log)通道设置为空

是否有条件判断是否发布了另一个Wordpress页面?

HTTPPost请求在从php脚本调用时返回404,但在从node.js脚本调用时有效.终结点有效

如何解决 Laravel 外键错误?

在 WooCommerce 中应用优惠券时显示购物车商品折扣金额

用自定义代码替换 WooCommerce 单一产品简短描述

通过添加计数器修改文本区域表单中的重复值

ACF 更新字段功能不更新 WordPress 中的任何数据

我正在使用 Baryryvdh/laravel-snappy 从 HTML 导出 PDF 它正在工作但缩小了 pdf 文件