Ok so this is making me crazy... I abstracted the code because it comes from a big project. But in my project I ended up commenting everything and only have this left which is still causing problems and I have no idea why.
$f = fopen('tmp/'.$name.'.zip', 'wb');
fwrite($f, $myzip);
fclose($f); //I can open this file manually and everything is fine
$zip = new ZipArchive;
$res = $zip->open('tmp/'.$name.'.zip'); //$res is "1"
$zip->extractTo("final/" . $unique);
$zip->close();
As you can see I write a zip file in /tmp, at this point, I can open the file manually and it contains all files with the correct size.
But after I extract it to /final, for some reason some files are empty...
Any idea what could cause this?
You can do this way by throwing Exception at zip archive open time,
function DecompressFile()
{
$zip = new ZipArchive;
if ($zip->open('tmp/'.$name.'.zip') === TRUE) {
$zip->extractTo("final/" . $hwidDir);
$zip->close();
return 'completed';
}
else {
throw new Exception ("Decompress operation from ZIP file failed.");
}
}
Related
I am trying to extract zip file in codeigniter 4... I have the code below
$file_name = session()->get('file_name');
// Zip file name
$filename = "/public/$file_name";
$zip = new \ZipArchive;
$res = $zip->open($filename);
if ($res === true) {
// Unzip path
$path = "/public";
// Extract file
$zip->extractTo($path);
$zip->close();
return 'Site Updated Successfully';
} else {
return "failed to update $filename!";
}
}
but I get this result: return "failed to update $filename!";
Please can someone help me fix the issue with the code.
This has nothing specifically to do with Codeigniter. It's just using PHP and ZipArchive. The code looks OK - be sure the file is really in the /public/ directory and that it is a zip archive. The PHP site has examples that are like $zip = new ZipArchive; (without the \ char); maybe try that.
I was creating a zip archive with php 7.4 (lib-zip version 1.6.1) without any problems.
Now I try to protect these zip archive with a password. Not just for encrypting with php, but in general. I found this tutorial. It does what it should, but I could not read the files of the zip archive any more. If I doubleclick on the archive, the password prompt opens up, but it does not work with the password from the source code. I also copy and pasted it to prevent any keyboard struggle.
<?php
$zip = new ZipArchive();
$filePath = sprintf('%s/test/', __DIR__);
$fileName = 'test.zip';
$absoluteFilePath = $filePath . $fileName;
$excludeFolderNames = [
'.',
'..',
'.DS_Store',
$fileName,
];
$zipFlag = ZipArchive::CREATE;
if (file_exists($absoluteFilePath)) {
$zipFlag = ZipArchive::OVERWRITE;
}
$createFile = $zip->open($absoluteFilePath, $zipFlag);
if (true !== $createFile) {
throw new RuntimeException(sprintf('could not open file in "%s" caused by %s', $fileName, $createFile));
}
$iterator = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($filePath));
$password = 'top-secret';
if (!$zip->setPassword($password)) {
throw new RuntimeException('Set password failed');
}
/** #var SplFileInfo $value */
foreach ($iterator as $key => $value) {
if (in_array($value->getFilename(), $excludeFolderNames)) {
continue;
}
$cleanFilePath = realpath($key);
if (!$cleanFilePath) {
throw new RuntimeException(sprintf('could not create real path from filepath: %s', $key));
}
$zipName = str_replace($filePath, '', $cleanFilePath);
if (!$zip->addFile($cleanFilePath, $zipName)) {
throw new RuntimeException(sprintf('Add file failed: %s', $cleanFilePath));
}
if (!$zip->setEncryptionName($zipName, ZipArchive::EM_AES_256)) {
throw new RuntimeException(sprintf('Set encryption failed: %s', $zipName));
}
}
$zip->close();
Does someone has the same problem or am I the problem?
UPDATE I:
I tought it solves my problem to save the zip-file outside the folder I want to zip. So I changed the following line:
$absoluteFilePath = sprintf('%s/%s', __DIR__, $fileName);
After a while the error occured again.
One possible reason I discovered, were .DS_Store files. In my example I exclude them. But the error occured again.
UPDATE II:
One further problem is, that there is no password prompt, if all files are empty.
UPDATE III:
Same code works with files without line break, but the error occurs, if the file has multiple lines.
I found help at the php-bugtracker. It turns out that I can extract all the files with an zip-extension like the comments tryed to tell me before. Now I wait for the new libzip version 1.7.0, where the default zip encryption is available. After this I hope I can extract my files without any extension.
I'm completely at a loss for explaining why this isn't working. HELP!
$archive = "x.zip";
$zip = new ZipArchive();
$res = $zip->open($archive);
if ($res === 'TRUE') {
$unzip_success= $zip->extractTo('/temp/', "inscriptions.txt")
$zip->close();
}
the target dir "temp" is "0777" permissions
the code obtained from $res is "11" and not "TRUE" as required by the documentation on PHP.net
note: must put the full url for $archive and the first argument of extractTo
if nothing works then check if your server is linux.
if its linux you can run unzip command to unzip your file via php's system/exec function.
i.e
system("unzip archive.zip");
to extract specific file you can check man docs for unzip. many times due to server parameters zip library doesn't work as expected in that cases i switch back to linux commands.
The problem is that you are quoting TRUE, which is a keyword and should be left without single quotes. Plus, you could check if the file exists in the zip archive prior to its extraction with locateName:
$archive = "x.zip";
$zip = new ZipArchive();
$res = $zip->open($archive);
if ($res === true && $zip->locateName('inscriptions.txt') !== false) {
$unzip_success= $zip->extractTo('/tmp/', "inscriptions.txt");
$zip->close();
}
ZipArcive::extractTo is case-sensitive. If file's name to be extracted do not meet zipped one exactly, the method returns false.
I faced the same problem, I have fixed this :)
Use $_SERVER['DOCUMENT_ROOT'] for url.
My code (codeigniter):
$this->load->library('unzip');
$file = $this->input->GET('file');
$this->unzip->extract($_SERVER['DOCUMENT_ROOT'].'/TRAS/application/uploads/' . $file,$_SERVER['DOCUMENT_ROOT'].'/TRAS/application/views/templates/' . $file);
If $res is equal to 11, that means that ZipArchive can't open the specified file.
To test this:
$archive = "x.zip";
$zip = new ZipArchive();
$res = $zip->open($archive);
if($res == ZipArchive::ER_OPEN){
echo "Unable to open $archive\n";
}
Adding document root is what worked for me as well. here is my code
$zip = new ZipArchive;
if ($zip->open($_SERVER['DOCUMENT_ROOT'].'/'.$folder.$file_path) === TRUE) {
$zip->extractTo($_SERVER['DOCUMENT_ROOT'].'/$folder');
$zip->close();
echo 'ok';
}
I meet same problem, but I can open the zip file, it returns true after open.
My issue is I got false after $zip->extractTo().
I finally success after delete files named in CHINESE (NO-ENGILISH) in the zip file.
I had the same problem on Windows 10. The only solution I found was just to try extractTo twice, even though the open() was successful:
$zip = new ZipArchive;
if ($open === true) {
$result = $zip->extractTo($destination);
if ($result === false) {
$result = $zip->extractTo($destination);
}
$zip->close();
}
The fact that the second extractTo() works (with no intervening action) would seem to indicate that there's nothing wrong with the archive or the destination directory.
I wrote this code to create a ZIP file and to save it. But somehow it just doesn't show any error, but it doesn't create a ZIP file either. Here's the code:
$zip = new ZipArchive;
$time = microtime(true);
$res = $zip->open("maps/zips/test_" . $time . ".zip", ZipArchive::CREATE);
if ($res === TRUE) {
echo "RESULT TRUE...";
$zip->addFile("maps/filename.ogz","filename.ogz"); //Sauerbraten map format
$zip->addFromString('how_to_install.txt', 'Some Explanation...');
$zip->close();
$zip_created = true;
echo "FILE ADDED!";
}
What am I doing wrong, and how can I fix it?
Probably apache or php has not got permissions to create zip archives in that directory. From one of the comments on ZipArchice::open:
If the directory you are writing or
saving into does not have the correct
permissions set, you won't get any
error messages and it will look like
everything worked fine... except it
won't have changed!
Instead make sure you collect the
return value of ZipArchive::close().
If it is false... it didn't work.
Add an else clause to your if statement and dump $res to see the results:
if($res === TRUE) {
...
} else {
var_dump($res);
}
There are 2 cases when zip doesn't generate the error.
Make sure every file you are adding to the zip is valid. Even if
one file is not available when zip->close is called then the archive
will fail and your zip file won't be created.
If your folder doesn't
have write permissions zip will not report the error. It will finish
but nothing will be created.
I had an exactly same issue, even when with full writing/reading permissions.
Solved by creating the ".zip" file manually before passing it to ZipArchive:
$zip = new ZipArchive;
$time = microtime(true);
$path = "maps/zips/test_" . $time . ".zip"
touch($path); //<--- this line creates the file
$res = $zip->open($path, ZipArchive::CREATE);
if ($res === TRUE) {
echo "RESULT TRUE...";
$zip->addFile("maps/filename.ogz","filename.ogz"); //Sauerbraten map format
$zip->addFromString('how_to_install.txt', 'Some Explanation...');
$zip->close();
$zip_created = true;
echo "FILE ADDED!";
}
Check out that each of your file exists before calling $zip->addFile otherwise the zip won't be generated and no error message will be displayed.
if(file_exists($fichier->url))
{
if($zip->addFile($fichier->url,$fichier->nom))
{
$erreur_ouverture = false;
}
else
{
$erreur_ouverture = true;
echo 'Open error : '.$fichier->url;
}
}
else
{
echo 'File '.$fichier->url.' not found';
}
break it into steps.
if ($res === TRUE) {
check if file_exist
check if addFile give any error
}
if($zip->close())
{
$zip_created = true;
echo "FILE ADDED!"
}
Check the phpinfo for zip is enabled or not :)
One of the reasons for zip file is not created is due to missing check if you are adding file and not a directory.
if (!$file->isDir())
I found the solution here.
The purpose of this code is to grab an update.zip file from a remote server, unzip it and save it to a local directory, updating, overwriting or creating the updated files.
I've almost got a non cURL version of this working, but I'd rather use this version. The first problem I have is that the path to the tmp folder is incorrect. I need a better method of sniffing that out (temporarily hardcoded)...
The 2nd problem is that the code's not working, but its not throwing an error. Its executing the $x branch but no zip extraction is taking place.
require('../../../wp-blog-header.php'); //enables wp security check and ABSPATH
$payload = file_get_contents('http://myserver.com/upgrade.zip'); //grab the file from the remote server
$target = ABSPATH .'wp-content/themes/mytheme/'; // this is the destination for the unzipped files
openZip($payload);
function openZip($file_to_open, $debug = false) {
global $target;
$file = ABSPATH . '/tmp/'.md5($file_to_open).'.zip'; //this should be home/myfolder/tmp but ABSPATH is giving the wrong path to the tmp directory.
$client = curl_init($file_to_open);
curl_setopt($client, CURLOPT_RETURNTRANSFER, 1);
$fileData = curl_exec($client);
file_put_contents($file, $fileData);
$zip = new ZipArchive();
$x = $zip->open($file);
if($x === true) { //this is true, but no zip extraction?
$zip->extractTo($target);
$zip->close();
unlink($file);
} else {
if($debug !== true) {
unlink($file);
}
die("There was a problem. Please try again!");
}
}
The most likely cause here is that you're not actually writing the zip file data in your file_put_contents() call inside openZip. If you pass a zero-length file to $zip->open(), it will happily go about its way returning (bool)true, even though you obviously will not be able to extract anything from it. See this example.