Untitled Document

ZIP в PHP (ZipArchive)

Класс ZipArchive позволяет быстро и удобно работать с ZIP-архивам, рассмотрим основные возможности класса.

Добавление файлов в архив

В примере используются константы:

  • ZipArchive::CREATE – создавать архив, если он не существует
  • ZipArchive::OVERWRITE – если архив существует, то игнорировать текущее его содержимое т.е. работать как с пустым архивом.
$zip = new ZipArchive(); $zip->open(__DIR__ . '/archive.zip', ZipArchive::CREATE|ZipArchive::OVERWRITE); $zip->addFile(__DIR__ . '/image1.jpg', 'image1.jpg'); $zip->addFile(__DIR__ . '/image2.jpg', 'image2.jpg'); $zip->close();

Если файл необходимо поместить в директорию, то предварительно не нужно создавать пустую папку. Можно просто указать путь и имя файла, например «src»:

$zip->addFile(__DIR__ . '/image1.jpg', 'src/image1.jpg'); $zip->addFile(__DIR__ . '/image2.jpg', 'src/image2.jpg');

Если текстовой файл генерится прямо в скрипте, то удобней скинуть его в архив методом addFromString() .

$contents = 'Содержание файла file.log'; $zip = new ZipArchive(); $zip->open(__DIR__ . '/archive.zip', ZipArchive::CREATE|ZipArchive::OVERWRITE); $zip->addFromString('file.log', $contents); $zip->close();

Заархивировать директорию с содержимым

Сделать архив сайта можно с помощью рекурсивной функции, функция обойдет все файлы в директориях и добавит их в архив.

function addFileRecursion($zip, $dir, $start = '') < if (empty($start)) < $start = $dir; >if ($objs = glob($dir . '/*')) < foreach($objs as $obj) < if (is_dir($obj)) < addFileRecursion($zip, $obj, $start); >else < $zip->addFile($obj, str_replace(dirname($start) . '/', '', $obj)); > > > > $zip = new ZipArchive(); $zip->open(__DIR__ . '/archive.zip', ZipArchive::CREATE|ZipArchive::OVERWRITE); addFileRecursion($zip, __DIR__ . '/test'); $zip->close();

Переименовать файл

$zip = new ZipArchive(); $zip->open(__DIR__ . '/archive.zip'); $zip->renameName('image2.jpg', 'images.jpg'); $zip->close();

Если файл лежит в папке

$zip->renameName('src/image2.jpg', 'src/images.jpg');

Удалить файл из архива

$zip = new ZipArchive(); $zip->open(__DIR__ . '/archive.zip'); $zip->deleteName('image2.jpg'); $zip->close();

Если файл лежит в папке

$zip->deleteName('src/image2.jpg');

Список файлов в архиве

$zip = new ZipArchive(); $zip->open(__DIR__ . '/archive.zip'); $i = 0; $list = array(); while($name = $zip->getNameIndex($i)) < $list[$i] = $name; $i++; >print_r($list); $zip->close();
Array ( [0] => src/image1.jpg [1] => src/image2.jpg [2] => file.log )

Извлечь весь архив

$zip = new ZipArchive(); $zip->open(__DIR__ . '/archive.zip'); $zip->extractTo(__DIR__); $zip->close();

Извлечь определенные файлы

$zip = new ZipArchive(); $zip->open(__DIR__ . '/archive.zip'); $zip->extractTo(__DIR__, array('src/image1.jpg', 'src/image2.jpg')); $zip->close();

Извлечь файл в поток

Данный метод удобен если требуется только прочитать содержимое файла.

$zip = new ZipArchive(); $zip->open(__DIR__ . '/archive.zip'); $contents = ''; $fp = $zip->getStream('file.log'); while (!feof($fp)) < $contents .= fread($fp, 2); >fclose($fp); echo $contents; $zip->close();

Источник

Читайте также:  Поток ввода вывода python

How to Create Zip Files using PHP ZipArchive and Download

Creating a zip from a folder full of files can be done in PHP using the ZipArchive class. This class instance creates a handle to read or write files to a compressed archive.

This class includes several properties and methods to zip file archives.

In this article, we will see an example of,

If you want to know how to compress more than one image in PHP image compression refer to this earlier article.

How to create a zip archive file

This file parses the input directory and compresses its files into a zip file. It proceeds with the following steps to create the zip file of a directory.

  1. Create a PHP ZipArchive class instance.
  2. Open a zip file archive with the instance. It accepts the output zip file name and the mode to open the archive.
  3. Apply a recursive parsing in the input directory.
  4. If the directory includes a file, then it adds to the zip archive using addFile().

