I have the following code, which as you can see i use to create a new directory then unzip a file.
<?php
function unzip_to_s3() {
// Set temp path
$temp_path = 'wp-content/uploads/gravity_forms/1-9e5dc27086c8b2fd2e48678e1f54f98c/2013/02/tmp/';
// Get filename from Zip file
$zip_file = 'archive.zip';
// Create full Zip file path
$zip_file_path = $temp_path.$zip_file;
// Generate unique name for temp sub_folder for unzipped files
$temp_unzip_folder = uniqid('temp_TMS_', true);
// Create full temp sub_folder path
$temp_unzip_path = $temp_path.$temp_unzip_folder;
// Make the new temp sub_folder for unzipped files
if (!mkdir($temp_unzip_path, '0755', true)) {
die('Error: Could not create path: '.$temp_unzip_path);
}
// Unzip files to temp unzip folder, ignoring anything that is not a .mp3 extension
$zip = new ZipArchive();
$filename = $zip_file_path;
if ($zip->open($filename)!==TRUE) {
exit("cannot open <$filename>\n");
}
for ($i=0; $i<$zip->numFiles;$i++) {
$info = $zip->statIndex($i);
$file = pathinfo($info['name']);
if(strtolower($file['extension']) == "mp3") {
file_put_contents(basename($info['name']), $zip->getFromIndex($i));
} else {
$zip->deleteIndex($i);
}
}
$zip->close();
}
unzip_to_s3();
?>
The unzip code was courtesy of #TotalWipeOut from one of my other posts. It currently unzips just mp3 files to my base directory, but i want to put them in my newly created folder.
I'm very new to PHP so have been trying my best with this, but i can't figure out how to change the file_put_contents(basename($info['name']), $zip->getFromIndex($i)); line to get it to put the files in my new folder?
As Marc B. mentioned you need to include the path to the directory you are putting the file in.
using your code:
file_put_contents($temp_unzip_path."/".basename($info['name']), $zip->getFromIndex($i));
I would also suggest reading a little more about the basics of PHP.
Related
i need to create a zipFile with a childs zipFiles already exist :
> folder
- file1.zip
- file2.zip
I want to get a zip file containing all the zip files in the folder.
$dir = "path/to/my/dir";
$finder = new Finder();
$zip = new \ZipArchive();
/***** I create a empty zip file ****/
$filesystem->dumpFile("$dir/delivrables.zip",'');
if($zip->open('delivrables.zip', ZipArchive::CREATE) === TRUE) {
foreach ($finder->in($dir) as $file) {
$zip->addFile($file->getPath(), $file->getFilename());
}
}
I don't get error but i can't extract zip file.
You can create a zip file with zip files in the same way as you create a zip file with images, documents etc
So, I want to create a system where user uploads in a zip file the files of a 3d model and the model can be shown, stored, etc
So, I got the file, I place it into a folder, permanently, And unzip it into another temp folder, just to see if it is a 3d model.
I tried like this:
$target_dir = "upload/";
$targetfilename = rand().$_FILES['file']['name'];
move_uploaded_file($_FILES['file']['tmp_name'], $target_dir.$targetfilename);
//unzip the file into temp folder
$tmp_dir = $target_dir.rand();
mkdir($tmp_dir);
chmod($tmp_dir, 0777);
//chmod($targetfilename, 0777); //this not working, maybe isn't the right way
$zip = new ZipArchive;
$res = $zip->open($targetfilename);
if ($res === TRUE) {
// extract it to the path we determined above
$zip->extractTo($tmp_dir);
$zip->close();
echo 'SUCCESS';
} else {
echo 'ERROR';
}
I do not get any errors, but the zip can't be unzipped. Any idea? How can I resolve this?
Isn't $targetfilename is in $target_dir folder?
If so, changing
$res = $zip->open($targetfilename); to
$res = $zip->open($target_dir.$targetfilename); might solve your problem.
I need to download all files form url and download as a zip. Every thing is working but i am not able to rename the file names under zip. I am using below code
$zip = new ZipArchive();
$zip_name = time().".zip"; // Zip name
if($zip->open($zip_name, ZIPARCHIVE::CREATE)!==TRUE)
{
$error = "* Sorry ZIP creation failed at this time";
}else{
foreach ($_POST as $file) {
foreach($file as $res){
$download_file = file_get_contents($res);
$zip->addFromString(basename($res), $download_file);
}
}
$zip->close();
}
can anyone please help me how can i rename the files?
In your code, you use the line
$zip->addFromString(basename($res), $download_file);
...that means: add the downloaded file under it's name to the archive. If you want to change the file name that should occur in the archive, you should start looking here
I am currently working on a tool made with PHP (quite newbie with this technology...) which should generate zip files with a set of files inside. This set of files can be:
Basic files (mutliple formats)
Full directories (will be added into the resulting zip as a new zipped file - ZIP inside the final ZIP)
The thing is that when the zip files contains simple files it is downloaded properly but when the file contains the "Full directory zip file" then the resulting ZIP file get corrupted...
Below the code I am currently using (sorry if its a bit messy but is the first time I work with PHP...)
function ZipFiles($fileArr,$id) {
$destination = "{$_SERVER['DOCUMENT_ROOT']}/wmdmngtools/tempFiles/WMDConfigFiles_".$id.".zip";
$valid_files = array();
//if files were passed in...
if(is_array($fileArr)) {
//cycle through each file
foreach($fileArr as $file) {
if(is_dir($file)) {
//If path is a folder we zip it and put it on $valid_files[]
$resultingZipPath = "{$_SERVER['DOCUMENT_ROOT']}/wmdmngtools/tempFiles/".basename($file)."_FOLDER.zip";
ZipFolder($file,$resultingZipPath );
$valid_files[] = $resultingZipPath ;
}
else {
//If path is not a folder then we make sure the file exists
if(file_exists("{$_SERVER['DOCUMENT_ROOT']}/wmdmngtools/tempFiles/".$file)) {
$valid_files[] = $file;
}
}
}
}
//if we have good files...
if(count($valid_files)) {
//create the archive
$zip = new ZipArchive();
if($zip->open($destination,ZIPARCHIVE::CREATE) !== true) {
return false;
}
//add the files
foreach($valid_files as $file) {
$zip->addFile("{$_SERVER['DOCUMENT_ROOT']}/wmdmngtools/tempFiles/".$file,$file);
}
$zip->close();
return $destination;
}
else
{
return "";
}
}
function ZipFolder($source, $destination) {
// Initialize archive object
$folderZip = new ZipArchive();
$folderZip->open($destination, ZipArchive::CREATE | ZipArchive::OVERWRITE);
// Create recursive directory iterator
/** #var SplFileInfo[] $files */
$files = new RecursiveIteratorIterator(
new RecursiveDirectoryIterator($source),
RecursiveIteratorIterator::LEAVES_ONLY
);
foreach ($files as $name => $file)
{
// Skip directories (they would be added automatically)
if (!$file->isDir())
{
// Get real and relative path for current file
$filePath = $file->getRealPath();
$relativePath = substr($filePath, strlen($source) + 1);
// Add current file to archive
$folderZip->addFile($filePath, $relativePath);
}
}
// Zip archive will be created only after closing object
$folderZip->close();
}
On it we can see two functions:
ZipFiles: is the main fucntion that is called by passing a list/array (contains the list of files and folders that will be added into the final ZIP) and an ID parameter which is simply used for generatig different file names... (can be ignored)
ZipFolder: this fucntion is called for each of the folders (not files) on the above mentioned list/array in order to zip that folder and create a zip file to add it on the final file. (based on what I found in How to zip a whole folder using PHP)
I have tried many things like mentioned in above post like closing all files, or avoiding empty zips inside the zip but nothing worked...
Zip inside zip (php)
Maybe I missed something (most probably :) ) but am running out of aces so any help/guideance would be appreciated.
In case more info is needed please let me know and will post it.
Thanks a lot in advance!!
Finally found the issue. Seems that the file was generated properly but when downloading it from PHP there was a problem when size was bigger than a concrete number.
THis was due to wrong definition of the message length on the header definition:
header("Cache-Control: public");
header("Content-Description: File Transfer");
header("Content-Length: ".filesize($zippedFile));
header("Content-Disposition: attachment; filename=".$zippedFile);
header("Content-type: application/zip");
header("Content-Transfer-Encoding: binary");
Even if I guess it may not be a correct practice I removed the Content-Length entry and now I get the correct file despite of its size.
$File = "images/files.txt";
$zip = new ZipArchive();
$filename = "./images/files.zip";
if ($zip->open($filename, ZipArchive::CREATE)!==TRUE) {
exit("cannot open <$filename>\n");
}
$zip->addFile("$File");
$zip->close();
This code creates a files.zip file inside 'images' folder, if I open that zip file, 'images' folder is there too. I don't want folder 'images' to be there. But only the 'files.txt' file(located inside images folder) needs to be there.
Files structure:
zip.php
images
files.txt
How can I do that?
#hek2mgl I have 'files.txt' inside 'images' folder, that's why it's happening
Then your code will not work at all as the path to $File is wrong. Use this:
$File = "images/files.txt";
$zip = new ZipArchive();
$filename = "./images/files.zip";
if ($zip->open($filename, ZipArchive::CREATE)!==TRUE) {
exit("cannot open <$filename>\n");
}
// use the second parameter of addFile(). It will give the file
// a new name inside the archive. basename() returns the filename
// from a given path
$zip->addFile("$File", basename($File));
if(!$zip->close()) {
die('failed to create archive');
}