Php ziparchive ошибка

I have a problem that I install ‘Archive_Zip 0.1.1’ on Linux server, but when I try to run the script to create the zip file it gives the fatal error

Fatal error: Class ZipArchive not found in …

where I put the code

$zip = new ZipArchive;
var_dump($zip);
$res = $zip->open($filename, ZipArchive::OVERWRITE);
if ($res !== TRUE) {
    echo 'Error: Unable to create zip file';
    exit;
}
if (is_file($src)) {
    $zip->addFile($src);
} else {
    // echo "<br>" . dirname(__FILE__) . $src;//'/install1';
    if (!is_dir($src)) {
         $zip->close();
         @unlink($filename);
         echo 'Error: File not found';
         exit;
    }
    recurse_zip($src, $zip, $path_length);
}
$zip->close();
echo "<br>file name ".$filename;

but it doesn’t find the class file.

Please tell me the solution. What should I do to resolve the problem?
I also put php.ini file to the folder where script is, but it does not work.

Alessio Cantarella's user avatar

asked Oct 6, 2010 at 12:47

Parag Chaure's user avatar

Parag ChaureParag Chaure

2,9032 gold badges19 silver badges27 bronze badges

6

For the ZipArchive class to be present, PHP needs to have the zip extension installed.

See this page for installation instructions (both Linux and Windows).

On Debian and Ubuntu, you can usually install it with:

sudo apt update
sudo apt install php-zip

Then restart your webserver. Example:

sudo systemctl restart apache2

Valerio Bozz's user avatar

answered Oct 6, 2010 at 12:49

Pekka's user avatar

14

On Amazon ec2 with Ubuntu + nginx + php7, I had the same issues, solved it using:

sudo apt-get install php7.0-zip

answered May 6, 2016 at 6:56

Dixit's user avatar

DixitDixit

12.7k3 gold badges49 silver badges46 bronze badges

3

On ubuntu desktop, I had to do.

sudo apt-get install php5.6-zip

This installed the library but I still kept on getting the same error, so I had to restart apache using:

sudo service apache2 restart

and it worked.

answered Oct 28, 2016 at 12:10

Mubashar Abbas's user avatar

Mubashar AbbasMubashar Abbas

5,5064 gold badges38 silver badges49 bronze badges

1

I’m not seeing it here, so I’d like to add that on Debian/Ubuntu you may need to enable the extension after installing the relative package. So:

sudo apt-get install php-zip
sudo phpenmod zip
sudo service apache2 restart

answered Oct 16, 2017 at 6:54

lorenzo-s's user avatar

lorenzo-slorenzo-s

16.6k15 gold badges54 silver badges86 bronze badges

4

First of all, The solution for remote server:

If you are using cpanel you may have zip extension installed but not activate. You need to active it. For this case you need to go to cpanel > inside software section > click on PHP version. Then find zip and check it. Now save.

You should see like the image.
enter image description here

Refresh page. The error should disappear.

Note: If you dont found, contact server provider. They will install for you.

answered Nov 17, 2017 at 2:39

Kalyan Halder's user avatar

2

Centos 6

Or any RHEL-based flavors

yum install php-pecl-zip

service httpd restart

Abel Callejo's user avatar

Abel Callejo

13.5k10 gold badges69 silver badges84 bronze badges

answered Oct 10, 2018 at 13:57

zzapper's user avatar

zzapperzzapper

4,7435 gold badges48 silver badges45 bronze badges

1

If you have WHM available it is easier.

Log in to WHM.

Go to EasyApache 4 (or whatever version u have) under Software tab.

Under Currently Installed Packages click Customize.

Go to PHP Extensions, in search type «zip» (without quotes),

you should see 3 modules

check all of them,

click blue button few times to finish the process.

This worked for me.
Thankfully I’ve WHM available.

answered May 15, 2018 at 11:36

temo's user avatar

temotemo

6121 gold badge9 silver badges25 bronze badges

1

For PHP 7.x

sudo apt-get install php-zip

For PHP 5.x

sudo apt-get install php5.x-zip
// (for example sudo apt-get install php5.6-zip)

And then restart the Apache server

sudo service apache2 restart

answered Dec 6, 2019 at 5:32

Santo Boldizar's user avatar

You also need to compile PHP with zip support. The manual says the following:

In order to use these functions you must compile PHP with zip support by using the —enable-zip configure option.

It’s not enough to simply install the correct extensions on the server. Have a look at the installation instructions link Pekka posted earlier. My answer is just a clarification of his.

answered Oct 6, 2010 at 13:08

Jeremy's user avatar

JeremyJeremy

2,6511 gold badge22 silver badges28 bronze badges

3

This worked

apt-get install php7.0-zip

and no need to restart php7.0-fpm manually.

