Extract sub folders of ZIP file in PHP - php

I am using a php script to unzip ZIP file. but this script unzip only one level of directories without extracting the sub directories of that file
the script:
$zip = new ZipArchive;
if ($zip->open('test.zip') === TRUE) {
$zip->extractTo('/my/destination/dir/');
$zip->close();
echo 'ok';
} else {
echo 'failed';
}
for example: if the test.zip contains 2 folders: folder1\file.png, folder2\folder3\file3.png
after extracting this ZIP file, i only see the folder1*.* and folder2*.* but without the sub directory folder3.
How can i improve it?

I think this PHP manual will be helpful to you
http://php.net/manual/en/ref.zip.php
<?php
$file = "2537c61ef7f47fc3ae919da08bcc1911.zip";
$dir = getcwd();
function Unzip($dir, $file, $destiny="")
{
$dir .= DIRECTORY_SEPARATOR;
$path_file = $dir . $file;
$zip = zip_open($path_file);
$_tmp = array();
$count=0;
if ($zip)
{
while ($zip_entry = zip_read($zip))
{
$_tmp[$count]["filename"] = zip_entry_name($zip_entry);
$_tmp[$count]["stored_filename"] = zip_entry_name($zip_entry);
$_tmp[$count]["size"] = zip_entry_filesize($zip_entry);
$_tmp[$count]["compressed_size"] = zip_entry_compressedsize($zip_entry);
$_tmp[$count]["mtime"] = "";
$_tmp[$count]["comment"] = "";
$_tmp[$count]["folder"] = dirname(zip_entry_name($zip_entry));
$_tmp[$count]["index"] = $count;
$_tmp[$count]["status"] = "ok";
$_tmp[$count]["method"] = zip_entry_compressionmethod($zip_entry);
if (zip_entry_open($zip, $zip_entry, "r"))
{
$buf = zip_entry_read($zip_entry, zip_entry_filesize($zip_entry));
if($destiny)
{
$path_file = str_replace("/",DIRECTORY_SEPARATOR, $destiny . zip_entry_name($zip_entry));
}
else
{
$path_file = str_replace("/",DIRECTORY_SEPARATOR, $dir . zip_entry_name($zip_entry));
}
$new_dir = dirname($path_file);
// Create Recursive Directory (if not exist)
if (!file_exists($new_dir)) {
mkdir($new_dir, 0700);
}
$fp = fopen($dir . zip_entry_name($zip_entry), "w");
fwrite($fp, $buf);
fclose($fp);
zip_entry_close($zip_entry);
}
echo "\n</pre>";
$count++;
}
zip_close($zip);
}
}
Unzip($dir,$file);
?>

This script extracts all files in the zip file recursively. This will extract them into the current directory.
<?php
set_time_limit(0);
echo "HI<br><br>";
//----------------
//UNZIP a zip file
//----------------
$zipfilename = "site.zip";
//----------------
function unzip($file){
$zip=zip_open(realpath(".")."/".$file);
if(!$zip) {return("Unable to proccess file '{$file}'");}
$e='';
while($zip_entry=zip_read($zip)) {
$zdir=dirname(zip_entry_name($zip_entry));
$zname=zip_entry_name($zip_entry);
if(!zip_entry_open($zip,$zip_entry,"r")) {$e.="Unable to proccess file '{$zname}'";continue;}
if(!is_dir($zdir)) mkdirr($zdir,0777);
#print "{$zdir} | {$zname} \n";
$zip_fs=zip_entry_filesize($zip_entry);
if(empty($zip_fs)) continue;
$zz=zip_entry_read($zip_entry,$zip_fs);
$z=fopen($zname,"w");
fwrite($z,$zz);
fclose($z);
zip_entry_close($zip_entry);
}
zip_close($zip);
return($e);
}
function mkdirr($pn,$mode=null) {
if(is_dir($pn)||empty($pn)) return true;
$pn=str_replace(array('/', ''),DIRECTORY_SEPARATOR,$pn);
if(is_file($pn)) {trigger_error('mkdirr() File exists', E_USER_WARNING);return false;}
$next_pathname=substr($pn,0,strrpos($pn,DIRECTORY_SEPARATOR));
if(mkdirr($next_pathname,$mode)) {if(!file_exists($pn)) {return mkdir($pn,$mode);} }
return false;
}
unzip($zipfilename);
?>

