使用 PHP 操作内存中的存档(无需在磁盘上创建临时文件) [英] Manipulate an Archive in memory with PHP (without creating a temporary file on disk)

查看:17
本文介绍了使用 PHP 操作内存中的存档(无需在磁盘上创建临时文件)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在 PHP 中即时生成存档并立即将其发送给用户(不保存).我认为没有必要在磁盘上创建文件,因为我发送的数据无论如何都不是持久的,但是,在搜索网络时,我无法找到方法.我也不关心文件格式.

I am trying to generate an archive on-the-fly in PHP and send it to the user immediately (without saving it). I figured that there would be no need to create a file on disk as the data I'm sending isn't persistent anyway, however, upon searching the web, I couldn't find out how. I also don't care about the file format.

所以,问题是:

是否可以在 php 脚本中创建和操作内存中的文件存档,而无需一路创建临时文件?

Is it possible to create and manipulate a file archive in memory within a php script without creating a tempfile along the way?

推荐答案

我遇到了同样的问题,但最终找到了一个有点晦涩的解决方案,并决定在这里分享.

I had the same problem but finally found a somewhat obscure solution and decided to share it here.

我遇到了 phpmyadmin 附带的很棒的 zip.lib.php/unzip.lib.php 脚本,它们位于图书馆"目录.

I came accross the great zip.lib.php/unzip.lib.php scripts which come with phpmyadmin and are located in the "libraries" directory.

使用 zip.lib.php 对我来说很有魅力:

Using zip.lib.php worked as a charm for me:

require_once(LIBS_DIR . 'zip.lib.php');

... 

//create the zip
$zip = new zipfile();

//add files to the zip, passing file contents, not actual files
$zip->addFile($file_content, $file_name);

...

//prepare the proper content type
header("Content-type: application/octet-stream");
header("Content-Disposition: attachment; filename=my_archive.zip");
header("Content-Description: Files of an applicant");

//get the zip content and send it back to the browser
echo $zip->file();

此脚本允许下载 zip,无需将文件作为真实文件或将 zip 本身另存为文件.

This script allows downloading of a zip, without the need of having the files as real files or saving the zip itself as a file.

遗憾的是,此功能不是更通用的 PHP 库的一部分.

It is a shame that this functionality is not part of a more generic PHP library.

这是来自 phpmyadmin 源代码的 zip.lib.php 文件的链接:https://github.com/phpmyadmin/phpmyadmin/blob/RELEASE_4_5_5_1/libraries/zip.lib.php

Here is a link to the zip.lib.php file from the phpmyadmin source: https://github.com/phpmyadmin/phpmyadmin/blob/RELEASE_4_5_5_1/libraries/zip.lib.php

更新:确保从 zip.lib.php 的开头删除以下检查,否则脚本将终止:

UPDATE: Make sure you remove the following check from the beginning of zip.lib.php as otherwise the script just terminates:

if (! defined('PHPMYADMIN')) {
    exit;
}

更新:此代码也可用于 CodeIgniter 项目:https://github.com/patricksavalle/CodeIgniter/blob/439ac3a87a440c3a87a440c3a87a440c3a87a440cae6help/helpers/zip_helper.php>

UPDATE: This code is available on the CodeIgniter project as well: https://github.com/patricksavalle/CodeIgniter/blob/439ac3a87a448ae6c2cbae0890c9f672efcae32d/system/helpers/zip_helper.php

这篇关于使用 PHP 操作内存中的存档(无需在磁盘上创建临时文件)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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