Unpacking php7.0-zip (7.0.16-4+deb.sury.org~trusty+1) …
Processing triggers for php7.0-fpm (7.0.11-1+deb.sury.org~trusty+1) …
php7.0-fpm stop/waiting
php7.0-fpm start/running, process 1572
php7.0-fpm stop/waiting
php7.0-fpm start/running, process 1777
Setting up php7.0-zip (7.0.16-4+deb.sury.org~trusty+1) …
locale: Cannot set LC_ALL to default locale: No such file or directory

Creating config file /etc/php/7.0/mods-available/zip.ini with new version
Processing triggers for php7.0-fpm (7.0.11-1+deb.sury.org~trusty+1) …
php7.0-fpm stop/waiting
php7.0-fpm start/running, process 2354
php7.0-fpm stop/waiting
php7.0-fpm start/running, process 2397

Alessio Cantarella's user avatar

answered Mar 13, 2017 at 19:22

prosti's user avatar

prostiprosti

42.4k14 gold badges186 silver badges152 bronze badges

I had the same issue with CentOS and cPanel installed server. I installed zipArchive package via cPanel and didn’t worked as expected.
After trying with so many fixes suggested each and everywhere just the below worked for me.

First find the name for the correct package with the below command

yum search zip |grep -i php

Then use the below code.

yum install your_zip_package_name_with_php_version

In my case correct code to install zipArchive was

yum install php-pecl-zip.x86_64

I had the solution from this link.
How can I inslatt zipArchive on PHP 7.2 with CentOS 7?

And this installation somehow enabled that package too and it also restarted the effecting services and after the completion of the execution of the above code zipArchive issue was gone.

answered Sep 2, 2018 at 9:52

Anton Perera's user avatar

PHP 5.2.0 and later

Linux systems

In order to use these functions you must compile PHP with zip support by using the —enable-zip configure option.

Windows

Windows users need to enable php_zip.dll inside of php.ini in order to use these functions.

answered Jul 1, 2013 at 11:39

V A S's user avatar

V A SV A S

3,3384 gold badges33 silver badges39 bronze badges

For Centos 7 and PHP 7.3 on Remi

Search for the zip extension:

$ yum search php73 | grep zip
php73-php-pecl-zip.x86_64 : A ZIP archive management extension

The extension name is php73-php-pecl-zip.x86_64. To install it in server running single version of PHP, remove the prefix php73:

$ sudo yum --enablerepo=remi-php73 install php-pecl-zip #for server running single PHP7.3 version
$ #sudo yum --enablerepo=remi-php73 install php73-php-pecl-zip # for server running multiple PHP versions

Restart PHP:

$ sudo systemctl restart php-fpm

Check installed PHP extensions:

$ php -m
[PHP Modules]
apcu
bcmath
bz2
...
zip
zlib

answered Jan 7, 2020 at 3:51

kiatng's user avatar

kiatngkiatng

2,85732 silver badges39 bronze badges

0

I faced this issue on GCP while deploying wordpress in the App Engine Standard environment. This solved it :

sudo apt-get install php7.2-zip

answered Oct 18, 2019 at 3:55

Omar Shabab's user avatar

Omar ShababOmar Shabab

5417 silver badges16 bronze badges

For me work, first review

   php -m
   php -version

Later install the extension

apt-get update 
apt-get install php7.2-zip
systemctl restart apache2

answered Oct 14, 2020 at 22:01

Doberon's user avatar

DoberonDoberon

6119 silver badges19 bronze badges

If you are running into this error while using a Docker image and that you are calling the class properly, or that the error comes from an up-to-date library, then the zip module is probably missing.

Assuming we use docker-compose, we can confirm it’s missing by running docker-compose run php php -m for instance and see that zip is not listed.

To install it in your image, modify your Dockerfile so it does the same as this example.

FROM php:7.3-apache 

RUN set -eux \
    && apt-get update \
    && apt-get install -y libzip-dev zlib1g-dev \
    && docker-php-ext-install zip

Then rebuild the image with docker-compose build php and you are good to go.

answered Dec 9, 2020 at 8:43

Capripot's user avatar

CapripotCapripot

1,35416 silver badges26 bronze badges

For PHP 7.4 > The ZipArchive is not longer present by default and you need to install and configure it.

I strongly suggest using a library which you can just include in your project — like https://github.com/zanysoft/laravel-zip
This library is just a wrapper for the native ZipArchive

answered Sep 15, 2021 at 8:13

alex toader's user avatar

alex toaderalex toader

2,3101 gold badge17 silver badges20 bronze badges

For CentOS based server use

yum install php-pecl-zip.x86_64

Enable it by running: echo "extension=zip.so" >> /etc/php.d/zip.ini

answered Jan 7, 2020 at 11:10

Wolfack's user avatar

WolfackWolfack

2,6671 gold badge26 silver badges50 bronze badges

You need to check the PHP version

If php version is 5.6 then , You need to install php5.7-zip

sudo apt-get install php5.6-zip

and then

sudo service apache2 restart

Hope it helps

answered May 12, 2020 at 5:16

Sundar's user avatar

SundarSundar

2632 silver badges6 bronze badges