Try this simple way:
system('unzip my_zip_file.zip');

Related

PHP Create a Zip archive for file only particular extension

How to create Zip archive for file only particular extension in my case .TIF .JPG .TXT
currently i have added single extensions in code you can modify it later on.
<?php
/* creates a compressed zip file */
function create_zip($files = array(), $destination = '', $overwrite = false) {
//if the zip file already exists and overwrite is false, return false
if (file_exists($destination) && !$overwrite) {
return false;
}
//vars
$valid_files = array();
//if files were passed in...
if (is_array($files)) {
//cycle through each file
foreach ($files as $file) {
//make sure the file exists
if (file_exists($file)) {
$valid_files[] = $file;
}
}
}
//if we have good files...
if (count($valid_files)) {
//create the archive
$zip = new ZipArchive();
if ($zip->open($destination, $overwrite ? ZIPARCHIVE::OVERWRITE : ZIPARCHIVE::CREATE) !== true) {
return false;
}
//add the files
foreach ($valid_files as $file) {
$zip->addFile($file, $file);
}
//debug
//echo 'The zip archive contains ',$zip->numFiles,' files with a status of ',$zip->status;
//close the zip -- done!
$zip->close();
//check to make sure the file exists
return file_exists($destination);
} else {
return false;
}
}
//your directory path where all files are stored
$dir = 'D:\xampp\htdocs\samples\zip';
$files1 = scandir($dir, 1);
// $ext = "png"; //whatever extensions which you want to be in zip.
$ext = ['jpg','tif','TXT']; //whatever extensions which you want to be in zip.
$finalArray = array();
foreach ($files1 as $key => $value) {
$getExt = explode(".", $value);
if ( in_array($getExt[1] , $ext) ) {
$finalArray[$key] = $value;
}
}
$result = create_zip($finalArray, 'my-archive' . time() . '.zip');
if ($result) {
echo "Operation done.";
}
?>
i think this is what you want.
let me know if you have any issue.

How to unzip subdirectory and files from a zip file using php

I am trying to unzip all subdirectory and files from a zip file.
Folder Structure
A folder
B1 folder (in b1 folder) C1 folder - C2 file
B2 file
A1 file
Below my tried codes
Try 1
functio unZip($source, $destiny) {
$zip = zip_open($source);
if ($zip) {
while ($zip_entry = zip_read($zip)) {
$fp = fopen("zip/" . zip_entry_name($zip_entry), 'w');
if (zip_entry_open($zip, $zip_entry, 'r')) {
$buf = zip_entry_read($zip_entry, zip_entry_filesize($zip_entry));
fwrite($fp, "$buf");
zip_entry_close($zip_entry);
fclose($fp);
}
}
zip_close($zip);
}
}
Try 2
function unZip($source, $destiny) {
$zips = new ZipArchive;
if($zips->open($source) == TRUE){
$zips->extractTo($destiny);
$zips->close();
echo 'ok';
} else {
echo 'fail';
}
}
Try 3
function unZip($path_file, $destiny) {
if (!file_exists($destiny)) {
mkdir($destiny);
}
$zips = zip_open($path_file);
if ($zips) {
while ($zips_entry = zip_read($zips)) {
$zips_entry_name = str_replace('\\', '/', zip_entry_name($zips_entry));
$file_open = fopen($destiny, 'w');
if (zip_entry_open($zips, $zips_entry, 'w')) {
$buf = zip_entry_read($zips_entry, zip_entry_filesize($zips_entry));
fwrite($file_open, $buf);
zip_entry_close($zips_entry);
fclose($file_open);
}
}
zip_close($zips);
}
}
Error
Warning: fopen(). failed to open stream: Invalid argument

PHP extract zip [duplicate]

