用php解压缩文件

时间:2012-01-17 02:38:32

标签: php unzip

我想解压缩一个文件,这很好用

system('unzip File.zip');

但是我需要通过URL传递文件名并且无法使其工作,这就是我所拥有的。

$master = $_GET["master"];
system('unzip $master.zip'); 

我错过了什么?我知道它必须是一个小而愚蠢的东西,我忽略了。

谢谢,

12 个答案:

答案 0 :(得分:446)

我只能假设您的代码来自某个在线教程?在那种情况下,努力想要自己解决这个问题。另一方面,这个代码实际上可以在某个地方在线发布作为解压缩文件的正确方法这一事实有点令人恐惧。

PHP具有用于处理压缩文件的内置扩展。我们不需要使用system来电。 ZipArchive docs是一种选择。

$zip = new ZipArchive;
$res = $zip->open('file.zip');
if ($res === TRUE) {
  $zip->extractTo('/myzips/extract_path/');
  $zip->close();
  echo 'woot!';
} else {
  echo 'doh!';
}

此外,正如其他人所评论的那样,自{4.1}版本以来,$HTTP_GET_VARS已经被弃用了......这是很久以前的事了。不要使用它。请改用$_GET超全局。

最后,要非常小心接受通过$_GET变量传递给脚本的任何输入。

始终保持SANITIZE用户输入。


<强>更新

根据您的评论,将zip文件解压缩到它所在的同一目录的最佳方法是确定文件的硬路径并将其专门提取到该位置。所以,你可以这样做:

// assuming file.zip is in the same directory as the executing script.
$file = 'file.zip';

// get the absolute path to $file
$path = pathinfo(realpath($file), PATHINFO_DIRNAME);

$zip = new ZipArchive;
$res = $zip->open($file);
if ($res === TRUE) {
  // extract it to the path we determined above
  $zip->extractTo($path);
  $zip->close();
  echo "WOOT! $file extracted to $path";
} else {
  echo "Doh! I couldn't open $file";
}

答案 1 :(得分:33)

请不要这样做(将GET var作为系统调用的一部分)。请改用ZipArchive

因此,您的代码应如下所示:

$zipArchive = new ZipArchive();
$result = $zipArchive->open($_GET["master"]);
if ($result === TRUE) {
    $zipArchive ->extractTo("my_dir");
    $zipArchive ->close();
    // Do something else on success
} else {
    // Do something on error
}

为了回答你的问题,你的错误是“$ var其他东西”应该是“$ var something something”(用双引号)。

答案 2 :(得分:5)

使用getcwd()在同一目录中提取

<?php
$unzip = new ZipArchive;
$out = $unzip->open('wordpress.zip');
if ($out === TRUE) {
  $unzip->extractTo(getcwd());
  $unzip->close();
  echo 'File unzipped';
} else {
  echo 'Error';
}
?>

答案 3 :(得分:4)

我将 @rdlowrey 的答案更新为更清晰,更好的代码,这将使用__DIR__将文件解压缩到当前目录。

<?php 
    // config
    // -------------------------------
    // only file name + .zip
    $zip_filename = "YOURFILENAME.zip";
?>

<!DOCTYPE html>
<html>
<head>
    <meta charset='utf-8' >
    <title>Unzip</title>
    <style>
        body{
            font-family: arial, sans-serif;
            word-wrap: break-word;
        }
        .wrapper{
            padding:20px;
            line-height: 1.5;
            font-size: 1rem;
        }
        span{
            font-family: 'Consolas', 'courier new', monospace;
            background: #eee;
            padding:2px;
        }
    </style>
</head>
<body>
    <div class="wrapper">
        <?php
        echo "Unzipping <span>" .__DIR__. "/" .$zip_filename. "</span> to <span>" .__DIR__. "</span><br>";
        echo "current dir: <span>" . __DIR__ . "</span><br>";
        $zip = new ZipArchive;
        $res = $zip->open(__DIR__ . '/' .$zip_filename);
        if ($res === TRUE) {
          $zip->extractTo(__DIR__);
          $zip->close();
          echo '<p style="color:#00C324;">Extract was successful! Enjoy ;)</p><br>';
        } else {
          echo '<p style="color:red;">Zip file not found!</p><br>';
        }
        ?>
        End Script.
    </div>
</body>
</html> 

答案 4 :(得分:4)

只需尝试 yourDestinationDir 即可提取或删除 -d yourDestinationDir 以提取到根目录。

$master = 'someDir/zipFileName';
$data = system('unzip -d yourDestinationDir '.$master.'.zip');

答案 5 :(得分:0)

只需更改

system('unzip $master.zip');

到这个

system('unzip ' . $master . '.zip');

或者这个

system("unzip {$master}.zip");

答案 6 :(得分:0)

我将Morteza Ziaeemehr的答案更新为更清晰,更好的代码,这将使用 DIR 将表单中提供的文件解压缩到当前目录中。