I had the same issue and it had solved using two command lines:

sudo apt install php-zip

then reboot your web server, for Apache

sudo service apache2 restart

answered Mar 11, 2019 at 13:08

AboElnouR's user avatar

AboElnouRAboElnouR

2813 silver badges14 bronze badges

Try to write \ZIPARCHIVE instead of ZIPARCHIVE.

answered Feb 9, 2020 at 12:27

URL87's user avatar

URL87URL87

10.7k35 gold badges107 silver badges175 bronze badges

namespace

If you get this problem after adding namespace you can use the global namespace (backslash \ ):

$zip = new \ZipArchive;

answered Jun 18, 2021 at 22:02

Mahdi Bashirpour's user avatar

Mahdi BashirpourMahdi Bashirpour

17.2k13 gold badges118 silver badges146 bronze badges

CPanel [ Sharing Hosting ]
To fix this issue or error use the below steps:-

Error Details:-
/=========================================================================
An uncaught Exception was encountered
Type: Error

Message: Class 'ZipArchive' not found

Filename: /home/b2bvniowy1go/public_html/system/libraries/PHPExcel/Reader/Excel2007.php

Line Number: 85

Backtrace:

File: /home/b2bvniowy1go/public_html/dashboard/controllers/Brand_price.php

============================================================================ /

cPanel Version [ 94.0 (build 19) ]
Solution:-  Do this changes to your remote server:  Cpanel > Select PHP version section > extensions tab. Then find zip and check it. Now save.

zip setting in cpanel

answered May 4, 2022 at 9:23

Sonu Chohan's user avatar

1

The same in CMS Typo3 ver.11.5.8
while installing an extension by the Extension Manager,
nevermind that the Zip extension was installed in the cpanel.

The reason: in the .htaccess there was:

AddType application/x-httpd-php74 .php
AddHandler application/x-httpd-php74 .php

The fix: change the above by:

AddType application/x-httpd-alt-php74 .php .php7 .phtml

Now it’s working in me.

answered Feb 7 at 22:38

Tashko Valkov's user avatar

Don’t forget to use this class
use ZipArchive;

answered Mar 12 at 9:20

Nigus Abate's user avatar

  • Goto php.ini
  • Search for zip
  • Remove ‘;’ from that line (uncomment it)

answered May 23 at 9:41

Nikunj Singhania's user avatar

You can use the following script to find the currently installed PHP versions:

# /usr/local/cpanel/bin/rebuild_phpconf --current

Once you have identified that version of PHP, you can then install the missing «Zip» module. You can install them with the following command:

yum install ea-phpXX-php-zip*

toyota Supra's user avatar

toyota Supra

3,2165 gold badges15 silver badges19 bronze badges

answered Aug 9 at 14:38

maedeh afrasteh's user avatar

1) You should require your file with ZipArchive file.

require 'path/to/file/ZipArchive.php';

2) Or use __autoload method of class.
In PHP 5 it is a greate method __autoload().

function __autoload($class_name) {
    require_once $class_name . '.php';
}

$obj  = new MyClass1(); // creating an object without require.

http://www.php.net/manual/en/language.oop5.autoload.php

answered Oct 6, 2010 at 12:52

Alex Pliutau's user avatar

Alex PliutauAlex Pliutau

21.4k27 gold badges113 silver badges143 bronze badges

1

(PHP 5 >= 5.2.0, PHP 7, PHP 8, PECL zip >= 1.1.0)

ZipArchive::openОткрывает ZIP-архив

Описание

public ZipArchive::open(string $filename, int $flags = 0): bool|int

Начиная с libzip 1.6.0, пустой файл больше не является корректным архивом.

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

Возвращает true в случае успешного выполнения, false или один из следующих кодов ошибки:

ZipArchive::ER_EXISTS

Файл уже существует.

ZipArchive::ER_INCONS

Несовместимый ZIP-архив.

ZipArchive::ER_INVAL

Недопустимый аргумент.

ZipArchive::ER_MEMORY

Ошибка динамического выделения памяти.

ZipArchive::ER_NOENT

Нет такого файла.

ZipArchive::ER_NOZIP

Не является ZIP-архивом.

ZipArchive::ER_OPEN

Невозможно открыть файл.

ZipArchive::ER_READ

Ошибка чтения.

ZipArchive::ER_SEEK

Ошибка поиска.

Примеры

Пример #1 Открытие и извлечение

<?php
$zip
= new ZipArchive;
$res = $zip->open('test.zip');
if (
$res === TRUE) {
echo
'готово';
$zip->extractTo('test');
$zip->close();
} else {
echo
'ошибка с кодом:' . $res;
}
?>

Пример #2 Создание архива

<?php
$zip
= new ZipArchive;
$res = $zip->open('test.zip', ZipArchive::CREATE);
if (
$res === TRUE) {
$zip->addFromString('test.txt', 'содержимое файла');
$zip->addFile('data.txt', 'entryname.txt');
$zip->close();
echo
'готово';
} else {
echo
'ошибка';
}
?>