This question already has answers here:
Unzip a file with php
(12 answers)
Closed 8 years ago.
I have a zip file with some files and folders inside, and I want to extract the contents of the folder "/files" from the zip file to the a specified path (the root path of my application).
If there is a non existing folder it should just be created.
So for example if the path inside the zip is: "/files/includes/test.class.php" it should be extracted to
$path . "/includes/test.class.php"
How can I do this?
The only function i found to switch inside the zip file should be
http://www.php.net/manual/en/ziparchive.getstream.php
but i actually don't know how i can do that with this function.
Try this:
$zip = new ZipArchive;
$archiveName = 'test.zip';
$destination = $path . '/includes/';
$pattern = '#^files/includes/(.)+#';
$patternReplace = '#^files/includes/#';
function makeStructure($entry, $destination, $patternReplace)
{
$entry = preg_replace($patternReplace, '', $entry);
$parts = explode(DIRECTORY_SEPARATOR, $entry);
$dirArray = array_slice($parts, 0, sizeof($parts) - 1);
$dir = $destination . join(DIRECTORY_SEPARATOR, $dirArray);
if (!file_exists($dir)) {
mkdir($dir, 0777, true);
}
if ($dir !== $destination) {
$dir .= DIRECTORY_SEPARATOR;
}
$fileExtension = pathinfo($entry, PATHINFO_EXTENSION);
if (!empty($fileExtension)) {
$fileName = $dir . pathinfo($entry, PATHINFO_BASENAME);
return $fileName;
}
return null;
}
if ($zip->open($archiveName) === true) {
for ($i = 0; $i < $zip->numFiles; $i++) {
$entry = $zip->getNameIndex($i);
if (preg_match($pattern, $entry)) {
$file = makeStructure($entry, $destination, $patternReplace);
if ($file === null) {
continue;
}
copy('zip://' . $archiveName . '#' . $entry, $file);
}
}
$zip->close();
}
I think you need zziplib extension for this to work
$zip = new ZipArchive;
if ($zip->open('your zip file') === TRUE) {
//create folder if does not exist
if (!is_dir('path/to/directory')) {
mkdir('path/to/directory');
}
//then extract the zip
$zip->extractTo('destination to which zip is to be extracted');
$zip->close();
echo 'Zip successfully extracted.';
} else {
echo 'An error occured while extracting.';
}
Read this link for more info http://www.php.net/manual/en/ziparchive.extractto.php
Hope this helps :)

zip generating function generating blank files

