Unzip a file with php

2019-01-01 02:22发布

问题:

I want to unzip a file and this works fine

system(\'unzip File.zip\');

But I need to pass in the file name through the URL and can not get it to work, this is what I have.

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

What am I missing? I know it has to be something small and stupid I am overlooking.

Thank you,

回答1:

I can only assume your code came from a tutorial somewhere online? In that case, good job trying to figure it out by yourself. On the other hand, the fact that this code could actually be published online somewhere as the correct way to unzip a file is a bit frightening.

PHP has built-in extensions for dealing with compressed files. There should be no need to use system calls for this. ZipArchivedocs is one option.

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

Also, as others have commented, $HTTP_GET_VARS has been deprecated since version 4.1 ... which was a reeeeeally long time ago. Don\'t use it. Use the $_GET superglobal instead.

Finally, be very careful about accepting whatever input is passed to a script via a $_GET variable.

ALWAYS SANITIZE USER INPUT.


UPDATE

As per your comment, the best way to extract the zip file into the same directory in which it resides is to determine the hard path to the file and extract it specifically to that location. So, you could do:

// 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\";
}


回答2:

Please, don\'t do it like that (passing GET var to be a part of a system call). Use ZipArchive instead.

So, your code should look like:

$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
}

And to answer your question, your error is \'something $var something else\' should be \"something $var something else\" (in double quotes).



回答3:

Simply try this yourDestinationDir is the destination to extract to or remove -d yourDestinationDir to extract to root dir.

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


回答4:

I updated answer of @rdlowrey to a cleaner and better code, This will unzip a file into current directory using __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> 


回答5:

Using getcwd() to extract in the same directory

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


回答6:

I updated answer of Morteza Ziaeemehr to a cleaner and better code, This will unzip a file provided within form into current directory using 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:

Just change

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

To this one

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

or this one

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



回答8:

you can use prepacked function

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;
}

How to use it.

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


回答9:

function extract_zip($Sourse_file, $extract_folder){
    $zip = new ZipArchive() ;
    if (!$zip->open($Sourse_file) == TRUE) {
        return false;
    }
    $zip->extractTo($extract_folder);
    $zip->close();
        return true;
}


回答10:

Use below PHP code, with file name in the URL param \"name\"

<?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\';
}

?>


回答11:

PHP has its own inbuilt class that can be used to unzip or extracts contents from a zip file. The class is ZipArchive. Below is the simple and basic PHP code that will extract a zip file and place it in a specific directory:

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

If you want some advance features then below is the improved code that will check if the zip file exists or not:

<?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\";
}
?>

Source: How to unzip or extract zip files in PHP?



回答12:

Just use this:

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

in your code $master is passed as a string, system will be looking for a file called $master.zip

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


标签: php unzip