Page 1 of 1

create a file on the fly AND zip it on the fly

Posted: Wed Aug 05, 2009 2:29 pm
by php_blob
Hi, I'd like to create a file on the fly, and zip it on the fly for download.

I can do them separately:

Code: Select all

<?php
    //create file on the fly for download
    $filename = "filename.txt";
    header('Content-type: text/plain');
    header('Content-Disposition: attachment; filename="'.$filename.'"');
    echo 'file contents';
?>
and

Code: Select all

<?php
    require_once("zip.lib.php");
 
    $zip = new zipfile();
    $filename = "filename.txt";
    $fsize = @filesize($filename);
    $fh = fopen($filename, 'rb', false);
    $data = fread($fh, $fsize);
    $zip->addFile($data,$filename);
 
    $zipcontents = $zip->file();
 
    header("Content-type: application/octet-stream");
    header("Content-Disposition: attachment; filename=\"TheZip.zip\"");
    header("Content-length: " . strlen($zipcontents) . "\n\n");
 
    // output data
    echo $zipcontents;
?>
source: http://lt.php.net/manual/en/ref.zip.php

But I can't figure out how to create a file on the fly, and zip it on the fly for download. There seems to be heaps of stuff on the net for creating zip files on the fly, but nothing that does what I need.

Anyone got any ideas?

Re: create a file on the fly AND zip it on the fly

Posted: Wed Aug 05, 2009 3:14 pm
by redmonkey
You just need to replace $data with the contents of your 'on the fly' file, so combining you two examples would be....

Code: Select all

<?php
require_once("zip.lib.php");
 
$data = 'file contents';
 
$zip = new zipfile();
$filename = "filename.txt";
/*  no longer required
 *  $fsize = @filesize($filename);
 *  $fh = fopen($filename, 'rb', false);
 *  $data = fread($fh, $fsize);
 */
$zip->addFile($data,$filename);
 
$zipcontents = $zip->file();
 
header("Content-type: application/octet-stream");
header("Content-Disposition: attachment; filename=\"TheZip.zip\"");
header("Content-length: " . strlen($zipcontents) . "\n\n");
 
// output data
echo $zipcontents;
?>

Re: create a file on the fly AND zip it on the fly

Posted: Fri Aug 07, 2009 2:33 am
by php_blob
it works! :D
Thanks redmonkey. so simple and elegant the solution.