Load zip file 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();

Источник

Читайте также:  What css color is this

zip_open

Эта функция была УДАЛЕНА в PHP 8.0.0. Использование этой функции не рекомендуется.

Описание

Открывает ZIP-архив для чтения.

Список параметров

Имя файла ZIP-архива для открытия.

Возвращаемые значения

Возвращает ссылку на ресурс для последующего использования с функциями zip_read() и zip_close() либо возвращает номер ошибки, если filename не существует или в случае другой ошибки.

Список изменений

Версия Описание
8.0.0 Функция устарела в пользу Object API, смотрите ZipArchive::open() .

Смотрите также

User Contributed Notes 13 notes

Note that the Zip functions return an integer error number in the event of error. So:

if ( $zip ) ?>

is incorrect. Instead use:

Some older PHP versions used to return false if zip_open failed, and newer versions return the number of error (as integer), so instead of this:

$zip = zip_open($zip_file);
if ($zip) // consider zip file opened successfully
>

$zip = zip_open($zip_file);
if (is_resource($zip)) // consider zip file opened successfully
>

You may also use this function to get the error message by it’s number:

function zipFileErrMsg($errno) // using constant name as a string to make this function PHP4 compatible
$zipFileFunctionsErrors = array(
‘ZIPARCHIVE::ER_MULTIDISK’ => ‘Multi-disk zip archives not supported.’,
‘ZIPARCHIVE::ER_RENAME’ => ‘Renaming temporary file failed.’,
‘ZIPARCHIVE::ER_CLOSE’ => ‘Closing zip archive failed’,
‘ZIPARCHIVE::ER_SEEK’ => ‘Seek error’,
‘ZIPARCHIVE::ER_READ’ => ‘Read error’,
‘ZIPARCHIVE::ER_WRITE’ => ‘Write error’,
‘ZIPARCHIVE::ER_CRC’ => ‘CRC error’,
‘ZIPARCHIVE::ER_ZIPCLOSED’ => ‘Containing zip archive was closed’,
‘ZIPARCHIVE::ER_NOENT’ => ‘No such file.’,
‘ZIPARCHIVE::ER_EXISTS’ => ‘File already exists’,
‘ZIPARCHIVE::ER_OPEN’ => ‘Can\’t open file’,
‘ZIPARCHIVE::ER_TMPOPEN’ => ‘Failure to create temporary file.’,
‘ZIPARCHIVE::ER_ZLIB’ => ‘Zlib error’,
‘ZIPARCHIVE::ER_MEMORY’ => ‘Memory allocation failure’,
‘ZIPARCHIVE::ER_CHANGED’ => ‘Entry has been changed’,
‘ZIPARCHIVE::ER_COMPNOTSUPP’ => ‘Compression method not supported.’,
‘ZIPARCHIVE::ER_EOF’ => ‘Premature EOF’,
‘ZIPARCHIVE::ER_INVAL’ => ‘Invalid argument’,
‘ZIPARCHIVE::ER_NOZIP’ => ‘Not a zip archive’,
‘ZIPARCHIVE::ER_INTERNAL’ => ‘Internal error’,
‘ZIPARCHIVE::ER_INCONS’ => ‘Zip archive inconsistent’,
‘ZIPARCHIVE::ER_REMOVE’ => ‘Can\’t remove file’,
‘ZIPARCHIVE::ER_DELETED’ => ‘Entry has been deleted’,
);
$errmsg = ‘unknown’;
foreach ($zipFileFunctionsErrors as $constName => $errorMessage) if (defined($constName) and constant($constName) === $errno) return ‘Zip File Function error: ‘.$errorMessage;
>
>
return ‘Zip File Function error: unknown’;
>

$zip = zip_open($zip_file);
if (!is_resource($zip)) die(zipFileErrMsg($zip));
>

getting a mozilla addon version (a firefox extension, for instance):

function get_addon_version ( $path )
// open zip
$zip = zip_open ( $path );

// open entry
zip_entry_open ( $zip , $entry , «r» );

// read entry
$entry_content = zip_entry_read ( $entry , zip_entry_filesize ( $entry ));

// position of
$version_open_pos = strpos ( $entry_content , «» );

// position of
$version_close_pos = strpos ( $entry_content , «» , $version_open_pos );

// version
$version = substr (
$entry_content ,
$version_open_pos + strlen ( «» ),
$version_close_pos — ( $version_open_pos + strlen ( «» ))
);

// close entry
zip_entry_close ( $entry );

Источник

zip_read

Эта функция была УДАЛЕНА в PHP 8.0.0. Использование этой функции не рекомендуется.

Описание

Считывает следующую запись в ZIP-архиве.

Список параметров

ZIP-файл, предварительно открытый с помощью функции zip_open() .

Возвращаемые значения

Возвращает запись каталога для дальнейшего использования с функциями zip_entry_. , или false , если больше нет записей для чтения, или код ошибки, если она произошла.

Список изменений

Версия Описание
8.0.0 Функция устарела в пользу Object API, смотрите ZipArchive::statIndex() .

Смотрите также

  • zip_open() — Открывает ZIP-архив
  • zip_close() — Закрывает дескриптор ZIP-архива
  • zip_entry_open() — Открывает директорию для чтения
  • zip_entry_read() — Читает данные из открытого ранее дескриптора директории

User Contributed Notes 3 notes

