使用PHP处理内存中的存档(无需在磁盘上创建临时文件) [英] Manipulate an Archive in memory with PHP (without creating a temporary file on disk)
问题描述
我试图用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.
所以,问题是:
是否可以在不使用tempfile的方式创建和操作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
文件的链接:
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项目上也可用: >
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屋!