How to unzip file in server(linux) with php code - php

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";
}

Related

Solution for php ZipArchieve Error code 9

I am trying to make zip with help of the below code. It works fine in my localhost. But when I transfer it to DirectAdmin server, It returns error code 9 ZipArchive::ER_NOENT : return 'N No such file';
I don't know how to fix it to create zip
define('ABSPATH', dirname(__FILE__) . '/' );
$dest = ABSPATH.'zip_file_name.zip';
$file = ABSPATH.'test.php';
$zip = new ZipArchive;
$res = $zip->open($dest, ZIPARCHIVE::OVERWRITE);
if ($res === TRUE) {
echo 'ok';
$zip->addFile($file, $file);
$zip->close();
} else {
echo 'failed, code:' . $res;
}
Tested your script on localhost (Windows). I get the error message "failed, code:9".
#see http://php.net/manual/en/ziparchive.open.php and search for "ZipArchive::ER_NOENT".
I think you need to create the zip file.
When i add ZipArchive::CREATE it works (Output "ok"):
define('ABSPATH', dirname(__FILE__) . '/' );
$dest = ABSPATH.'zip_file_name.zip';
$file = ABSPATH.'test.php';
$zip = new ZipArchive;
$res = $zip->open($dest, ZipArchive::CREATE | ZIPARCHIVE::OVERWRITE);
if ($res === TRUE) {
echo 'ok';
$zip->addFile($file, $file);
$zip->close();
} else {
echo 'failed, code:' . $res;
}
-- UPDATE --
The file test.php inside zip_file_name.zip has the full windows path. There is a directory "C:" inside the the zip file on root level (Windows environment). Is this correct?
In case you dont want absolute path you can use relative path:
define('ABSPATH', dirname(__FILE__) . '/' );
$dest = ABSPATH.'zip_file_name.zip';
$relativeFile = 'test.php';
$absoluteFile = ABSPATH.$relativeFile;
$zip = new ZipArchive;
$res = $zip->open($dest, ZipArchive::CREATE | ZIPARCHIVE::OVERWRITE);
if ($res === TRUE) {
echo 'ok';
$zip->addFile($absoluteFile, $relativeFile);
$zip->close();
} else {
echo 'failed, code:' . $res;
}

How to create compressed file using PHP with destination directory?

I found the script below from previous posts to create a ZIP file using PHP.
This script lets you create a zip file, but it doesn't let you create it in any directory you want. This is the original code.
<?php
// Config Vars
$sourcefolder = "uploads/output" ; // Default: "./"
$zipfilename = "myarchive.zip"; // Default: "myarchive.zip"
$timeout = 5000 ; // Default: 5000
// instantate an iterator (before creating the zip archive, just
// in case the zip file is created inside the source folder)
// and traverse the directory to get the file list.
$dirlist = new RecursiveDirectoryIterator($sourcefolder);
$filelist = new RecursiveIteratorIterator($dirlist);
// set script timeout value
ini_set('max_execution_time', $timeout);
// instantate object
$zip = new ZipArchive();
// create and open the archive
if ($zip->open("$zipfilename", ZipArchive::CREATE) !== TRUE) {
die ("Could not open archive");
}
// add each file in the file list to the archive
foreach ($filelist as $key=>$value) {
$zip->addFile(realpath($key), $key) or die ("ERROR: Could not add file: $key");
}
// close the archive
$zip->close();
echo "<br>Archive ". $zipfilename . " created successfully - ";
// And provide download link ?>
Download <?php echo $zipfilename?>
I tried amending the code to be able to decide the desitnation of the script as I found no solution after spending a couple of hours on the internet. Some solutions suggested where to change $zipfilename = "myarchive.zip"; to $zipfilename = "uploads/output/myarchive.zip"; but in the URL to download link I want to appear as: Archive myarchive.zip created successfully - Download myarchive.zip not as Archive uploads/output/myarchive.zip created successfully - Download myarchive.zip
Therefore I tried this code, but it didn't work for me. I don't know what I did wrong.
<?php
// Config Vars
$sourcefolder = "uploads/output" ; // Default: "./"
$destfolder = "uploads/output/"; // Default: "myarchive.zip"
$zipfilename = "myarchive.zip"; // Default: "myarchive.zip"
$timeout = 5000 ; // Default: 5000
// instantate an iterator (before creating the zip archive, just
// in case the zip file is created inside the source folder)
// and traverse the directory to get the file list.
$dirlist = new RecursiveDirectoryIterator($sourcefolder);
$filelist = new RecursiveIteratorIterator($dirlist);
// set script timeout value
ini_set('max_execution_time', $timeout);
// instantate object
$zip = new ZipArchive();
// create and open the archive
if ($zip->open(''.$destfolder.''.$zipfilename.'', ZipArchive::CREATE) !== TRUE) {
die ("Could not open archive");
}
// add each file in the file list to the archive
foreach ($filelist as $key=>$value) {
$zip->addFile(realpath($key), $key) or die ("ERROR: Could not add file: $key");
}
// close the archive
$zip->close();
echo "<br>Archive ". $zipfilename . " created successfully - ";
// And provide download link ?>
Download <?php echo $zipfilename?>
Example static method to create zip archive:
//...
public static function zip($source, $destination)
{
if (!extension_loaded('zip') || !file_exists($source)) {
throw new \Exception('zip not loaded');
}
$zip = new \ZipArchive();
if ($zip->open($destination, \ZIPARCHIVE::CREATE) === false) {
return false;
}
if (is_dir($source) === true) {
$files = new \RecursiveIteratorIterator(
new \RecursiveDirectoryIterator($source),
\RecursiveIteratorIterator::SELF_FIRST
);
foreach ($files as $file) {
if (in_array(substr($file, strrpos($file, DIRECTORY_SEPARATOR) + 1), array('.', '..'))) {
continue;
}
$file = realpath($file);
if (is_dir($file) === true) {
$zip->addEmptyDir(str_replace($source . DIRECTORY_SEPARATOR, '', $file . DIRECTORY_SEPARATOR));
} else {
if (is_file($file) === true) {
$zip->addFromString(
str_replace($source . DIRECTORY_SEPARATOR, '', $file),
file_get_contents($file)
);
}
}
}
} else {
if (is_file($source) === true) {
$zip->addFromString(basename($source), file_get_contents($source));
}
}
return $zip->close();
}
// ...

