Tuesday, March 3, 2009

PHP Extract / Unzip a Zip file by code

I came across a task where i had to unzip a zip folder on a server to a new directory path in PHP

For the code to work we need the PCLZip library.The PclLib is a free open source.

You can download the library from the PCLZip site

Steps for UnZip of files

//make a directory
// $target is the directory where you want to unzip the files
//$zipfile is the zipped file which has to be unzipped
@mkdir($target);
$path = $target;
$file = $zipfile;
// Use the library
require_once('pclzip.lib.php');
$archive = new PclZip($file);
if (($v_result_list = $archive->extract(PCLZIP_OPT_PATH, $path)) == 0)
{
die("Error : ".$archive->errorInfo(true));
}



-------------------------------------------------------------------------------------

PCLZip also supports error detection

Built in error function are
errorName() : Returns a string containing the name of the error.
errorCode() : Returns the error code value.
errorInfo() : Returns a description associated with the error.

Using the Traceable Library we can also trace our errors.
You can download the trace library seperately.

require_once('pcltrace.lib.php');
require_once('pclzip-trace.lib.php');

PclTraceOn(2);

$zip = new PclZip('test.zip');
$list = $zip->create("readme.txt");
if ($list == 0) {
PclTraceDisplay();
die("Error : ".$zip->errorInfo(true));
}

PclTraceDisplay();

?>

No comments:

Post a Comment

Express you views