开发者

php recursive zip?

Currently FTP is insanely slow on our server when it comes to multiple small files.

I am wanting to create a file that I can run in my browser that creates a zip file.

Basically this file will sit in /htdocs

The zip file it creates must take all files in /htdocss (and sub folders ect) and mimic the structure.

Can anyone point me in the right direction?

I am attempting to use the below code.

The only issue is that, I am getting s开发者_如何学JAVAome blank folders

say the file is:

C:/xampp/htdocs/booking/zip.php

I get /C

/C/xampp

/C/xampp/htdocs

/C/xampp/htdocs/booking

/C/xampp/htdocs/booking/image.png

/C/xampp/htdocs/booking/index.php

I dont want /C/xampp/htdocs/booking

I just want the zip file to contain image.png index.php

How can I fix this?

<?php

function Zip($source, $destination) {
  if(extension_loaded('zip') === true) {
    if(file_exists($source) === true) {
      $zip = new ZipArchive();

      if($zip->open($destination, ZIPARCHIVE::CREATE) === true) {
        $source = realpath($source);

        if(is_dir($source) === true) {
          $files = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($source), RecursiveIteratorIterator::SELF_FIRST);

          foreach($files as $file) {
            $file = realpath($file);

            if(is_dir($file) === true) {
              $zip->addEmptyDir(str_replace($source . '/', '', $file . '/'));
            } else if(is_file($file) === true) {
              $zip->addFromString(str_replace($source . '/', '', $file), file_get_contents($file));
            }
          }
        } else if(is_file($source) === true) {
          $zip->addFromString(basename($source), file_get_contents($source));
        }
      }

      return $zip->close();
    }
  }

  return false;
}

Zip(dirname(__FILE__), 'testzip.zip');
?>


There are two options. You can use PHPs built-in ZipArchive and manually iterate over the directory contents (readdir or DirectoryIterator).

Or you can do the lazy thing:

header("Content-Type: archive/zip");   // mime 2.0
header("Content-Disposition: attachment; filename=dir.zip");
passthru("zip -q -r - .");

Depends on the installed zip tool. It complains if you try that on the terminal, but should work over the passthru pipe.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