简体   繁体   中英

Extract a Zip Archive using PHP

what i'm trying to do is to basically extract the contents of Zip archives on my server.Here is some code:

$entry="test.zip";

    $zip = new ZipArchive;

    if ($zip->open($entry,ZIPARCHIVE::OVERWRITE) === TRUE)
    {
        $zip->extractTo('unpacked');
        $zip->close();

     }else 
     {
        echo ‘failed’;

     }

the directory "unpacked" is writeable for everyone and all the used methods of the ZipArchive Class return true. However nothing is being extracted. Does anyone happen to have an idea what could cause this behaviour? Any hint will be highly appreciated...Thanks in advance!

If you are using PHP 5.2.0 or later can you check zlib extension first http://www.zlib.net/

You also check PECL extensions, In order to access ZipArchive, you can also try zip_open, zip_read just for checking.

In case of failure you should echo out $zip as it contains the error. Furthermore I'd guess that you may not have the needed permissions for test.zip

If this code is in-house, and you can safely make the assumption that you won't move this code from Linux to Windows (or vice versa), you also have the option to execute local system commands, which may help solve your problem.

<?php

echo `unzip myarchive.zip`; 
echo `tar -xzf myotherarchive.tar.gz`;

?>

When developing internal-use and/or maintenance scripts, I used to opt for straight-up system calls, as it was more in-line with the commands sysadmins were used to using.

If your zip archive is big, sometimes you cannot extract all files during the maximum allowed execution time of your server.

The only solution, if you cannot change the maximum_execution_time in your php.ini, is to use a javascript to extract one file after the other. On the first javascript request you take the number of files in the archive

$nbr_of_files = $zip->numFiles;

And after you extract one file after another using the id number in the zip archive for each file

$zip->extractTo('unpacked', array($zip->getNameIndex($file_nbr)));

Please try removing the ZIPARCHIVE::OVERWRITE flag from the ZipArchive open method. (The flag may not be functioning as expected and may be the root of the issue if you have followed the advice in the other answers.)

I had the same issue too. The solution:

$zip->extractTo(public_path() .'/restoreDb/extracted/');

add the public_path() helper function.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM