Unzipping files using PHP

My colleage faced little problem today while transfering files to a server. The number of files were in the range of thousands, and we all know what a pain it is to ftp a large number of these small files ( Size wasn’t much of an issue compared to the overhead of commands).

Of course the logical solution was to zip everything up before uploading, but the real problem was the server does not have a file manager, nor does he have shell access.

So I wrote this little script for him:


<?php
	$inputPath = $_GET['in'];
	$outputPath = $_GET['out'].'/';
	$zip = new ZipArchive;
	$res = $zip->open($inputPath);
	if ($res === TRUE) {
		echo 'Read success';
		$zip->extractTo($outputPath);
		echo 'extracting to '.$outputPath.'';
		$zip->close();
		echo 'ok';
	} else {
		echo 'failed';
	}
?>

I called it unzip.php. Using it was real simple, just pass in the in and out parameters like this

unzip.php?in=file.zip&out=unzippedcontents

and there you have it, the contents of file.zip will be unzipped into the unzippedcontents directory. Of course a few conditions do apply:

  1. the php installation must have the zip module
  2. the output folder must have the correct write permissions.

Hope this helps if you find yourself facing the same problem next time.

p.s. Nope the code does not have any error checking so use it at your own risk xD and do not add trailing slashes to the output path!

Share