Answer the question
In order to leave comments, you need to log in
How to unpack a zip archive with file replacement using PHP?
Good day to all. I think the title is clear, but I repeat. Tell me, how can I unpack a zip archive without fail with file replacement using PHP?
It doesn't matter what library, the main thing is that it works.
Thank you in advance for your response.
Answer the question
In order to leave comments, you need to log in
Something like this (using PclZip):
require_once 'pclzip.lib.php';
$archive = new PclZip('archive.zip');
$archive->extract(PCLZIP_OPT_PATH, 'folder', PCLZIP_CB_PRE_EXTRACT, 'preExtractCallback');
// функция будет вызвана перед распаковкой очередного файла
function preExtractCallback($p_event, &$p_header)
{
// если файл уже существует, то удаляем его
if (file_exists($p_header['filename'])) {
unlink($p_header['filename']);
}
return 1;
}
Use Phar, it can be structured in Phar, Tar and Zip formats.
See my use case:
https://github.com/nazar-pc/CleverStyle-CMS/blob/m...
First I create a regular Phar, then I convert to *.tar.bz2
Documentation:
www.php.net/manual/ ru/book.phar.php
No need to use third-party libraries if everything is there out of the box.
Once upon a time I did this (with checking the existence of the necessary files in the archive):
//передается путь к zip архиву
public function getData($filename) {
$zip = new \ZipArchive;
$res = $zip->open($filename);
if ($res === true) {
$msg = '';
$fail = false;
if (!$zip->getFromName('1.txt')) {
$fail = true;
$msg .= 'В архиве не найден файл 1.txt. ';
}
if (!$zip->getFromName('2.txt')) {
$fail = true;
$msg .= 'В архиве не найден файл 2.txt. ';
}
if (!$zip->getFromName('3.txt')) {
$fail = true;
$msg .= 'В архиве не найден файл 3.txt. ';
}
if (!$zip->getFromName('4.txt'))
{
$fail = true;
$msg .= 'В архиве не найден файл 4.txt. ';
}
if ($fail) {
return $ms;
}
$zip->extractTo(__DIR__.'/../../../../web/uploads/DBfiles/res');
$zip->close();
return 'Файлы успешно распакованы';
}
return 'Не удалось открыть архив';
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question