Not being able to save files inside ZIP with ZipArchive - php

I Have been reading many similar problems but I just can't find the solution to mine.
All I need is zip the files that come in the POST variable as an array and get the path to the zip file just created. Here is my code... I keep getting an empty Object and just can't make 1 file inside
function downloadAllImages(){
$data = array();
$files = $_POST['files_to_download'];
$archive_file_name = 'images.zip';
$zip = new ZipArchive();
//create the file and throw the error if unsuccessful
if ($zip->open($archive_file_name, ZIPARCHIVE::CREATE )!==TRUE) {
$data['debug'].=("cannot open <$archive_file_name>\n");
}
//add each files of $file_name array to archive
foreach($files as $file)
{
$zip->addFile($file, basename($file));
}
$zip->close();
//then send the headers to foce download the zip file
header("Content-type: application/zip");
header("Content-Disposition: attachment; filename=$archive_file_name");
header("Pragma: no-cache");
header("Expires: 0");
readfile("$archive_file_name");
$data['debug'].=print_r($zip,true);
echo json_encode($data);
die();
}
I'm using JQuery to get the download link after the file is zipped. I just can't make the files to zip.
The array files_to_download prints:
Array(
[0] => http://localhost/br/wp-content/uploads/2020/04/rabbit-black-transp-300x300.png
[1] => http://localhost/br/wp-content/uploads/2020/04/bg-shop-300x169.png
)
And my jQuery
function downloadAllImages(){
var files_to_download = [];
$("img.downloadable").each(function(){
files_to_download.push($(this).attr('src'));
});
jQuery.ajax({
url: runAJAX.ajaxurl,
data: ({action: 'downloadAllImages', files_to_download:files_to_download}),
method: "POST",
success: function(data_received) {
displayAjaxResponse(data_received);
}
});
}

In the end a friend of mine helped and the PHP code should look like this:
function downloadAllImages()
{
$data = array();
$files = $_POST['files_to_download']; // array
$domain= wp_upload_dir();
// used this to rename the file so each post gets it's own zip
$prefix=$_POST['file_prefix'];
$zip = new ZipArchive();
$tmp_zip = $zip->open($domain['basedir'].'/'.$prefix.'images.zip', ZipArchive::CREATE);
foreach($filesas $img)
{
if(!empty($img))
{
$download_file = file_get_contents($img);
$zip->addFromString(basename($img), $download_file);
}
}
$zip->close();
$now = new DateTime();
$data['file'] = get_bloginfo('wpurl')."/wp-content/uploads/{$prefix}images.zip?v={$now ->getTimestamp()}";
echo json_encode($data);
die();
}
And the jQuery looks pretty much the same, except for adding the 'file_prefix' variable.

Related

Create zip from array list of elements, stored in different folders

I got a loop with whom I write data in a table, included urls of files I've to zip.
During the loop I put the url in an array.
At the end of table I would have a button, giving me the zip of all files.
I'm in a wordpress site, PHP 5 and Linux.
During loop I save url file here with its path
if (file_exists($file_letttut)) {
$nameAndCode['zipp'] = "http://mypath/to/".$file_letttut;
$namesArray[] = $nameAndCode;}
I tried different codes to zip, I write here the easier
$zip = new ZipArchive;
$zip_name = "zippot.zip"; // Zip name
$res = $zip->open($zip_name, ZipArchive::CREATE);
if ($res === TRUE) {
foreach($namesArray as $key => $value) {
$nomefile = basename($namesArray[$key][zipp].$value);
$nomefile = str_replace('Array', '', $nomefile);
$nomecompleto = str_replace('Array', '', $namesArray[$key][zipp].$value);
$zip->addFile($nomecompleto, $nomefile);
}
$zip->close();
echo 'ok';
} else {
echo 'failed';
}
if(file_exists($zip_name)) {
echo "yes";die;
header('Content-type: application/zip');
header('Content-Disposition: attachment; filename="'.$res.'"');
readfile($res);
unlink($res);
} else {
echo "zip not created";die;
}
$zip_name doesn't exist...
Where do I fail?
Should I've to copy files to a folder before?
Thanks in advance

Zip file is not downloading in Yii2

