$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');
Related
I tried a lot of code, But not work.
<?php
$file = $_GET['file'];
if (isset($file))
{
echo "Unzipping " . $file . "<br>";
if(system('unzip '. $file.' -d dirtounzipto ' ))
{echo 'GGWP';}else{echo 'WTF';}
exit;
}?>
How can i unzip in server. with "system" or "shell_exec" code.
$zip_filename = "test.zip";
$zip_extract_path = "/";
try{
$zip_obj = new ZipArchive;
if (file_exists($zip_filename)) {
$zip_stat = $zip_obj->open($zip_filename);
if ($zip_stat === TRUE) {
$res = $zip_obj->extractTo($zip_extract_path);
if ($res === false) {
throw new Exception("Error in extracting file on server.");
}
$zip_obj->close();
} else {
throw new Exception("Error in open file");
}
} else {
throw new Exception("zip file not found for extraction");
}
}catch (Exception $e) {
echo $e->getMessage();
}
Please make good use of PHP's ZipArchive library:
<?php
$zip = new ZipArchive;
if ($zip->open('test.zip') === TRUE) {
$zip->extractTo('/my/destination/dir/');
$zip->close();
echo 'ok';
} else {
echo 'failed';
}
?>
Version requirement: PHP >= 5.2.0, PECL zip >= 1.1.0
UPDATE To create the destination path automatically, you can use:
mkdir($path, 0755, true);
which create the folders required automatically.
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.
// 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);
//folder name as per zip file name
$foldername = basename($file, ".zip");
mkdir($foldername, 0755, true);
$path = $path . "/" . $foldername;
$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";
}
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 :)
I'm in need of unziping uploaded content. But for security purposes must verify the files are only image files so that somebody can't add a php into the zip and then run it later.
While doing the unzip I need to preseverve the file structure as well.
$zip->extractTo($save_path . $file_name, array('*.jpg','*.jpeg','*.png','*.gif') );
doesn't return null. Is there a parameter I can use for this or must I iterate with a loop through the zip file using regex to match extensions and create the folders and save the files with code??
Thanks
from php.net, handling .txt files
<?php
$value="test.zip";
$filename="zip_files/$value";
$zip = new ZipArchive;
if ($zip->open($filename) === true) {
echo "Generating TEXT file.";
for($i = 0; $i < $zip->numFiles; $i++) {
$entry = $zip->getNameIndex($i);
if(preg_match('#\.(txt)$#i', $entry))
{
////This copy function will move the entry to the root of "txt_files" without creating any sub-folders unlike "ZIP->EXTRACTO" function.
copy('zip://'.dirname(__FILE__).'/zip_files/'.$value.'#'.$entry, 'txt_files/'.$value.'.txt');
}
}
$zip->close();
}
else{
echo "ZIP archive failed";
}
?>
for anyone who would need this in the future here is my solution. Thanks Ciro for the post, I only had to extend yours a bit. To make sure all folders are created I loop first for the folders and then do the extarction.
$ZipFileName = dirname(__FILE__)."/test.zip";
$home_folder = dirname(__FILE__)."/unziped";
mkdir($home_folder);
$zip = new ZipArchive;
if ($zip->open($ZipFileName ) === true)
{
//make all the folders
for($i = 0; $i < $zip->numFiles; $i++)
{
$OnlyFileName = $zip->getNameIndex($i);
$FullFileName = $zip->statIndex($i);
if ($FullFileName['name'][strlen($FullFileName['name'])-1] =="/")
{
#mkdir($home_folder."/".$FullFileName['name'],0700,true);
}
}
//unzip into the folders
for($i = 0; $i < $zip->numFiles; $i++)
{
$OnlyFileName = $zip->getNameIndex($i);
$FullFileName = $zip->statIndex($i);
if (!($FullFileName['name'][strlen($FullFileName['name'])-1] =="/"))
{
if (preg_match('#\.(jpg|jpeg|gif|png)$#i', $OnlyFileName))
{
copy('zip://'. $ZipFileName .'#'. $OnlyFileName , $home_folder."/".$FullFileName['name'] );
}
}
}
$zip->close();
} else
{
echo "Error: Can't open zip file";
}
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');
I'm searching for a good solution to read a zip file from an url with php.
I checked the zip_open() function, but i never read anything about reading the file from another server.
Thank you very much
The best way to do that is to copy the remote file in a temporary one:
$file = 'http://remote/url/file.zip';
$newfile = 'tmp_file.zip';
if (!copy($file, $newfile)) {
echo "failed to copy $file...\n";
}
Then, you can do whatever you want with the temporary file:
$zip = new ZipArchive();
if ($zip->open($newFile, ZIPARCHIVE::CREATE)!==TRUE) {
exit("cannot open <$filename>\n");
}
This is a basic example:
$url = 'https://my.domain.com/some_zip.zip?blah=1&hah=2';
$destination_dir = '/path/to/local/storage/directory/';
if (!is_dir($destination_dir)) {
mkdir($destination_dir, 0755, true);
}
$local_zip_file = basename(parse_url($url, PHP_URL_PATH)); // Will return only 'some_zip.zip'
if (!copy($url, $destination_dir . $local_zip_file)) {
die('Failed to copy Zip from ' . $url . ' to ' . ($destination_dir . $local_zip_file));
}
$zip = new ZipArchive();
if ($zip->open($destination_dir . $local_zip_file)) {
for ($i = 0; $i < $zip->numFiles; $i++) {
if ($zip->extractTo($destination_dir, array($zip->getNameIndex($i)))) {
echo 'File extracted to ' . $destination_dir . $zip->getNameIndex($i);
}
}
$zip->close();
// Clear zip from local storage:
unlink($destination_dir . $local_zip_file);
}
Download the file contents (possibly with file_get_contents, or copy to put it on your filesystem) then apply the unzip algorithm.