PHP ZipArchive::open won't create a zip file

I can't make ZipArchive create a zip file, but it won't give me any errors except for returning False on $zip->close();
I'm trying to create a zip archive in a directory a couple down from the one in which the operations are taking place.
$file_name = 'example.txt'; // or whatever, I'm including a few
$zip = new ZipArchive();
$path = getcwd() . '/output/run1/';
$zip_name = 'files_run1.zip';
$zip_p_name = $path . $zip_name;
$res = $zip->open($zip_p_name, ZIPARCHIVE::CREATE);
if (!($res ===TRUE)) echo 'failed, code:'.$res;
else
{
if (file_exists($zip_path . '/' . $file_name))
{
$add = $zip->addFile($zip_path . '/' . $file_name);
if (!($add)) echo "didn't work";
}
else echo "File doesn't exist!";
$close = $zip->close();
if ($close) echo 'File Closed';
else echo 'fail!!';
}
That little lot only outputs 'fail!!'. Any ideas what I'm missing?

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

Server to Server > Retrieve and extract a remote zip file to local server directory

I have a wp plugin file on server B who's purpose is to retrieve a zip file from a remote server A.
Once Server B receives the zip file, it should extract the contents and copy the files into a specific folder on server B overwriting any existing files.
I have some code below that I've borrowed from a file that uses and uploader to do the same thing and I'd just like to redo it for the automated server to server procedure described above. But I'm getting a fatal error when trying to Activate this plugin.
function remote_init()
{
openZip('http://myserver.com/upgrade.zip');
$target = ABSPATH.'wp-content/themes/mytheme/';
}
function openZip($file_to_open, $debug = false) {
global $target;
$file = realpath('/tmp/'.md5($file_to_open).'.zip');
//$file is always empty. can't use realpath in this case. What to do?
$client = curl_init($file_to_open);
curl_setopt(CURLOPT_RETURNTRANSFER, 1);
$fileData = curl_exec($client);
file_put_contents($file, $fileData);
$zip = new ZipArchive();
$x = $zip->open($file);
if($x === true) {
$zip->extractTo($target);
$zip->close();
unlink($file);
} else {
if($debug !== true) {
unlink($file);
}
die("There was a problem. Please try again!");
}
}
add_action( 'init','remote_init');
I did a quick check in the manual, and there was a slight error on line 5.
$target = ABSPATH .'wp-content/themes/mytheme/';
function openZip($file_to_open, $debug = false) {
global $target;
$file = ABSPATH . '/tmp/'.md5($file_to_open).'.zip';
$client = curl_init($file_to_open);
curl_setopt($client, CURLOPT_RETURNTRANSFER, 1); //fixed this line
$fileData = curl_exec($client);
file_put_contents($file, $fileData);
$zip = new ZipArchive();
$x = $zip->open($file);
if($x === true) {
$zip->extractTo($target);
$zip->close();
unlink($file);
} else {
if($debug !== true) {
unlink($file);
}
die("There was a problem. Please try again!");
}
}
function openZip($file_to_open, $debug = false) {
global $target;
$file = realpath('/tmp/'.md5($file_to_open).'.zip');
$client = curl_init($file_to_open);
curl_setopt(CURLOPT_RETURNTRANSFER, 1);
$fileData = curl_exec($client);
file_put_contents($file, $fileData);
$zip = new ZipArchive();
$x = $zip->open($file);
if($x === true) {
$zip->extractTo($target);
$zip->close();
unlink($file);
} else {
if($debug !== true) {
unlink($file);
}
die("There was a problem. Please try again!");
}
}

Categories