Zip all files in directory php

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();

Источник

Читайте также:  Встроенные элементы

ZIP all files in directory and download generated .zip

Here is an example of how you can use PHP to create a ZIP archive of all files in a directory and then prompt the user to download the generated ZIP file:

 $dir = 'path/to/your/directory'; // Initialize archive object $zip = new ZipArchive(); $zip_name = time() . ".zip"; // Zip name $zip->open($zip_name, ZipArchive::CREATE); // Create recursive directory iterator /** @var SplFileInfo[] $files */ $files = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($dir), RecursiveIteratorIterator::LEAVES_ONLY); foreach ($files as $name => $file) < // Skip directories (they would be added automatically) if (!$file->isDir()) < // Get real and relative path for current file $filePath = $file->getRealPath(); $relativePath = substr($filePath, strlen($dir) + 1); // Add current file to archive $zip->addFile($filePath, $relativePath); > > // Zip archive will be created only after closing object $zip->close(); //then prompt user to download the zip file header('Content-Type: application/zip'); header('Content-disposition: attachment; filename=' . $zip_name); header('Content-Length: ' . filesize($zip_name)); readfile($zip_name); //cleanup the zip file unlink($zip_name); ?>

This script will create a ZIP archive of all files in the specified directory, and then prompt the user to download the generated ZIP file. It is also cleaning up the zip file after download is complete. Please make sure to update the path to the directory you want to compress.

Источник

How to create a zip file using PHP

Recently I had to write a script to create a zip file containing different files and folders. PHP has a ZipArchive class which can be used easily to create zip files. In this article we will see how to create zip files in PHP. We will create different zip files from different files and folders.

Create a new zip file

The following code will open a zip file test_new.zip and add a few files into it.

$zip = new ZipArchive; if ($zip->open('test_new.zip', ZipArchive::CREATE) === TRUE) < // Add files to the zip file $zip->addFile('test.txt'); $zip->addFile('test.pdf'); // Add random.txt file to zip and rename it to newfile.txt $zip->addFile('random.txt', 'newfile.txt'); // Add a file new.txt file to zip using the text specified $zip->addFromString('new.txt', 'text to be added to the new.txt file'); // All files are added, so close the zip file. $zip->close(); >
Explanation of code
  • Line 1 creates an object of the ZipArchive class
  • Line 2 opens a file with filename as test_new.zip so that we can add files to it. The flag ZipArchive::CREATE specifies that we want to create a new zip file
  • Lines 5 & 6 are used to add files to the zip file
  • Line 9 is used to add a file with name random.txt to the zip file and rename it in the zipfile as newfile.txt
  • Line 12 is used to add a new file new.txt with contents of the file as ‘text to be added to the new.txt file’
  • Line 15 closes and saves the changes to the zip file

Note: Sometimes there can be issues when using relative paths for files. If there are any issues using paths then we can also use absolute paths for files

Overwrite an existing zip file

If you want to overwrite an existing zip file then we can use code similar to following. The flag ZipArchive::OVERWRITE overwrites the existing zip file.

$zip = new ZipArchive; if ($zip->open('test_overwrite.zip', ZipArchive::OVERWRITE) === TRUE) < // Add file to the zip file $zip->addFile('test.txt'); $zip->addFile('test.pdf'); // All files are added, so close the zip file. $zip->close(); >
Explanation of code
  • This code will create a file test_overwrite.zip if it already exists the file will be overwritten with this new file

Create a new zip file and add files to be inside a folder

$zip = new ZipArchive; if ($zip->open('test_folder.zip', ZipArchive::CREATE) === TRUE) < // Add files to the zip file inside demo_folder $zip->addFile('text.txt', 'demo_folder/test.txt'); $zip->addFile('test.pdf', 'demo_folder/test.pdf'); // Add random.txt file to zip and rename it to newfile.txt and store in demo_folder $zip->addFile('random.txt', 'demo_folder/newfile.txt'); // Add a file demo_folder/new.txt file to zip using the text specified $zip->addFromString('demo_folder/new.txt', 'text to be added to the new.txt file'); // All files are added, so close the zip file. $zip->close(); >
Explanation of code
  • The above code will add different files inside the zip file to be inside a folder demo_folder
  • The 2nd parameter to addfile function can be used to store the file in a new folder
  • The 1st parameter in the addFromString function can be used to store the file in a new folder

Create a new zip file and move the files to be in different folders

$zip = new ZipArchive; if ($zip->open('test_folder_change.zip', ZipArchive::CREATE) === TRUE) < // Add files to the zip file $zip->addFile('text.txt', 'demo_folder/test.txt'); $zip->addFile('test.pdf', 'demo_folder1/test.pdf'); // All files are added, so close the zip file. $zip->close(); >
Explanation of code

Create a zip file with all files from a directory

$zip = new ZipArchive; if ($zip->open('test_dir.zip', ZipArchive::OVERWRITE) === TRUE) < if ($handle = opendir('demo_folder')) < // Add all files inside the directory while (false !== ($entry = readdir($handle))) < if ($entry != "." && $entry != ".." && !is_dir('demo_folder/' . $entry)) < $zip->addFile('demo_folder/' . $entry); > > closedir($handle); > $zip->close(); >
Explanation of code
  • Lines 5-16 opens a directory and creates a zip file with all files within that directory
  • Line 5 opens the directory
  • Line 7 gets the name of each file in the dir
  • Line 9 skips the “.” and “..” and any other directories
  • Line 11 adds the file into the zip file
  • Line 14 closes the directory
  • Line 17 closes the zip file

Add multiple files and directories to a zip file

The following code will add different folders and files in those directories into a zip file

$zip = new ZipArchive; if ($zip->open('test_files_dirs.zip', ZipArchive::OVERWRITE) === TRUE) < // Add directory1 if ($handle = opendir('demo_folder/directory1/')) < while (false !== ($entry = readdir($handle))) < if ($entry != "." && $entry != "..") < $zip->addFile('demo_folder/directory1/' . $entry); > > closedir($handle); > // Add directory2 if ($handle = opendir('demo_folder/directory2/')) < while (false !== ($entry = readdir($handle))) < if ($entry != "." && $entry != "..") < $zip->addFile('demo_folder/directory2/' . $entry); > > closedir($handle); > // Add directory3 if ($handle = opendir('demo_folder/directory3/')) < while (false !== ($entry = readdir($handle))) < if ($entry != "." && $entry != "..") < $zip->addFile('demo_folder/directory3/' . $entry); > > closedir($handle); > // Add more files $zip->addFile('demo_folder/index.txt'); $zip->close(); >
Explanation of code
  • Lines 5-41 adds all the files inside the directories 1,2 and 3 into the zip file inside the respective directories
  • Line 44 adds “index.txt” file to the zip file

Share this:

Источник

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