如何使用php将文件添加到zip,这些文件应该有一个GET参数

时间:2016-05-02 07:32:41

标签: php get zip ziparchive

我有一个文件gen.php这个文件应该有一些GET参数,例如:gen.php?oid=35852 打开此链接时:gen.php?oid=35852将使用一些php标题生成名为35852.txt的下载文件

现在我正在尝试使用php ZipArchive()将这些生成的文件添加到zip存档中,但它无法正常工作

$zip = new ZipArchive(); // Load zip library 
$zip_name = time().".zip"; // Zip name

if($zip->open($zip_name, ZIPARCHIVE::CREATE)!==TRUE){ 
   // Opening zip file to load files
   $error .= "* Sorry ZIP creation failed at this time";
}

//this file will not added
$zip->addFile('/../../ser/gen.php?oid=35851');
//this file will not added
$zip->addFile('../ser/gen.php?oid=35852');
//this file will added, but as you see it will be the PHP file
$zip->addFile('../ser/gen.php');
//this file will added as a sample file
$zip->addFile('../samples2/2.png');

$zip->close();

有没有办法将gen.php?oid=35851的结果文件添加到zip存档中?35851.txt

1 个答案:

答案 0 :(得分:0)

如果要将gen.php?oid=35852生成的内容下载到35852.txt文件中,然后在Zip中压缩下载的文件,则可以使用类似以下的代码。

$id = 35851;
$url = "http://yourdomain.com/gen.php?oid=$id";

$txt_name = "${id}.txt";
$zip_name = "${id}.zip";

$zip = new ZipArchive();

if ($zip->open($zip_name, ZipArchive::CREATE | ZipArchive::OVERWRITE) !== true) {
   die("Failed to create zip archive $zip_name");
}

if (! $text = file_get_contents($url)) {
  die("Failed to download $url");
}

if (false === file_put_contents($txt_name, $text)) {
  die("Failed to write to $txt_name");
}

if (! $zip->addFile($txt_name)) {
  unlink($txt_name);
  die("Failed to add $txt_name to $zip_name");
}

$zip->close();

unlink($txt_name);