Пример #3 Создать временный архив

<?php
$name
= tempnam(sys_get_temp_dir(), "FOO");
$zip = new ZipArchive;
$res = $zip->open($name, ZipArchive::OVERWRITE); /* усечение, поскольку пустой файл недопустим */
if ($res === TRUE) {
$zip->addFile('data.txt', 'entryname.txt');
$zip->close();
echo
'готово';
} else {
echo
'ошибка';
}
?>

eric at webdeveric dot com

14 years ago

With php 5.2.6, the following code created a new zip or replaced a existing zip.
Note that I am only using the ZIPARCHIVE::OVERWRITE flag.

<?php
$zip
= new ZipArchive();
$opened = $zip->open( $zipFileName, ZIPARCHIVE::OVERWRITE );
if(
$opened !== true ){
die(
"cannot open {$zipFileName} for writing.");
}
$zip->addFromString( $name, $contents );
$zip->close();
?>

Now, with php 5.2.8, it does not work and gives this warning:

Warning: ZipArchive::addFromString() [ziparchive.addfromstring]: Invalid or unitialized Zip object in [myfile] on line [myline]

To fix this, you must specify the flags as create or overwrite.

<?php
$zip
= new ZipArchive();
$opened = $zip->open( $zipFileName, ZIPARCHIVE::CREATE | ZIPARCHIVE::OVERWRITE );
if(
$opened !== true ){
die(
"cannot open {$zipFileName} for writing.");
}
$zip->addFromString( $name, $contents );
$zip->close();
?>

When googling for the error message I found a lot of people that had it but couldn't figure out why they were getting it.
I hope this helps someone.

abolfazl dot ziaratban at gmail dot com

8 years ago

<?php
#made by abolfazl ziaratban (c)
#license GPL
class zip extends ZipArchive
{
public function
message($code)
{
switch (
$code)
{
case
0:
return
'No error';

case

1:
return
'Multi-disk zip archives not supported';

case

2:
return
'Renaming temporary file failed';

case

3:
return
'Closing zip archive failed';

case

4:
return
'Seek error';

case

5:
return
'Read error';

case

6:
return
'Write error';

case

7:
return
'CRC error';

case

8:
return
'Containing zip archive was closed';

case

9:
return
'No such file';

case

10:
return
'File already exists';

case

11:
return
'Can\'t open file';

case

12:
return
'Failure to create temporary file';

case

13:
return
'Zlib error';

case

14:
return
'Malloc failure';

case

15:
return
'Entry has been changed';

case

16:
return
'Compression method not supported';

case

17:
return
'Premature EOF';

case

18:
return
'Invalid argument';

case

19:
return
'Not a zip archive';

case

20:
return
'Internal error';

case

21:
return
'Zip archive inconsistent';

case

22:
return
'Can\'t remove file';

case

23:
return
'Entry has been deleted';

default:
return

'An unknown error has occurred('.intval($code).')';
}
}

public function

isDir($path)
{
return
substr($path,-1) == '/';
}

public function

getTree()
{
$Tree = array();
$pathArray = array();
for(
$i=0; $i<$this->numFiles; $i++)
{
$path = $this->getNameIndex($i);
$pathBySlash = array_values(explode('/',$path));
$c = count($pathBySlash);
$temp = &$Tree;
for(
$j=0; $j<$c-1; $j++)
if(isset(
$temp[$pathBySlash[$j]]))
$temp = &$temp[$pathBySlash[$j]];
else
{
$temp[$pathBySlash[$j]] = array();
$temp = &$temp[$pathBySlash[$j]];
}
if(
$this->isDir($path))
$temp[$pathBySlash[$c-1]] = array();
else
$temp[] = $pathBySlash[$c-1];
}
return
$Tree;
}
}
?>

ohcc at 163 dot com

7 years ago

<?php
// Use ZipArchive::OVERWRITE when the targetd file does not exist may lead you to an error like this
// Warning: ZipArchive::addFile(): Invalid or uninitialized Zip object
// try ZipArchive::OVERWRITE|ZipArchive::CREATE when you want to replace a zip archive that may not exist
$zip = new ZipArchive;
$rt=$zip->open('i.zip',ZipArchive::OVERWRITE);
echo
$rt;
// when i.zip does not exist, $rt is 9, ZipArchive::ER_NOENT, or "No such file."
$zip->addFile('wuxiancheng.cn.sql','db.sql');
// triggers an error with the message "Warning: ZipArchive::addFile(): Invalid or uninitialized Zip object ..."

// Use ZipArchive::OVERWRITE|ZipArchive::CREATE

$zip = new ZipArchive;
$zip->open('i.zip',ZipArchive::OVERWRITE|ZipArchive::CREATE);
$zip->addFile('wuxiancheng.cn.sql','db.sql');
?>

jekillen at prodigy net

8 years ago