It handles the use cases of getting the possibilities of being unable to read or archive the directory. Once the zip is created, it displays a message to the browser.

open($zipFile, ZipArchive::CREATE) !== TRUE) < exit("Unable to open file."); >$folder = 'example-folder/'; createZip($zipArchive, $folder); $zipArchive->close(); echo 'Zip file created.'; function createZip($zipArchive, $folder) < if (is_dir($folder)) < if ($f = opendir($folder)) < while (($file = readdir($f)) !== false) < if (is_file($folder . $file)) < if ($file != '' && $file != '.' && $file != '..') < $zipArchive->addFile($folder . $file); > > else < if (is_dir($folder . $file)) < if ($file != '' && $file != '.' && $file != '..') < $zipArchive->addEmptyDir($folder . $file); $folder = $folder . $file . '/'; createZip($zipArchive, $folder); > > > > closedir($f); > else < exit("Unable to open directory " . $folder); >> else < exit($folder . " is not a directory."); >> ?> 

Output

//If succeeded it returns Zip file created. //If failed it returns Unable to open directory example-folder. [or] "example-folder is not a director. 

php create zip

How to download the compressed zip file

In the last step, the zip file is created using the PHP ZipArchive class. That zip file can be downloaded by using the PHP code below.

It follows the below steps to download the zip file created.

  1. Get the absolute path of the zip file.
  2. Set the header parameters like,
    • Content length.
    • Content type.
    • Content encoding, and more.

This file just has the links to trigger the function to create a zip file containing the compressed archive of the directory. Then, the action to download the output zip archive is called.

 

Create and Download Zip file using PHP

Create Zip File

Download Zip File

Some methods of PHP ZipArchive class

We can do more operations by using the methods and properties of the PHP ZipArchive class. This list of methods is provided by this PHP class.

  1. count() – used to get the number of files in the zip archive file.
  2. extractTo() – extracts the archive content.
  3. renameIndex() – rename a particular archive entry by index.
  4. replaceFile() – replace a file in the zip archive with a new file by specifying a new path.

ZipArchive methods used in this example

Some of the methods are used in this example listed below. These are frequently used methods of this class to work with this.

  1. open() – Open a zip archive file by specifying the .zip file name.
  2. addFile() – To add a file from the input directory to the zip archive.
  3. addEmptyDir() – adds an empty directory into the archive to load the subdirectory file of the input directory.
  4. close() – closes the active ZipArchive with the reference of the handle.

Leave a Reply Cancel reply

Источник

How to Upload and Unpack a Zip File using PHP

When you’re emailing or uploading larger files, it always makes sense to compress them first. This decreases file size and also helps avoid file corruption during transfer. The most common compressed file you will encounter is the zip file, since most operating systems come with a basic utility to quickly zip and unzip files. Creating a small function to upload a zip file to your server and unpack in the process isn’t as complicated as you might think.

First let’s create a simple form that will allow us to browse our computer and upload a zip file.

 

Now comes the uploader function:

 > $continue = strtolower($name[1]) == 'zip' ? true : false; if(!$continue) < $message = "The file you are trying to upload is not a .zip file. Please try again."; >$target_path = "/home/var/yoursite/httpdocs/".$filename; // change this to the correct site path if(move_uploaded_file($source, $target_path)) < $zip = new ZipArchive(); $x = $zip->open($target_path); if ($x === true) < $zip->extractTo("/home/var/yoursite/httpdocs/"); // change this to the correct site path $zip->close(); unlink($target_path); > $message = "Your .zip file was uploaded and unpacked."; > else < $message = "There was a problem with the upload. Please try again."; >> ?>

To make sure the success and error messages appear, we will also have to add to short pieces of PHP code:

Putting it all together into a PHP file would look like this:

 > $continue = strtolower($name[1]) == 'zip' ? true : false; if(!$continue) < $message = "The file you are trying to upload is not a .zip file. Please try again."; >$target_path = "/home/var/yoursite/httpdocs/".$filename; // change this to the correct site path if(move_uploaded_file($source, $target_path)) < $zip = new ZipArchive(); $x = $zip->open($target_path); if ($x === true) < $zip->extractTo("/home/var/yoursite/httpdocs/"); // change this to the correct site path $zip->close(); unlink($target_path); > $message = "Your .zip file was uploaded and unpacked."; > else < $message = "There was a problem with the upload. Please try again."; >> ?>      $message

"; ?>

Источник

Оцените статью