PHP上传和提取Zip

时间:2011-05-25 09:19:35

标签: php zip extract unzip

我正在尝试运行一个脚本,允许上传.zip并提取内容。我在网上抓了一个应该工作的示例代码并在开头用b / c添加了一个类,我的ISP没有正确编译的zip功能。

我在中间留下了一个很大的评论,我被卡住了。不确定这与它在IIS上运行有什么关系吗?

.zip文件会上传到我期望的位置,并且我可以手动将其恢复并提取文件。我想在这里提取文件,循环它们,如果它们是图像文件,然后将它们添加到图库图像数据库......首先要做的事情。需要理解为什么我没有看到拉链的内容......

<?php // need this bc of ISP settings
require($_SERVER['DOCUMENT_ROOT']."/_classes/ZipArchive.php");
?><?php
if($_FILES["zip_file"]["name"]) {
    $filename = $_FILES["zip_file"]["name"];
    $source = $_FILES["zip_file"]["tmp_name"];
    $type = $_FILES["zip_file"]["type"];

    $name = explode(".", $filename);
    $accepted_types = array('application/zip', 'application/x-zip-compressed', 'multipart/x-zip', 'application/x-compressed');
    foreach($accepted_types as $mime_type) {
         if($mime_type == $type) {
             $okay = true;
             break;
          } 
    }
    $continue = strtolower($name[1]) == 'zip' ? true : false;
    if(!$continue) {
        $message = "The file you are trying to upload is not a .zip file. Please try again.";
    }

    // I set up the _TEST dir with 777 permissions
    $target_path = $_SERVER['DOCUMENT_ROOT']."/_TEST/".$filename;
    if(move_uploaded_file($source, $target_path)) {
        $zip = new ZipArchive();
        $x = $zip->open($target_path);

        // **********************************************************
        // $x returns an error here
        // code: ER_OPEN
        // http://php.net/manual/en/function.ziparchive-open.php
        // Not sure why?????
        // **********************************************************

        if ($x === true) {
           $zip->extractTo($_SERVER['DOCUMENT_ROOT']."/_TEST/");
           $zip->close();
           unlink($target_path);
           $message = "Your .zip file was uploaded and unpacked.";
        }
        else {
           $message =  'failed';
        }
    } else {    
        $message = "There was a problem with the upload. Please try again.";
    }
}
?>

2 个答案:

答案 0 :(得分:1)

不是解决方案而是解决方法:您是否拥有对机器的控制权?如果是,请安装7-zip(在Windows上)或unzip,使用system('unzip ...')system('7z ...')解压缩zip存档。

答案 1 :(得分:0)

ISP为zip工作安装了必要的组件,所以一切都很顺利。感谢@timdream提供另一种方法。