Calling ZipArchive->open() will not create an empty zip archive file.
I found this out the hard way. I wrote code that produced positive
results: I.E. the return value from the call to ZipArchive was TRUE
and the empty zip file was not created. So at least call
ZipArchive->addFromString(<filename.zip>, '<minimal content>')
when creating a new zip archive file.

jj at icglink dot com

14 years ago

if you are echoing out the output and confused about the number...maybe this will help. i'm not totally sure it is accurate though.

ZIPARCHIVE::ER_EXISTS - 10
ZIPARCHIVE::ER_INCONS - 21
ZIPARCHIVE::ER_INVAL - 18
ZIPARCHIVE::ER_MEMORY - 14
ZIPARCHIVE::ER_NOENT - 9
ZIPARCHIVE::ER_NOZIP - 19
ZIPARCHIVE::ER_OPEN - 11
ZIPARCHIVE::ER_READ - 5
ZIPARCHIVE::ER_SEEK - 4

Fred Johnson

3 years ago

Note that ZipArchive does not support generating streaming ZIP file content (i.e. start sending data to the user as soon as you start generating it such as from a database). This means you have to write the entire file to disk first and then send the file to the user. Doing that can take a while depending on how much data there is, which could run up against server timeout limits.

There are a couple of PHP userland libraries available on GitHub that can stream ZIP file content out to the user as soon as any data is written to the relevant classes.

cubiclesoft/php-zipstreamwriter
maennchen/ZipStream-PHP

Maybe a future version of ZipArchive will offer something similar.

walter at clevertechie dot com

10 years ago

If you have archives that you want to overwrite just use:

ZIPARCHIVE::CREATE

It will overwrite existing archives and at the same time create new ones if they don't already exist.

ZIPARCHIVE::OVERWRITE won't work for both of these scenarios.

(PHP version 5.4.4)

sunil dt bhave at gmail dt com

12 years ago

Even though the api specifies that the flags are optional I found that I had to specify the flag ZIPARCHIVE::CREATE for an archive to be opened.
This is on a Windows 7 system with PHP 5.3.0

Jan Vavra

12 years ago

As discussed in http://bugs.php.net/bug.php?id=54128 on Windows Server systems (2003, 2008) and IIS there is a problem when you want to unzip file stored in C:\Windows\Temp folder.
User of worker process IUSR_XXX has no directory listing right for C:\Windows\Temp and this is a reason why ZipArchive::open() fails with error 11 (error open). So it is not a good idea to store file for unzipping in folder defined by sys_get_temp_dir().

rickky at gmail dot com

16 years ago

If the directory you are writing or saving into does not have the correct permissions set, you won't get any error messages and it will look like everything worked fine... except it won't have changed!

Instead make sure you collect the return value of ZipArchive::close(). If it is false... it didn't work.

Eric Langlois

9 years ago

<?PHP
$zip
= new ZipArchive;
$res = $zip->open('test.zip', ZipArchive::CREATE);

if (

$res === TRUE) {
//CODE GOES HERE$zip->close();
} else {
switch(
$res){
case
ZipArchive::ER_EXISTS:
$ErrMsg = "File already exists.";
break;

case

ZipArchive::ER_INCONS:
$ErrMsg = "Zip archive inconsistent.";
break;

case

ZipArchive::ER_MEMORY:
$ErrMsg = "Malloc failure.";
break;

case

ZipArchive::ER_NOENT:
$ErrMsg = "No such file.";
break;

case

ZipArchive::ER_NOZIP:
$ErrMsg = "Not a zip archive.";
break;

case

ZipArchive::ER_OPEN:
$ErrMsg = "Can't open file.";
break;

case

ZipArchive::ER_READ:
$ErrMsg = "Read error.";
break;

case

ZipArchive::ER_SEEK:
$ErrMsg = "Seek error.";
break;

default:

$ErrMsg = "Unknow (Code $rOpen)";
break;

}
die(

'ZipArchive Error: ' . $ErrMsg);
}
?>

ohcc at 163 dot com

7 years ago

ZipArchive::OVERWRITE does NOT mean an existing file would be deleted when ZipArchive::open() is called.

In fact, the existing file will be deleted before PHP saves the zip archive on disk.

PHP takes these steps to finish zipping:

1. When ZipArchive::open('xx.zip') is called
If 'xx.zip' exists and is a zip archive, it will be opened and read as a temporary zip file,
If the file does not exist, and ZipArchive::CREATE is applied, php will create a temporary empty zip file
In these cases, ZipArchive::open() returns true, otherwise it returns an integer error code.
2. Adds file(s) to the temporary zip file when methods such as addFile(), addFromString() are called.
3. Deletes the existing file before saving the temporary zip file on disk.
4. Save the temporary zip file on disk
5. Closes the active archive when ZipArchive::close() is called or at the end of the script

Since PHP does NOT delete the existing file before saving the zip archive on disk, you should use unset() to delete it if you want to zip that file's containing folder and save the zip archive in that folder, otherwise you will get a larger and larger zip archive everytime you refresh the page.

