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

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
php_blob
Forum Newbie
Posts: 2
Joined: Wed Aug 05, 2009 1:47 pm

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

Post 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?
redmonkey
Forum Regular
Posts: 836
Joined: Thu Dec 18, 2003 3:58 pm

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

Post 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;
?>
php_blob
Forum Newbie
Posts: 2
Joined: Wed Aug 05, 2009 1:47 pm

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

Post by php_blob »

it works! :D
Thanks redmonkey. so simple and elegant the solution.
Post Reply