*Here is a simple example*
$zp = zip_open ( ‘file.zip’ );

while ( $file = zip_read ( $zp )) echo zip_entry_name ( $file ). PHP_EOL ;
>
?>

The output will be something similar to:

Note: Only the first 65535 entries will be returned, even if your archive contains more entries. See https://bugs.php.net/bug.php?id=59118 for details.

If you get an error like this:

Warning: zip_read() expects parameter 1 to be resource, integer given in xxxxxx on line x

It’s because zip_open() failed to open the file and returned an error code instead of a resource. It took me a while to figure out why it failed to open the file, until I tried to use the FULL path to the file.

// Even if the file exists, zip_open() will return an error code.
$file = ‘file.zip’ ;
$zip = zip_open ( $file );

// The workaround:
$file = getcwd () . ‘/file.zip’ ;

?>

This worked for me on Windows at least. I’m not sure about other platforms.

  • Функции Zip
  • Deprecated
    • zip_​close
    • zip_​entry_​close
    • zip_​entry_​compressedsize
    • zip_​entry_​compressionmethod
    • zip_​entry_​filesize
    • zip_​entry_​name
    • zip_​entry_​open
    • zip_​entry_​read
    • zip_​open
    • zip_​read

    Источник

    How To Read Zip Files In PHP (Simple Examples)

    Welcome to a quick tutorial on how to read zip files in PHP. So the old zip functions are deprecated in PHP 8, how do we read files using Zip Archive then? This has caused some confusion, but it is actually very straightforward.

    To read zip files in PHP, we can use statIndex() to get the file statistics, and getFromName() to directly read a file.

    • $zip = new ZipArchive;
    • $zip->open(«FILE.ZIP», ZipArchive::RDONLY);
    • $entries = $zip->count();
    • for ($i=0; $istatIndex($i); >
    • $content = $zip->getFromName(«FILE-IN-ZIP.TXT»);
    • $zip->close();

    That should cover the basics, but if you need more concrete examples – Read on!

    TLDR – QUICK SLIDES

    How To Read Zip Files In PHP

    TABLE OF CONTENTS

    PHP READ ZIP FILE

    All right, let us now get into the examples of how to read a zip file in PHP.

    1) READ FILE LIST OR INFORMATION

    open($file, ZipArchive::RDONLY) !== true) < exit("Failed to open $file"); >// (B) LOOP THROUGH EVERY FILE & FOLDER - DISPLAY INFORMATION $total = $zip->count(); for ($i=0; $istatIndex($i)); > // (C) CLOSE ZIP $zip->close();

    This should be pretty self-explanatory, and how Zip Archive works is actually somewhat like an array – Each file or folder inside the zip archive will have an index number. To get a whole list of files/folders inside the archive, we can simply use a for loop to run through them and statIndex() to fetch the information.

    2) READ FILE IN ZIP ARCHIVE

    open($file, ZipArchive::RDONLY) !== true) < exit("Failed to open $file"); >// (B) DIRECTLY READ FILE USING INDEX $content = $zip->getFromIndex(0); echo "$content
    "; // (C) OR USE GET FROM FILE NAME $content = $zip->getFromName("second.txt"); echo "$content
    "; // (D) CLOSE ZIP $zip->close();

    To read the contents of a file inside a zip archive, we can either use getFromIndex() or getFromName() . But there will be a problem dealing with large files in this one. While both functions accept a second parameter to restrict the number of bytes read, there is just no way to open it as a file stream – The best way to deal with large files is still to unzip it and use fgets() instead.

    3) LEGACY ZIP READ

     // (B) READ FILES while ($entry = zip_read($zip)) < // (B1) GET FILE NAME & SIZE $name = zip_entry_name($entry); $size = zip_entry_filesize($entry); echo "$name - $size bytes
    "; // (B2) READ FILE DIRECTLY if ($name == "first.txt") < if (zip_entry_open($zip, $entry)) < $contents = zip_entry_read($entry); echo "$contents
    "; zip_entry_close($entry); > else < echo "Cannot open first.txt"; >> > zip_close($zip);

    Yes, the old zip functions are deprecated in PHP 8 (they still work but will eventually disappear). I shall not explain too much on this example but leave it here as “legacy support”… Do not use this method anymore, unless you have to support the older PHP versions.

    EXTRA) HOW TO UNZIP FILE

    open("TEST.ZIP") === TRUE) < $zip->extractTo("DESTINATION/FOLDER/"); $zip->close(); >

    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 all for the main tutorial, and here is a small section on some extras and links that may be useful to you.

    SUMMARY & REFERENCES

    INFOGRAPHIC CHEAT SHEET

    THE END

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

    Leave a Comment Cancel Reply

    Breakthrough Javascript

    Take pictures with the webcam, voice commands, video calls, GPS, NFC. Yes, all possible with Javascript — Check out Breakthrough Javascript!

    Socials

    About Me

    W.S. Toh is a senior web developer and SEO practitioner with over 20 years of experience. Graduated from the University of London. When not secretly being an evil tech ninja, he enjoys photography and working on DIY projects.

    Code Boxx participates in the eBay Partner Network, an affiliate program designed for sites to earn commission fees by linking to ebay.com. We also participate in affiliate programs with Bluehost, ShareASale, Clickbank, and other sites. We are compensated for referring traffic.

    Источник

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