I am trying to download the zip file with many images.This code is working when i call the path in browser but not downloading when i call from Jquery ajax.Need to change or add anything in header?please help.
Controller:
public function actionZipdownload(){
$files = Yii::$app->request->post('imgsrc');
//it displays the URLs.
$zip = new \ZipArchive();
$tmp_file = tempnam('.', '');
$zip->open($tmp_file, ZipArchive::CREATE);
foreach ($files as $file) {
$download_file = file_get_contents($file);
$zip->addFromString(basename($file), $download_file);
}
$zip->close();
header('Content-disposition: attachment; filename="my file.zip"');
header('Content-type: application/zip');
readfile($tmp_file);
unlink($tmp_file);
}
Jquery:
$.ajax({
url:url+'site/zipdownload',
data:{'imgsrc':imgsrc},
type:'POST',
success:function(data){
//alert(data);
}
});
In console response:
I just ignore the Jquery Ajax and done it by Html::a with two actions..When i am calling the url in a tag then the file got downloaded.And also done some changes in controller.
Views:
<?=Html::a('Create Zip',['site/zipdownload'],['class'=>'btn btn-danger pull-left'])?>
<?=Html::a('Download',['site/download'],['class'=>'btn btn-danger pull-left'])?>
Controller:
public function actionZipdownload(){
$files = Yii::$app->request->post('img_src');
$zip = new \ZipArchive();
$tmp_file = 'uploads/images.zip';
if(file_exists($tmp_file)){
$zip->open($tmp_file, ZipArchive::OVERWRITE);
}
else{
$zip->open($tmp_file, ZipArchive::CREATE);
}
$i=1;
foreach ($files as $file) {
$download_file = file_get_contents($file);
$fileParts = pathinfo($file);
$filename = $i.explode("?",$fileParts['filename'])[0];
$zip->addFromString($filename, $download_file);
$i++;
}
$zip->close();
}
public function actionDownload(){
$path = 'uploads/images.zip';
if(file_exists($path)){
\Yii::$app->response->sendFile($path)->send();
unlink($path);
}
else{
return $this->redirect(['site/dashboard']);
}
}

Add both folders and files into zip (PHP)

I am looking to add both folders and files from a matching array to a zip file. Below is my code:
function listdir($start_dir='./assets') {
//Array that will contain the director
$files = array();
if (is_dir($start_dir)) {
$fh = opendir($start_dir);
while (($file = readdir($fh)) !== false) {
// Loop through the files, skipping '.' and '..', and recursing if necessary
if (strcmp($file, '.')==0 || strcmp($file, '..')==0) continue;
$filepath = $start_dir . '/' . $file;
if ( is_dir($filepath) )
$files = array_merge($files, listdir($filepath));
//else
array_push($files, $filepath);
}
closedir($fh);
} else {
// false if the function was called with an invalid non-directory argument
$files = false;
}
return $files;
}
//Array of all files
$allFiles = listdir('./assets');
print_r($allFiles);
//Gets all values with name "asset"
$name = $_POST['asset'];
//If there are items in the array, zip them together
if($name!=0){
//Compares $_POST array with array of all files in directory
$result = array_intersect($allFiles, $name);
function zipFilesAndDownload($result){
$zip = new ZipArchive();
//create the file and throw the error if unsuccessful
if ($zip->open('SelectedAssets.zip', ZIPARCHIVE::CREATE )!==TRUE) {
exit("cannot open SelectedAssets.zip\n");
}
//add each files of $file_name array to archive
foreach($result as $allFiles) {
$zip->addFile($allFiles);
}
$zip->close();
$zipped_size = filesize('SelectedAssets.zip');
header("Content-Description: File Transfer");
header("Content-type: application/zip");
header("Content-Type: application/force-download");// some browsers need this
header("Content-Disposition: attachment; filename=SelectedAssets.zip");
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Pragma: public');
header("Content-Length:". " $zipped_size");
ob_clean();
flush();
readfile("SelectedAssets.zip");
unlink("SelectedAssets.zip"); // Now delete the temp file (some servers need this option)
exit;
}
if(isset($_POST['submit'])) {
//$file_names=$_POST['assets'];// Always sanitize your submitted data!!!!!!
//$file_names = filter_var_array($_POST['assets']);//works but it's the wrong method
$filter = filter_input_array(INPUT_POST, FILTER_SANITIZE_SPECIAL_CHARS) ;
$file_names = $filter['assets'] ;
//Archive name
$archive_file_name='DEMO-archive.zip';
//Download Files path
$file_path= getcwd(). './';
//call the function
zipFilesAndDownload($result);
} else {
print 'Something went wrong.';
exit;
}
} //Otherwise, don't.
else {
print_r("Please select a file.");
}
The code above searches through a directory and reads all the folders and files. Then using array_intersect I matched files that were put into an empty array by the user to all the files in the previously searched directory. I then zip the files that match and download.
My question is, how can I have a folder be added to this zip as well? As of now, this only adds files and folders are assumed as empty.

How to create Zip file and download in CakePhp?

I'm trying to create zip files using CakePhp 1.3. The file descriptions are stored in database. In my controller I'm using the following logic.
// Fetching File description form database.
$this->view = 'Media';
$user_id=$this->Session->read('userData.User.id');
$condition = "Document.isdeleted = '0' AND Document.project_id='". $project_id."'";
$projectDocumentList = $this->Document->find("all",array('conditions'=>$condition,'fields'=>array('Document.id','Document.document_name','Document.path'),'order' => array('Document.id ASC')));
$this->set('projectDocumentList',$projectDocumentList);
if(!empty($projectDocumentList)){
$fileNames = "";
$fileNamesArr = array();
foreach($projectDocumentList as $projectDocument){
$fileNamesArr[ ]= $projectDocument['Document']['document_name'];
}
}
// Making zip
$archive_file_name='myFile.zip';
$file_path= "my_file_path";// Here I'm using my server basepath
$zip = new ZipArchive();
if ($zip->open($archive_file_name, ZIPARCHIVE::CREATE )!==TRUE) {
exit("cannot open <$archive_file_name>\n");
}
foreach($fileNamesArr as $files)
{
$zip->addFile($file_path.$files,$files);
//echo $file_path.$files."<br>"; // This can show the file in browser
}
$zip->close();
header("Content-type: application/zip");
header("Content-Disposition: attachment; filename=$archive_file_name");
header("Pragma: no-cache");
header("Expires: 0");
readfile("$archive_file_name");
exit;
Now the zip file download as myFile.zip, but when I'm going to open that file, it throws an error "The archive is either in unknown format or damaged".
Create Zip File of whole folder
// Get real path for our folder
$rootPath = realpath('folder-to-zip');
// Initialize archive object
$zip = new ZipArchive();
$zip->open('file.zip', ZipArchive::CREATE | ZipArchive::OVERWRITE);
// Create recursive directory iterator
/** #var SplFileInfo[] $files */
$files = new RecursiveIteratorIterator(
new RecursiveDirectoryIterator($rootPath),
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($rootPath) + 1);
// Add current file to archive
$zip->addFile($filePath, $relativePath);
}
}
// Zip archive will be created only after closing object
$zip->close();
And than pass the path of the zip file to the view.
$this->set('Zip_path'.zip_file_name);

Download multiple files as a zip-file using php

How can I download multiple files as a zip-file using php?
You can use the ZipArchive class to create a ZIP file and stream it to the client. Something like:
$files = array('readme.txt', 'test.html', 'image.gif');
$zipname = 'file.zip';
$zip = new ZipArchive;
$zip->open($zipname, ZipArchive::CREATE);
foreach ($files as $file) {
$zip->addFile($file);
}
$zip->close();
and to stream it:
header('Content-Type: application/zip');
header('Content-disposition: attachment; filename='.$zipname);
header('Content-Length: ' . filesize($zipname));
readfile($zipname);
The second line forces the browser to present a download box to the user and prompts the name filename.zip. The third line is optional but certain (mainly older) browsers have issues in certain cases without the content size being specified.
This is a working example of making ZIPs in PHP:
$zip = new ZipArchive();
$zip_name = time().".zip"; // Zip name
$zip->open($zip_name, ZipArchive::CREATE);
foreach ($files as $file) {
echo $path = "uploadpdf/".$file;
if(file_exists($path)){
$zip->addFromString(basename($path), file_get_contents($path));
}
else{
echo"file does not exist";
}
}
$zip->close();
Create a zip file, then download the file, by setting the header, read the zip contents and output the file.
http://www.php.net/manual/en/function.ziparchive-addfile.php
http://php.net/manual/en/function.header.php
You are ready to do with php zip lib,
and can use zend zip lib too,
<?PHP
// create object
$zip = new ZipArchive();
// open archive
if ($zip->open('app-0.09.zip') !== TRUE) {
die ("Could not open archive");
}
// get number of files in archive
$numFiles = $zip->numFiles;
// iterate over file list
// print details of each file
for ($x=0; $x<$numFiles; $x++) {
$file = $zip->statIndex($x);
printf("%s (%d bytes)", $file['name'], $file['size']);
print "
";
}
// close archive
$zip->close();
?>
http://devzone.zend.com/985/dynamically-creating-compressed-zip-archives-with-php/
and there is also php pear lib for this
http://www.php.net/manual/en/class.ziparchive.php

Categories