BostonBB BostonBB - 1 year ago 60
PHP Question

Unzip a file with php

I want to unzip a file and this works fine


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

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

Thank you,

Answer Source

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('');
if ($res === TRUE) {
  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.



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 is in the same directory as the executing script.
$file = '';

// 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
  echo "WOOT! $file extracted to $path";
} else {
  echo "Doh! I couldn't open $file";