ohcc at 163 dot com

7 years ago

return values of ZipArchive::open() and their values and meanings
ZipArchive::ER_SEEK 4 Seek error.
ZipArchive::ER_READ 5 Read error.
ZipArchive::ER_NOENT 9 No such file.
ZipArchive::ER_OPEN 11 Can't open file.
ZipArchive::ER_EXISTS 10 File already exists.
ZipArchive::ER_MEMORY 14 Malloc failure.
ZipArchive::ER_INVAL 18 Invalid argument.
ZipArchive::ER_NOZIP 19 Not a zip archive.
ZipArchive::ER_INCONS 21 Zip archive inconsistent

laacz at laacz dot lv

2 years ago

If on PHP 8.0+, you can use match expression to decode status code:

<?php
$archive
= new \ZipArchive();
$result = $archive->open('some.file.zip');$message = match ($result) {
\
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 => 'Malloc 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',
// \ZipArchive::ER_OK => 'No error',
default => 'No error',
};
?>

Anonymous

2 years ago

To read a zip file contents then loop through $zip->numFiles using $zip->getNameIndex(i)

e.g.

$zipfilename=$dir.DIRECTORY_SEPARATOR."test.zip";
$zippedFile = new ZipArchive;
$zippedFile->open($zipfilename);

echo "<LI>".$zippedFile->getFromName("mpdf-8.0.7/.gitignore")."</LI><HR>";

echo "<LI>Loaded $zipfilename ".$zippedFile->numFiles;
for($i = 0; $i < $zippedFile->numFiles; $i++) {
$fn=$zippedFile->getNameIndex($i);
echo "<LI>$i: ".$fn;

if ( strcmp(substr($fn, -1), DIRECTORY_SEPARATOR )==0 ) echo "... directory";
else echo "... ".strlen($zippedFile->getFromIndex($i))." bytes";

}
$zippedFile->close();

YiiWanAB at hotmail dot com

12 years ago

Most of the time people iterate over a directory with 'opendir' or 'readdir' to add files to a zip. Like...

while ($file = readdir($dir)) { ... $zip->addFile($file) }

Note that $zip->addFile($file) will only work in the current directory if your at the root. You will need to add the correct path to that $file string variable to have the full file name like ...

$zip->addFile($dir . DIRECTORY_SEPARATOR . $file); will work.

This may identify why you may get a read error when closing the file.

Enjoy.

Jonathan Baltazar

15 years ago

The file name does not need to end in '.zip' if it is created using tempnam(). You just need to overwrite the file instead of trying to read it:

<?php

$file
= tempnam("tmp", "zip");
$zip = new ZipArchive();
// Zip will open and overwrite the file, rather than try to read it.

$zip->open($file, ZipArchive::OVERWRITE);
$zip->close();
// Stream the file to the client

header("Content-Type: application/zip");

header("Content-Length: " . filesize($file));

header("Content-Disposition: attachment; filename=\"a_zip_file.zip\"");

readfile($file);
unlink($file);

?>

sebwoolford at gmail dot com

13 years ago

Further to what rickky at gmail dot com was saying, I've had that problem while trying to cache zip files and found that I had to set the permissions of the containing folder to 777 to get it to work.

Because this is a potential security weakness if on a public viewable folder, I'd recommend moving the folder so that it is no longer within public_html. You can then use readfile() to output the archive to the browser, with some HTTP headers to tell the browser it is a zip file.

michael202 at gmx dot de

14 years ago

to anyone getting an error ZIPARCHIVE::ER_READ = 5, when
doing $zip->open($zipfile) with a ZIP file containing a total of more then (around) 800 files (even when they are in sub-directories).

possibly related bugs 40873, 8714:

1. it was not an OS limit, because it worked when called from windows via samba on the same file at the same place

2. it wasn't working under 32bit linux

with php 5.3.0 the issue seems to be resolved.

azsymvelik at gmail dot com

15 years ago

<?php
/*

Hi!

I made a little script about checking content and "secure repacking"

*/

$somefile = "zip.zip";

$someurl = "/some/url"

$zip = new ZipArchive;

$open = $zip->open($somefile, ZIPARCHIVE::CHECKCONS);

// If the archive is broken(or just another file renamed to *.zip) the function will return error on httpd under windows, so it's good to check if the archive is ok with ZIPARCHIVE::CHECKCONS

if ($open === TRUE) {

if(!
$zip->extractTo($someurl)) {

die (
"Error during extracting");

}

$zip->close();

}

$new_archive_name = "new.zip";

$new_zip = new ZipArchive;

$new_open = $new_zip->open($new_archive_name, ZIPARCHIVE::CREATE);

if (
$new_open === TRUE) {

$dir = opendir($someurl);

while (
$file = readdir($dir)) {

if (
$file == "." || $file == "..") { } else {

//We do not wanna this files in the new zip archive

if (!$new_zip->addFile($file)) {

print
$file."was not added!<br />";

}

}

}

}