I am using this function to generate zip files:
function create_zip($files = array(),$destination = '',$overwrite = false) {
//if the zip file already exists and overwrite is false, return false
if(file_exists($destination) && !$overwrite) { return false; }
//vars
$valid_files = array();
//if files were passed in...
if(is_array($files)) {
//cycle through each file
foreach($files as $file) {
//make sure the file exists
if(file_exists($file)) {
$valid_files[] = $file;
}
}
}
//if we have good files...
if(count($valid_files)) {
//create the archive
$zip = new ZipArchive();
if($zip->open($destination,$overwrite ? ZIPARCHIVE::OVERWRITE : ZIPARCHIVE::CREATE) !== true) {
return false;
}
//add the files
foreach($valid_files as $file) {
$zip->addFile($file,$file);
//echo $file;
}
//debug
//echo 'The zip archive contains ',$zip->numFiles,' files with a status of ',$zip->status;
//close the zip -- done!
$zip->close();
//check to make sure the file exists
echo $destination;
return file_exists($destination);
}
else
{
return false;
}
}
I am using this to zip a vanilla, unaltered Wordpress install.(http://wordpress.org/) However for some reason the wp-content folder is having a 'ghost' empty file generated with it's name. The folder (and everything else) itself compresses correctly, but most unzip applications (including php's own extractTo()) break when they reach this unwanted file due to the name conflict.
I've looked into the folder/file structure and as far as I can see the only difference of note between this and the other folders in the site is that it is the biggest at 5.86 mb.
Can anyone suggest a fix / workaround?
This is the sample example to zip a folder.
<?php
function Create_zipArch($archive_name, $archive_folder)
{
$zip = new ZipArchive;
if ($zip->open($archive_name, ZipArchive::CREATE) === TRUE)
{
$dir = preg_replace('/[\/]{2,}/', '/', $archive_folder . "/");
$dirs = array($dir);
while (count($dirs))
{
$dir = current($dirs);
$zip->addEmptyDir($dir);
$dh = opendir($dir);
while ($file = readdir($dh))
{
if ($file != '.' && $file != '..')
{
if (is_file($file))
$zip->addFile($dir . $file, $dir . $file);
elseif (is_dir($file))
$dirs[] = $dir . $file . "/";
}
}
closedir($dh);
array_shift($dirs);
}
$zip->close();
$result='success';
}
else
{
$result='failed';
}
return $result;
}
$zipArchName = "ZipFileName.zip"; // zip file name
$FolderToZip = "zipthisfolder"; // folder to zip
echo Create_zipArch($zipArchName, $FolderToZip);
?>

Unzip the file using php (collapses the ZIP file into one Folder)

$file_name = 'New Folder.zip'
$zip = new ZipArchive;
$result = $zip->open($target_path.$file_name);
if ($result === TRUE) {
for($i = 0; $i < $zip->numFiles; $i++) {
$filename = $zip->getNameIndex($i);
$fileinfo = pathinfo($filename);
copy("zip://".$file_name."#".$filename, $target_path.$fileinfo['basename']);
}
}
When i run this code i get this error Warning: copy(zip://New Folder.zip#New Folder/icon_android.png) [function.copy]: failed to open stream: operation failed in...
How can I solve this...
From PHP's doc
$zip = new ZipArchive;
if ($zip->open('test.zip') === TRUE) {
$zip->extractTo($your_desired_dir);
$zip->close();
foreach (glob($your_desired_dir . DIRECTORY_SEPARATOR . 'New Folder') as $file) {
$finfo = pathinfo($file);
rename($file, $your_desired_dir . DIRECTORY_SEPARATOR . $finfo['basename']);
}
unlink($your_desired_dir . DIRECTORY_SEPARATOR . 'New Folder');
echo 'ok';
} else {
echo 'failed';
}
Dunno why are you using stream.
copy("zip://".$file_name."#".$filename, $target_path.$fileinfo['basename']);}
correct to
copy("zip://".dirname(__FILE__).'/'.$file_name."#".$filename, $target_path.$fileinfo['basename']);}
Full path need to use zip:// stream
see manual http://php.net/manual/en/book.zip.php
unzip.php (sample code)
// the first argument is the zip file
$in_file = $_SERVER['argv'][1];
// any other arguments are specific files in the archive to unzip
if ($_SERVER['argc'] > 2) {
$all_files = 0;
for ($i = 2; $i < $_SERVER['argc']; $i++) {
$out_files[$_SERVER['argv'][$i]] = true;
}
} else {
// if no other files are specified, unzip all files
$all_files = true;
}
$z = zip_open($in_file) or die("can't open $in_file: $php_errormsg");
while ($entry = zip_read($z)) {
$entry_name = zip_entry_name($entry);
// check if all files should be unzipped, or the name of
// this file is on the list of specific files to unzip
if ($all_files || $out_files[$entry_name]) {
// only proceed if the file is not 0 bytes long
if (zip_entry_filesize($entry)) {
$dir = dirname($entry_name);
// make all necessary directories in the file's path
if (! is_dir($dir)) { pc_mkdir_parents($dir); }
$file = basename($entry_name);
if (zip_entry_open($z,$entry)) {
if ($fh = fopen($dir.'/'.$file,'w')) {
// write the entire file
fwrite($fh,
zip_entry_read($entry,zip_entry_filesize($entry)))
or error_log("can't write: $php_errormsg");
fclose($fh) or error_log("can't close: $php_errormsg");
} else {
error_log("can't open $dir/$file: $php_errormsg");
}
zip_entry_close($entry);
} else {
error_log("can't open entry $entry_name: $php_errormsg");
}
}
}
}
from http://www.java-samples.com/showtutorial.php?tutorialid=985
First thing I would do is this:
echo "FROM - zip://".$file_name."#".$filename;
echo "<BR>TO - " . $target_path.$fileinfo['basename'];
and see what you get
I have used very simple method to do this
system('unzip assets_04_02_2015.zip');

Categories