1

I'm searching for a solution that compresses uploaded files. I found a piece of code that helps gzip a single file (here). In case of multiple files, as far as I know, we firstly need to tar those files before gzipping them.

How could I do this with PHP?

Community
  • 1
  • 1
Lewis
  • 14,132
  • 12
  • 66
  • 87

2 Answers2

1

In PHP 5.3+ you can use the PharData class to create the tar:

// list of file paths to add
$files = glob('/docs/*.pdf');

$tar = new PharData(__DIR__ . '/myfiles.tar');

foreach ($files as $f) {
    $tar->addFile($f, basename($f));
}

If the tar isn't very large (or you have a lot of RAM), you can then compress with:

$tar->compress(Phar::GZ);

For large files, which could throw a memory limit error with the above method, one alternative is:

// you might want to adjust the time limit
set_time_limit(0);

$source = fopen($pathToTar, 'rb');
$target = __DIR__ . '/myfiles.tar.gz';
$destination = fopen('compress.zlib://' . $target, 'wb');
stream_copy_to_stream($source, $destination);

Reference: http://www.binarytides.com/how-to-create-tar-archives-in-php/

Vinicius Braz Pinto
  • 8,209
  • 3
  • 42
  • 60
0

Here is code for uploading zip file.

<?php

if(isset($_POST['btnsubmitzip'])){

$file=  $_FILES['txt_zip']['name'];

        $image_path = "../images/zip/".$file;

         $copy= copy($_FILES['txt_zip']['tmp_name'] ,$image_path);

            if($copy)
            {
             $message="Your Images successfully uploaded";
            }
            else
            {
              $message="Error in Image Uploading";
            }

            $zip = zip_open($image_path);

            if ($zip) {
              while ($zip_entry = zip_read($zip)) {
                $fp = fopen(DIR_FS_CATALOG."/images/".zip_entry_name($zip_entry), "w");
                if (zip_entry_open($zip, $zip_entry, "r")) {
                  $buf = zip_entry_read($zip_entry, zip_entry_filesize($zip_entry));
                  fwrite($fp,"$buf");
                  zip_entry_close($zip_entry);
                  fclose($fp);
                }
              }
              zip_close($zip);
            }
}

?>

        <form action="" name="frm" method="post" enctype="multipart/form-data">
          <table>
              <tr>
                <td style="padding-top:30px;">Import Images Zip File &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
                <input type="file" name="txt_zip" size="40"/>
                (size 300 x 300)
                </td>
            </tr>
          <tr><td style="padding-left:30px " class="smallText"><font color="#990000"><strong><?php echo $message; ?></strong></font></td></tr>

          <tr><td style="padding:20px;"><input type="submit" name="btnsubmitzip" value="Submit"></td></tr>
          </table>
        </form>
Hanif
  • 7
  • 1