$new_zip->close();

?>

olivier pons

15 years ago

If you try this to open a file with creation in mind (= empty zip to fill with other files), this may not work :

$res = $zip->open($zip_file, ZipArchive::CREATE);

// you may get false

Try this instead, it should work :

$res = $zip->open($zip_file, ZIPARCHIVE::OVERWRITE);

Is your PHP saying that it cannot find the ZipArchive class? Then, this post will show you how to enable the ZipArchive module.

You should see the following error:

PHP Fatal error: Uncaught Error: Class 'ZipArchive' not found

Also, below is an example of the code you may be using:

$zip = new \ZipArchive();
$x = $zip->open($target_path);
if ($x === true) {
    $zip->extractTo($target_dir . $name[0]);
    $zip->close();
}

Table of Contents

What does this error mean?

This error means that PHP could not find the ZipArchive class. Therefore, PHP needs to have the zip extension installed for the ZipArchive Class to be present.

You can check whether ZipArchive is installed by using a PHP info file.

See an example below:

Your PHP info file should return something like this:

Next, scroll down until you find the heading “Configuration” and then continue until you see the following:

You will know that the ZipArchive class is not enabled if you cannot see: “Zip” configuration “enabled”.

You can also check whether the Zip module is enabled using the CLI.

Show compiled in modules using: php -m.

user@server:/var/www/html# php -m
[PHP Modules]
Core
ctype
date
dom
zip
zlib

[Zend Modules]

As the PHP module list can get quite large, consider using the grep command to filter your list:

Or you can use “php -m” to show the PHP information in the CLI.

How to enable ZipArchive on Windows

Windows users have it easy! You do not need to do anything if you use PHP 5.3 or newer. So, don’t trust that the code written and evaluated on Windows will work on Linux.

As of PHP 5.3, this extension is built-in. Before, Windows users needed to enable php_zip.dll inside of php.ini  to use these functions.

https://www.php.net/manual/en/zip.installation.php

Before you enable ZipArchive

You can enable Zip support during the installation of PHP and after the fact. This post will focus on an after-the-fact ZipArchive installation on Linux. Please read the installing Zip instruction from the PHP manual for more information.

Before you continue, note the following helpful command to get your current version of PHP:

user@server:/var/www/html# php -v
PHP 7.4.2 (cli) (built: Feb  1 2020 19:39:30) ( NTS )
Copyright (c) The PHP Group
Zend Engine v3.4.0, Copyright (c) Zend Technologies

Note the version in the example above being: 7.4.2. We will, therefore, need to install the Zip module for PHP version 7.4. Please remember to change the version number to match yours if the command requires it!

Also, make sure that your packages are up to date using the “apt-get update” command:

user@server:/var/www/html# apt-get update
Hit:1 http://security.debian.org/debian-security buster/updates InRelease
Hit:2 http://deb.debian.org/debian buster InRelease
Hit:3 http://deb.debian.org/debian buster-updates InRelease
Reading package lists... Done

Lastly, you may need to determine the location of the loaded php.ini file. Please note that the CLI uses its version.

Use the following command to help you:

user@server:/var/www/html# php --ini
Configuration File (php.ini) Path: /usr/local/etc/php
Loaded Configuration File:         /usr/local/etc/php/php.ini
Scan for additional .ini files in: /usr/local/etc/php/conf.d
Additional .ini files parsed:      /usr/local/etc/php/conf.d/docker-php-ext-pdo_mysql.ini,
/usr/local/etc/php/conf.d/docker-php-ext-redis.ini,
/usr/local/etc/php/conf.d/docker-php-ext-sodium.ini,
/usr/local/etc/php/conf.d/docker-php-ext-zip.ini

How to enable ZipArchive on Docker

First, run the following command to install Zip and compile PHP correctly to run it.

apt-get install -y libzip-dev zip && docker-php-ext-install zip

Below you will see how to restart Apache or NGINX. Once you install, you have finished.

Note that you will get an “E: Package ‘php-XXX’ has no installation candidate” error if you try to install any of Debian‘s PHP packages. This error is the default intended behavior of the official PHP Docker image.

You can see an example of this behavior below:

user@server:/var/www/html# apt-get install php-zip
Reading package lists... Done
Building dependency tree
Reading state information... Done
Package php-zip is a virtual package provided by:
  php7.3-zip 7.3.14-1~deb10u1 [Not candidate version]
  php7.3-zip 7.3.11-1~deb10u1 [Not candidate version]

E: Package 'php-zip' has no installation candidate

You can also get the following error if you specify a specific version.

user@server:/var/www/html# apt-get install php7.0-zip
Reading package lists... Done
Building dependency tree
Reading state information... Done
E: Unable to locate package php7.0-zip
E: Couldn't find any package by glob 'php7.0-zip'
E: Couldn't find any package by regex 'php7.0-zip'

How to enable ZipArchive on Linux on Ubuntu

The install PHP Zip command:

sudo apt-get install -y php-zip

