Unzip a file with php

PhpUnzip

Php Problem Overview


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,

Php Solutions


Solution 1 - Php

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

Solution 2 - Php

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).

Solution 3 - Php

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

Solution 4 - Php

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>	

Solution 5 - Php

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');

Solution 6 - Php

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?

Solution 7 - Php

Simple PHP function to unzip. Please make sure you have zip extension installed on your server.

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

Solution 8 - Php

Just change

system('unzip $master.zip');

To this one

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

or this one

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

Solution 9 - Php

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> 

Solution 10 - Php

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

Solution 11 - Php

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

?>

Solution 12 - Php

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`

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionBostonBBView Question on Stackoverflow
Solution 1 - PhprdlowreyView Answer on Stackoverflow
Solution 2 - PhpAleksandar VuceticView Answer on Stackoverflow
Solution 3 - PhpRubyxView Answer on Stackoverflow
Solution 4 - PhpMortezaView Answer on Stackoverflow
Solution 5 - PhpSamuel Kwame AntwiView Answer on Stackoverflow
Solution 6 - PhpFaruque Ahamed MollickView Answer on Stackoverflow
Solution 7 - PhpM_R_KView Answer on Stackoverflow
Solution 8 - Phpsh4nn0nb1tView Answer on Stackoverflow
Solution 9 - PhpVarun NahariaView Answer on Stackoverflow
Solution 10 - Phpuser889030View Answer on Stackoverflow
Solution 11 - PhphuyncView Answer on Stackoverflow
Solution 12 - PhpDennis KiptugenView Answer on Stackoverflow