<!DOCTYPE html>
<html>
<head>
  <meta charset='utf-8' >
  <title>Unzip</title>
  <style>
  body{
    font-family: arial, sans-serif;
    word-wrap: break-word;
  }
  .wrapper{
    padding:20px;
    line-height: 1.5;
    font-size: 1rem;
  }
  span{
    font-family: 'Consolas', 'courier new', monospace;
    background: #eee;
    padding:2px;
  }
  </style>
</head>
<body>
  <div class="wrapper">
    <?php
    if(isset($_GET['page']))
    {
      $type = $_GET['page'];
      global $con;
      switch($type)
        {
            case 'unzip':
            {    
                $zip_filename =$_POST['filename'];
                echo "Unzipping <span>" .__DIR__. "/" .$zip_filename. "</span> to <span>" .__DIR__. "</span><br>";
                echo "current dir: <span>" . __DIR__ . "</span><br>";
                $zip = new ZipArchive;
                $res = $zip->open(__DIR__ . '/' .$zip_filename);
                if ($res === TRUE) 
                {
                    $zip->extractTo(__DIR__);
                    $zip->close();
                    echo '<p style="color:#00C324;">Extract was successful! Enjoy ;)</p><br>';
                } 
                else 
                {
                    echo '<p style="color:red;">Zip file not found!</p><br>';
                }
                break;
            }
        }
    }
?>
End Script.
</div>
    <form name="unzip" id="unzip" role="form">
        <div class="body bg-gray">
            <div class="form-group">
                <input type="text" name="filename" class="form-control" placeholder="File Name (with extension)"/>
            </div>        
        </div>
    </form>

<script type="application/javascript">
$("#unzip").submit(function(event) {
  event.preventDefault();
    var url = "function.php?page=unzip"; // the script where you handle the form input.
    $.ajax({
     type: "POST",
     url: url,
     dataType:"json",
           data: $("#unzip").serialize(), // serializes the form's elements.
           success: function(data)
           {
               alert(data.msg); // show response from the php script.
               document.getElementById("unzip").reset();
             }

           });

    return false; // avoid to execute the actual submit of the form
  });
</script>
</body>
</html> 

答案 7 :(得分:0)

您可以使用预先包装的功能

function unzip_file($file, $destination){
    // create object
    $zip = new ZipArchive() ;
    // open archive
    if ($zip->open($file) !== TRUE) {
        return false;
    }
    // extract contents to destination directory
    $zip->extractTo($destination);
    // close archive
    $zip->close();
        return true;
}

如何使用它。

if(unzip_file($file["name"],'uploads/')){
echo 'zip archive extracted successfully';
}else{
  echo 'zip archive extraction failed';
}

答案 8 :(得分:0)

使用以下PHP代码,文件名在URL参数&#34; name&#34;

<?php

$fileName = $_GET['name'];

if (isset($fileName)) {


    $zip = new ZipArchive;
    $res = $zip->open($fileName);
    if ($res === TRUE) {
      $zip->extractTo('./');
      $zip->close();
      echo 'Extracted file "'.$fileName.'"';
    } else {
      echo 'Cannot find the file name "'.$fileName.'" (the file name should include extension (.zip, ...))';
    }
}
else {
    echo 'Please set file name in the "name" param';
}

?>

答案 9 :(得分:0)

PHP有自己的内置类,可用于解压缩或从zip文件中提取内容。这个类是ZipArchive。 下面是简单和基本的PHP代码,它将提取zip文件并将其放在特定目录中:

<?php
$zip_obj = new ZipArchive;
$zip_obj->open('dummy.zip');
$zip_obj->extractTo('directory_name/sub_dir');
?>

如果你想要一些先进的功能,那么下面是改进的代码,它将检查zip文件是否存在:

<?php
$zip_obj = new ZipArchive;
if ($zip_obj->open('dummy.zip') === TRUE) {
   $zip_obj->extractTo('directory/sub_dir');
   echo "Zip exists and successfully extracted";
}
else {
   echo "This zip file does not exists";
}
?>

来源:How to unzip or extract zip files in PHP?

答案 10 :(得分:0)

用于解压缩的简单PHP函数。请确保您的服务器上安装了zip扩展名。

/**
 * Unzip
 * @param string $zip_file_path Eg - /tmp/my.zip
 * @param string $extract_path Eg - /tmp/new_dir_name
 * @return boolean
 */
function unzip(string $zip_file_path, string $extract_dir_path) {
    $zip = new \ZipArchive;
    $res = $zip->open($zip_file_path);
    if ($res === TRUE) {
        $zip->extractTo($extract_dir_path);
        $zip->close();
        return TRUE;
    } else {
        return FALSE;
    }
}

答案 11 :(得分:-2)

请使用:

  $master = $_GET["master"];
  system('unzip' $master.'.zip'); 
代码$master中的

作为字符串传递,系统将查找名为$master.zip的文件

  $master = $_GET["master"];
  system('unzip $master.zip'); `enter code here`