The output will result in something like this:

user@server:/home/user# sudo apt-get install php-zip
Reading package lists... Done
Building dependency tree       
Reading state information... Done
The following additional packages will be installed:
  libzip5 php-common php7.3-common php7.3-zip
The following NEW packages will be installed:
  libzip5 php-common php-zip php7.3-common php7.3-zip
0 to upgrade, 5 to newly install, 0 to remove and 48 not to upgrade.
1 not fully installed or removed.
Need to get 1,003 kB of archives.
After this operation, 7,443 kB of additional disk space will be used.

Please note that you may need to specify the PHP version if you upgraded to a recent version of PHP.

Don’t forget to restart your web server!

The configuration file (php.ini) is only read when PHP or the webserver starts. Equally, the php.ini file is only read at invocation for the CGI and CLI versions.

You can restart Apache using:

Likewise, you can restart NGINX using:

Wrapping up

It is easy to get your website zipping files and avoid a fatal error. I hope that you now know how to enable ZipArchive for PHP. No one likes seeing a “Fatal error: Class’ ZipArchive’ not found in”.

You may also be interested in


About the Authors

Anto’s editorial team loves the cloud as much as you! Each member of Anto’s editorial team is a Cloud expert in their own right. Anto Online takes great pride in helping fellow Cloud enthusiasts. Let us know if you have an excellent idea for the next topic! Contact Anto Online if you want to contribute.

Support the Cause

Support Anto Online and buy us a coffee. Anything is possible with coffee and code.

Buy me a coffee


i’m trying to create a zip script based on what I’ve found here but I seem to be getting a Fatal error: Class ‘ZipArchive’ not found error on the new ZipArchive(); function.

Researching this it seems that this is usually due to the way PHP is compiled. I have a shared hosting account, so i’ve not configured any of this stuff…and I assume that I can’t make any changes to the build. Out of interest I took a look in my phpinfo() and I found some things that looked associated:

PHP Version 5.2.6

BZip2 Support   Enabled    <--maybe not so relevant
ZLib Support    enabled
Stream Wrapper support  compress.zlib://
Stream Filter support   zlib.inflate, zlib.deflate
Compiled Version    1.1.4
Linked Version  1.1.4 

I’m not entirly sure if any of this means that I have the ability to create zips.
For further info (although I don’t think it’s relivent) here’s my script so far….this is untested mind you as I can’t get pased this Class not found error.

$file = tempnam("tmp", "zip");
$zip = new ZipArchive();
$zip->open($file, ZipArchive::OVERWRITE);


   //the string "file1" is the name we're assigning the file in the archive
$zip->addFile('show1.jpg', 'file1.jpg');
$zip->addFile('show2.jpg', 'file2.jpg');
$zip->addFile('show3.jpg', 'file3.jpg');
$zip->addFile('show4.jpg', 'file4.jpg');
$zip->addFile('show5.jpg', 'file5.jpg');
$zip->addFile('show6.jpg', 'file6.jpg');

// echo $zip->file(); //this sends the compressed archive to the output buffer instead of writing it to a file.

$zip->close();
header('Content-Type: application/zip');
header('Content-Length: ' . filesize($file));
header('Content-Disposition: attachment; filename="' . $file.'"');
readfile($file);
unlink($file); 

So my question(s) really are:

  1. Am I doing anything in my script to cause this error?
  2. Does any of that stuff from my phpinfo() mean I should be able to create zip files, ..if not what should I be looking for in there that will let me know if i have the capability.
  3. It looks like this ZLib is some soft of library, but I’ve got no idea if it does what I want it do, or even how to use it….this is a bit of a hunch, but if it can help me create zip files can anyone point me in the right direction of how to use it?

Thanks in advance.
Dan

Question: I am stuck with an error “PHP Fatal error: Uncaught Error Class ZipArchive not found” in one of the opensource PHP application installed on our server. The server uses PHP 7.2 with Apache web server. Could you help me to fix this error?

Solution: Fix Class ZipArchive not found error

All you need is to install the ZipArchive package from the REMI repo for PHP 7.2 as shown below.

# yum-config-manager --enable remi-php72
# yum install php-pecl-zip

You may also search for the package using the below command and install the respective version.

# yum search zip | grep -i php

Restart apache web server as below:

# systemctl restart httpd

(or) In some versions of Apache.

# systemctl restart apache2

On Debian/Ubuntu:

# apt-get install php-zip
# phpenmod zip
# systemctl restart httpd

Понравилась статья? Поделить с друзьями:

Интересное по теме:

  • Php возврат ошибки 404
  • Php sqlite3 обработка ошибок
  • Php pdo показать ошибки
  • Php pdo вывод ошибок
  • Php вернуть ошибку 500

  • Добавить комментарий

    ;-) :| :x :twisted: :smile: :shock: :sad: :roll: :razz: :oops: :o :mrgreen: :lol: :idea: :grin: :evil: :cry: :cool: :arrow: :???: :?: :!: