如何在php中解压缩zip文件[重复]

时间:2023-01-24 11:33:03

This question already has an answer here:

这个问题在这里已有答案:

My gallery script provides me with the option to upload a bunch of images through a zip file. When I try to do this I receive the error line: Fatal error: Call to undefined function: zip_open() in ..

我的图库脚本为我提供了通过zip文件上传一堆图像的选项。当我尝试这样做时,我收到错误行:致命错误:调用未定义的函数:zip_open()in ..

Heres an extract of the phpinfo:

这是phpinfo的摘录:

ZLib Support: enabled Compiled Version: 1.1.4 Linked Version: 1.1.4

ZLib支持:已启用编译版本:1.1.4链接版本:1.1.4

zlib.output_compression: Off zlib.output_compression_level: -1 zlib.output_handler: no value

zlib.output_compression:关闭zlib.output_compression_level:-1 zlib.output_handler:没有值

Zlib is enabled .. so why do I receive that error message? Thank you for helping me.

Zlib已启用..那么为什么我会收到该错误消息?感谢你们对我的帮助。

3 个解决方案

#1


32  

Very simple code to extract a zip file.

非常简单的代码来提取zip文件。

$zip = new ZipArchive;
$zip->open('myfile.zip');
$zip->extractTo('./');
$zip->close();

#2


5  

Zip support in PHP is not enabled by default. You need to use the ZZIPlib library and the --with-zip=[DIR] option when compiling php.

默认情况下不启用PHP中的Zip支持。在编译php时,您需要使用ZZIPlib库和--with-zip = [DIR]选项。

http://www.php.net/manual/en/ref.zip.php

If you can't install ZZIPLib, you could use a zip class alternative. Just an example (not written by me):

如果您无法安装ZZIPLib,则可以使用zip类替代方案。只是一个例子(不是我写的):

<?php

class zipfile
{
    /*
        zipfile class, for reading or writing .zip files
        See http://www.gamingg.net for more of my work
        Based on tutorial given by John Coggeshall at http://www.zend.com/zend/spotlight/creating-zip-files3.php
        Copyright (C) Joshua Townsend and licensed under the GPL
        Version 1.0
    */
    var $datasec = array(); // array to store compressed data
    var $files = array(); // array of uncompressed files
    var $dirs = array(); // array of directories that have been created already
    var $ctrl_dir = array(); // central directory
    var $eof_ctrl_dir = "\x50\x4b\x05\x06\x00\x00\x00\x00"; //end of Central directory record
    var $old_offset = 0;
    var $basedir = ".";




    function read_zip($name)
    {
        // Clear current file
        $this->datasec = array();

        // File information
        $this->name = $name;
        $this->mtime = filemtime($name);
        $this->size = filesize($name);

        // Read file
        $fh = fopen($name, "rb");
        $filedata = fread($fh, $this->size);
        fclose($fh);

        // Break into sections
        $filesecta = explode("\x50\x4b\x05\x06", $filedata);

        // ZIP Comment
        $unpackeda = unpack('x16/v1length', $filesecta[1]);
        $this->comment = substr($filesecta[1], 18, $unpackeda['length']);
        $this->comment = str_replace(array("\r\n", "\r"), "\n", $this->comment); // CR + LF and CR -> LF

        // Cut entries from the central directory
        $filesecta = explode("\x50\x4b\x01\x02", $filedata);
        $filesecta = explode("\x50\x4b\x03\x04", $filesecta[0]);
        array_shift($filesecta); // Removes empty entry/signature

        foreach($filesecta as $filedata)
        {
            // CRC:crc, FD:file date, FT: file time, CM: compression method, GPF: general purpose flag, VN: version needed, CS: compressed size, UCS: uncompressed size, FNL: filename length
            $entrya = array();
            $entrya['error'] = "";

            $unpackeda = unpack("v1version/v1general_purpose/v1compress_method/v1file_time/v1file_date/V1crc/V1size_compressed/V1size_uncompressed/v1filename_length", $filedata);

            // Check for encryption
            $isencrypted = (($unpackeda['general_purpose'] & 0x0001) ? true : false);

            // Check for value block after compressed data
            if($unpackeda['general_purpose'] & 0x0008)
            {
                $unpackeda2 = unpack("V1crc/V1size_compressed/V1size_uncompressed", substr($filedata, -12));

                $unpackeda['crc'] = $unpackeda2['crc'];
                $unpackeda['size_compressed'] = $unpackeda2['size_uncompressed'];
                $unpackeda['size_uncompressed'] = $unpackeda2['size_uncompressed'];

                unset($unpackeda2);
            }

            $entrya['name'] = substr($filedata, 26, $unpackeda['filename_length']);

            if(substr($entrya['name'], -1) == "/") // skip directories
            {
                continue;
            }

            $entrya['dir'] = dirname($entrya['name']);
            $entrya['dir'] = ($entrya['dir'] == "." ? "" : $entrya['dir']);
            $entrya['name'] = basename($entrya['name']);


            $filedata = substr($filedata, 26 + $unpackeda['filename_length']);

            if(strlen($filedata) != $unpackeda['size_compressed'])
            {
                $entrya['error'] = "Compressed size is not equal to the value given in header.";
            }

            if($isencrypted)
            {
                $entrya['error'] = "Encryption is not supported.";
            }
            else
            {
                switch($unpackeda['compress_method'])
                {
                    case 0: // Stored
                        // Not compressed, continue
                    break;
                    case 8: // Deflated
                        $filedata = gzinflate($filedata);
                    break;
                    case 12: // BZIP2
                        if(!extension_loaded("bz2"))
                        {
                            @dl((strtolower(substr(PHP_OS, 0, 3)) == "win") ? "php_bz2.dll" : "bz2.so");
                        }

                        if(extension_loaded("bz2"))
                        {
                            $filedata = bzdecompress($filedata);
                        }
                        else
                        {
                            $entrya['error'] = "Required BZIP2 Extension not available.";
                        }
                    break;
                    default:
                        $entrya['error'] = "Compression method ({$unpackeda['compress_method']}) not supported.";
                }

                if(!$entrya['error'])
                {
                    if($filedata === false)
                    {
                        $entrya['error'] = "Decompression failed.";
                    }
                    elseif(strlen($filedata) != $unpackeda['size_uncompressed'])
                    {
                        $entrya['error'] = "File size is not equal to the value given in header.";
                    }
                    elseif(crc32($filedata) != $unpackeda['crc'])
                    {
                        $entrya['error'] = "CRC32 checksum is not equal to the value given in header.";
                    }
                }

                $entrya['filemtime'] = mktime(($unpackeda['file_time']  & 0xf800) >> 11,($unpackeda['file_time']  & 0x07e0) >>  5, ($unpackeda['file_time']  & 0x001f) <<  1, ($unpackeda['file_date']  & 0x01e0) >>  5, ($unpackeda['file_date']  & 0x001f), (($unpackeda['file_date'] & 0xfe00) >>  9) + 1980);
                $entrya['data'] = $filedata;
            }

            $this->files[] = $entrya;
        }

        return $this->files;
    }

}
?>

And use it like:

并使用它像:

<?php

include 'class.zip.php';

$file = 'file.zip';

$zip = new zipfile();
$content = array();

foreach ($zip->read_zip($file) AS $filedata)
{
    $content[] = end(explode('.', $filedata['name']));
}

echo implode(', ', $content);

?>

#3


1  

I Use this code to extract files of a zip archive.

我使用此代码提取zip存档的文件。

$zip = new ZipArchive;
if($zip->open($zipname))
{
  for($i=0; $i<$zip->numFiles; $i++)
  {
    echo 'Filename: '.$zip->getNameIndex($i).'<br />';
      }

  if($zip->extractTo(dirname(__FILE__).'/extracted/')){ echo '<p>FILE EXTRACTED</p>'; }else{ echo '<p>ERROR IN FILE ECTRACTING!</p>'; }

  $zip->close();
} 
else 
{
  echo 'Error reading zip-archive!';
}

#1


32  

Very simple code to extract a zip file.

非常简单的代码来提取zip文件。

$zip = new ZipArchive;
$zip->open('myfile.zip');
$zip->extractTo('./');
$zip->close();

#2


5  

Zip support in PHP is not enabled by default. You need to use the ZZIPlib library and the --with-zip=[DIR] option when compiling php.

默认情况下不启用PHP中的Zip支持。在编译php时,您需要使用ZZIPlib库和--with-zip = [DIR]选项。

http://www.php.net/manual/en/ref.zip.php

If you can't install ZZIPLib, you could use a zip class alternative. Just an example (not written by me):

如果您无法安装ZZIPLib,则可以使用zip类替代方案。只是一个例子(不是我写的):

<?php

class zipfile
{
    /*
        zipfile class, for reading or writing .zip files
        See http://www.gamingg.net for more of my work
        Based on tutorial given by John Coggeshall at http://www.zend.com/zend/spotlight/creating-zip-files3.php
        Copyright (C) Joshua Townsend and licensed under the GPL
        Version 1.0
    */
    var $datasec = array(); // array to store compressed data
    var $files = array(); // array of uncompressed files
    var $dirs = array(); // array of directories that have been created already
    var $ctrl_dir = array(); // central directory
    var $eof_ctrl_dir = "\x50\x4b\x05\x06\x00\x00\x00\x00"; //end of Central directory record
    var $old_offset = 0;
    var $basedir = ".";




    function read_zip($name)
    {
        // Clear current file
        $this->datasec = array();

        // File information
        $this->name = $name;
        $this->mtime = filemtime($name);
        $this->size = filesize($name);

        // Read file
        $fh = fopen($name, "rb");
        $filedata = fread($fh, $this->size);
        fclose($fh);

        // Break into sections
        $filesecta = explode("\x50\x4b\x05\x06", $filedata);

        // ZIP Comment
        $unpackeda = unpack('x16/v1length', $filesecta[1]);
        $this->comment = substr($filesecta[1], 18, $unpackeda['length']);
        $this->comment = str_replace(array("\r\n", "\r"), "\n", $this->comment); // CR + LF and CR -> LF

        // Cut entries from the central directory
        $filesecta = explode("\x50\x4b\x01\x02", $filedata);
        $filesecta = explode("\x50\x4b\x03\x04", $filesecta[0]);
        array_shift($filesecta); // Removes empty entry/signature

        foreach($filesecta as $filedata)
        {
            // CRC:crc, FD:file date, FT: file time, CM: compression method, GPF: general purpose flag, VN: version needed, CS: compressed size, UCS: uncompressed size, FNL: filename length
            $entrya = array();
            $entrya['error'] = "";

            $unpackeda = unpack("v1version/v1general_purpose/v1compress_method/v1file_time/v1file_date/V1crc/V1size_compressed/V1size_uncompressed/v1filename_length", $filedata);

            // Check for encryption
            $isencrypted = (($unpackeda['general_purpose'] & 0x0001) ? true : false);

            // Check for value block after compressed data
            if($unpackeda['general_purpose'] & 0x0008)
            {
                $unpackeda2 = unpack("V1crc/V1size_compressed/V1size_uncompressed", substr($filedata, -12));

                $unpackeda['crc'] = $unpackeda2['crc'];
                $unpackeda['size_compressed'] = $unpackeda2['size_uncompressed'];
                $unpackeda['size_uncompressed'] = $unpackeda2['size_uncompressed'];

                unset($unpackeda2);
            }

            $entrya['name'] = substr($filedata, 26, $unpackeda['filename_length']);

            if(substr($entrya['name'], -1) == "/") // skip directories
            {
                continue;
            }

            $entrya['dir'] = dirname($entrya['name']);
            $entrya['dir'] = ($entrya['dir'] == "." ? "" : $entrya['dir']);
            $entrya['name'] = basename($entrya['name']);


            $filedata = substr($filedata, 26 + $unpackeda['filename_length']);

            if(strlen($filedata) != $unpackeda['size_compressed'])
            {
                $entrya['error'] = "Compressed size is not equal to the value given in header.";
            }

            if($isencrypted)
            {
                $entrya['error'] = "Encryption is not supported.";
            }
            else
            {
                switch($unpackeda['compress_method'])
                {
                    case 0: // Stored
                        // Not compressed, continue
                    break;
                    case 8: // Deflated
                        $filedata = gzinflate($filedata);
                    break;
                    case 12: // BZIP2
                        if(!extension_loaded("bz2"))
                        {
                            @dl((strtolower(substr(PHP_OS, 0, 3)) == "win") ? "php_bz2.dll" : "bz2.so");
                        }

                        if(extension_loaded("bz2"))
                        {
                            $filedata = bzdecompress($filedata);
                        }
                        else
                        {
                            $entrya['error'] = "Required BZIP2 Extension not available.";
                        }
                    break;
                    default:
                        $entrya['error'] = "Compression method ({$unpackeda['compress_method']}) not supported.";
                }

                if(!$entrya['error'])
                {
                    if($filedata === false)
                    {
                        $entrya['error'] = "Decompression failed.";
                    }
                    elseif(strlen($filedata) != $unpackeda['size_uncompressed'])
                    {
                        $entrya['error'] = "File size is not equal to the value given in header.";
                    }
                    elseif(crc32($filedata) != $unpackeda['crc'])
                    {
                        $entrya['error'] = "CRC32 checksum is not equal to the value given in header.";
                    }
                }

                $entrya['filemtime'] = mktime(($unpackeda['file_time']  & 0xf800) >> 11,($unpackeda['file_time']  & 0x07e0) >>  5, ($unpackeda['file_time']  & 0x001f) <<  1, ($unpackeda['file_date']  & 0x01e0) >>  5, ($unpackeda['file_date']  & 0x001f), (($unpackeda['file_date'] & 0xfe00) >>  9) + 1980);
                $entrya['data'] = $filedata;
            }

            $this->files[] = $entrya;
        }

        return $this->files;
    }

}
?>

And use it like:

并使用它像:

<?php

include 'class.zip.php';

$file = 'file.zip';

$zip = new zipfile();
$content = array();

foreach ($zip->read_zip($file) AS $filedata)
{
    $content[] = end(explode('.', $filedata['name']));
}

echo implode(', ', $content);

?>

#3


1  

I Use this code to extract files of a zip archive.

我使用此代码提取zip存档的文件。

$zip = new ZipArchive;
if($zip->open($zipname))
{
  for($i=0; $i<$zip->numFiles; $i++)
  {
    echo 'Filename: '.$zip->getNameIndex($i).'<br />';
      }

  if($zip->extractTo(dirname(__FILE__).'/extracted/')){ echo '<p>FILE EXTRACTED</p>'; }else{ echo '<p>ERROR IN FILE ECTRACTING!</p>'; }

  $zip->close();
} 
else 
{
  echo 'Error reading zip-archive!';
}