Php add file to zip

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

Источник

Читайте также:  Advanced online html editor

Add Files & Folders In PHP ZIP (Basics, Entire Folder, Recursive)

Welcome to a quick tutorial on how to add files and folders with PHP Zip. So you have a project that needs some zip archive action, and no idea where to start?

We can add files and folders to a zip file in PHP using the ZipArchive extension:

  • $zip = new ZipArchive();
  • $zip->open(«archive.zip», ZipArchive::CREATE);
  • $zip->addFile(«target.file», «name-in-zip.file»);
  • $zip->addEmptyDir(«folder»);
  • $zip->close();

That should cover the basics, but adding entire folders is a different story – Read on for more examples!

TLDR – QUICK SLIDES

How To Add Files Folders In PHP ZIP

TABLE OF CONTENTS

HOW TO ADD FILES & FOLDERS WITH PHP ZIP

All right, let us now get into the examples of the various ways to add files and folders into a zip archive in PHP.

1) BASICS – ADDING FILES & FOLDERS

open($zipfile, ZipArchive::CREATE) === true) < // (B1) ADD FILE echo $zip->addFile("readme.txt", "filename-in-zip.txt") ? "File added to zip archive" : "Error adding file to zip archive" ; // (B2) ADD FOLDER echo $zip->addEmptyDir("folder") ? "Folder added to zip archive" : "Error adding folder to zip archive" ; // (B3) CLOSE ZIP echo $zip->close() ? "Zip archive closed" : "Error closing zip archive" ; > // (C) FAILED TO OPEN/CREATE ZIP FILE else < echo "Failed to open/create $zipfile"; >

Yes, this is kind of an “expanded version” of the introduction – We start by creating a $zip = new ZipArchive() object, then there are only 4 basic zip functions that you should know.

  • open(FILE, MODE) This opens a zip file, but take extra note of the possible modes:
    • ZipArchive::CREATE – Creates a new zip archive if not found.
    • ZipArchive::OVERWRITE – Overwrite if there is an existing zip archive.
    • ZipArchive::EXCL – The safer way, which will return an error if there is an existing zip archive.
    • ZipArchive::RDONLY – Readonly.
    • ZipArchive::CHECKONS – Checks the zip archive, throws an error if the checksum fails.

    2) APPENDING FILES INTO A FOLDER IN THE ZIP ARCHIVE

    open($zipfile, ZipArchive::CREATE) === true) < // (B) APPEND FILE INTO ZIP echo $zip->addFile("1-basic.php", "1-basic.php") ? "File added to zip archive" : "Error adding file to zip archive" ; // (C) ADD FILE INTO FOLDER IN ZIP echo $zip->addFile("2-append.php", "folder/2-append.php") ? "File added to zip archive" : "Error adding file to zip archive" ; // (D) CLOSE ZIP echo $zip->close() ? "Zip archive closed" : "Error closing zip archive" ; > // (E) FAILED TO OPEN/CREATE ZIP FILE else < echo "Failed to open/create $zipfile"; >

    To append more files into an existing zip archive, we simply open it again and use the addFile() function; To add the file into a folder within the zip archive, we only have to specify it accordingly – addFile(TARGET.FILE, FOLDER-IN-ZIP/SAVE.FILE) .

    3) FROM STRING TO ZIP FILE

    open($zipfile, ZipArchive::CREATE) === true) < // (B) ADD FROM STRING echo $zip->addFromString("string.txt", "This is a string!") ? "File added to zip archive" : "Error adding file to zip archive" ; > // (C) FAILED TO OPEN/CREATE ZIP FILE else < echo "Failed to open/create $zipfile"; >

    Just a convenience for you guys who want to archive logs or any content – Use the addFromString() function to save a string into a zip file.

    4) ADD ENTIRE FOLDER INTO ZIP ARCHIVE (USING GLOB)

    open($zipfile, ZipArchive::CREATE) === true) < // (B1) ADD ENTIRE FOLDER // add all jpg png gif files in "/test/" into the "inside/" folder of the zip archive echo $zip->addGlob($tozip . "*.", GLOB_BRACE, [ "add_path" => "inside/", "remove_all_path" => true ]) ? "Folder added to zip" : "Error adding folder to zip" ; // (B2) CLOSE ZIP echo $zip->close() ? "Zip archive closed" : "Error closing zip archive" ; > // (C) FAILED TO OPEN/CREATE ZIP FILE else < echo "Failed to open/create $zipfile"; >

    PHP comes with a very handy glob() function to filter out files/folders in the system. There is also a addGlob() function that we can use in the zip archive – To add an entire folder or filter out certain file extensions only.

    Take note though – This will not “dig” into the sub-folders of the specified target folder.

    5) ADD ENTIRE FOLDER INTO ZIP ARCHIVE (USING PATTERN)

    open($zipfile, ZipArchive::CREATE) === true) < // (B1) ADD ENTIRE FOLDER // add all php txt files in "/test/" into the "inside/" folder of the zip archive echo $zip->addPattern("/\.(?:php|txt)$/", $tozip, [ "add_path" => "inside/", "remove_all_path" => true ]) ? "Folder added to zip" : "Error adding folder to zip" ; // (B2) CLOSE ZIP echo $zip->close() ? "Zip archive closed" : "Error closing zip archive" ; > // (C) FAILED TO OPEN/CREATE ZIP FILE else < echo "Failed to open/create $zipfile"; >

    This is an alternative to addGlob() , addPattern() uses the “standard regular expression” to filter out files. But take note again, this will not drill into the sub-folders.

    6) RECURSIVELY ADD FOLDER AND SUB-FOLDERS

    open($zipfile, ZipArchive::OVERWRITE | ZipArchive::CREATE) === true) < // (B1) RECURSIVE ADD function zipall ($folder, $base, $ziparchive) < // FOLDER NAME INSIDE ZIP $options = ["remove_all_path" =>true]; if ($folder != $base) < $options["add_path"] = substr($folder, strlen($base)); >// ADD CURRENT FOLDER TO ZIP ARCHIVE echo $ziparchive->addGlob($folder."*.", GLOB_BRACE, $options) ? "Folder added to zip" : "Error adding folder to zip" ; // ADD FOLDERS IN FOLDER $folders = glob($folder . "*", GLOB_ONLYDIR); if (count($folders)!=0) < foreach ($folders as $f) < zipall($f."/", $base, $ziparchive); >> > zipall($tozip, $tozip, $zip); // (B2) CLOSE ZIP echo $zip->close() ? "Zip archive closed" : "Error closing zip archive" ; > // (C) FAILED TO OPEN/CREATE ZIP FILE else < echo "Failed to open/create $zipfile"; >

    Finally, this is sadly the way to zip an entire folder, along with the sub-folders inside… Not going to explain this line-by-line, but essentially, use a recursive function to drill into the sub-folders themselves.

    DOWNLOAD & NOTES

    Here is the download link to the example code, so you don’t have to copy-paste everything.

    SUPPORT

    600+ free tutorials & projects on Code Boxx and still growing. I insist on not turning Code Boxx into a «paid scripts and courses» business, so every little bit of support helps.

    EXAMPLE CODE DOWNLOAD

    Click here for the source code on GitHub gist, just click on “download zip” or do a git clone. I have released it under the MIT license, so feel free to build on top of it or use it in your own project.

    That’s it for all the example code, and here is a summary of all the zip functions.

    THE ZIP FUNCTIONS AT A GLANCE

    TUTORIAL VIDEO

    INFOGRAPHIC CHEAT SHEET

    THE END

    Thank you for reading, and we have come to the end of the tutorial. I hope that it has helped you to better understand zip in PHP, and if you have anything to share with this guide, please feel free to comment below. Good luck and happy coding!

    Источник

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