Add files to zip and download zip using php - php

I have a web service that is requesting for data. The data received is being stored in the variable $response.
After that, i am creating files to store the data.
Then i am trying to add these files to a zip and afterwards download that zip. I have consulted various questions and answers similar to mine but i still cannot solve my problem. Note that i have the zip library installed.
Below is my php script:
// Load zip library
$zip = new ZipArchive();
//Zip name
$zip_name = "data.zip";
if($zip->open($zip_name, ZIPARCHIVE::CREATE)!==TRUE){
// Opening zip file to load files
$error = "ZIP creation failed at this time";
}
else{
echo "zip creation successful";
}
function myFunc(){
//Some codes
global $zip;
$myfile = fopen($filepath, "w");
fwrite($myfile, $response);
fclose($myfile);
echo "test1";
try {
//add file to zip
$zip->addFile($myfile);
}
catch (Exception $e) {
echo $e->getMessage();
}
echo "test2";
}
$zip->close();
//Some codes
if(file_exists($zip_name)){
// push to download the zip
header('Content-type: application/zip');
header('Content-Disposition: attachment; filename="'.$zip_name.'"');
readfile($zip_name);
// remove zip file is exists in temp path
unlink($zip_name);
}
After running the above script, test1 is being displayed and not test2. I think that the problem lies in this line $zip->addFile($myfile);.
From previous posts, i could notice that the function addFile takes 2 parameters. How can i edit my code for this?
Thanks for your help.

Related

Progress bar to prevent 504 Gateway TimeOut in ZIPARCHIVE::CREATE

I'm creating a zip with php with big files like videos. The ZIP should be around 500mb and the php crash with 504 Gateway TimeOut when i try to makeit. I want to add a progress bar or something to avoid the server saturation, i think the key is in the foreach when add files.
foreach($post['files'] as $file) {
$zip->addFile($file,basename($file));
}
i already setup max_execution_time
ini_set('max_execution_time', 0);
Any idea how is the best way?
Complete code:
<?php
set_time_limit(0);
ini_set('max_execution_time', 0);
if(isset($_POST['files']))
{ $error = ""; //error holder
{
$post = $_POST;
$file_folder = "files/"; // folder to load files
if(extension_loaded('zip'))
{
// Checking ZIP extension is available
if(isset($post['files']) and count($post['files']) > 0)
{
// Checking files are selected
$casting_titulo = $post['casting_titulo'];
$zip = new ZipArchive(); // Load zip library
$zip_name = $titulo."cast.zip"; // Zip name
if($zip->open($zip_name, ZIPARCHIVE::CREATE)!==TRUE)
{
// Opening zip file to load files
$error .= "* Sorry ZIP creation failed at this time";
}
foreach($post['files'] as $file) {
$zip->addFile($file,basename($file));
}
$zip->close();
if(file_exists($zip_name))
{
// push to download the zip
header('Content-type: application/zip');
header('Content-Disposition: attachment; filename="'.$zip_name.'"');
readfile($zip_name);
// remove zip file is exists in temp path
unlink($zip_name);
}}
else $error .= "* Please select file to zip "; }
else $error .= "* You dont have ZIP extension"; }
}
?>

Readfile error in the download feature on my website

Hi i am making a download feature on my website and it is running however all the files are corrupted due to a recurring error readfile(): Filename cannot be empty in 'my/file/location' I don't understand why this is happening because according to every post I have looked at I am doing the download->zipfiles procedure correctly. Please help.
By the way i think the key to the answer may be in the fact that when i open the zip in a text file it reads:
Warning: file_get_contents(/uploads/): failed to open stream: No such file or directory in /home/ghostx19/public_html/phDownloader.php on line 21
the error is repeated 10 times because of the loop obviously
My Code:
<?php
//define stuff
$dir = "./uploads";
$allfiles = glob($dir.'*.{aiff}', GLOB_BRACE);
// create zip
$zip = new ZipArchive();
$zip_name = "zipfile.zip";
if($zip->open($zip_name, ZIPARCHIVE::CREATE)!==TRUE){
$error .= "* Sorry ZIP creation failed at this time";
}
//array of random files
$n=1;
while ($n<=10){
$n ++;
$randomfile = $allfiles[array_rand($allfiles)];
$path = "./uploads".$randomfile;
$zip->addFile(basename($path), file_get_contents($path));
}
// //present for download
$zip->close();
header('Content-Type: application/zip');
header('Content-disposition: attachment; filename='.$zip_name);
readfile('zipfile.zip');
if(file_exists('zipfile.zip'))
{
unlink('zipfile.zip');
}
?>

Files not added to ZIP

Am developing a code that creates a ZIP file out of selected files from a folder. The folder is created with sessiontime as name, but the files are not added to the ZIP file. The permissions of files are 777. The files are getting selected, indicated by the output below. I have also checked the code by replacing with line $zip->addFile($file_folder); which downloads a blank zip archive, hence there is no issue with it.
<?php
ob_start();
$error = ""; //error holder
if(isset($_POST['createpdf']))
{
$post = $_POST;
$file_folder = "test/".$_SESSION["dir_name"]."/"; // folder to load files
echo $file_folder;
if(extension_loaded('zip'))
{ // Checking ZIP extension is available
echo "checking";
if(isset($post['files']) and count($post['files']) > 0)
{ echo "/checking2";// Checking files are selected
$zip = new ZipArchive(); // Load zip library
$zip_name = time().".zip"; // Zip name
if($zip->open($zip_name, ZIPARCHIVE::CREATE)!==TRUE)
{
// Opening zip file to load files
echo "* Sorry ZIP creation failed at this time<br/>";
}
foreach($post['files'] as $file)
{ echo "added";
$zip->addFile($file_folder.$file); // Adding files
into zip
}
$zip->close();
if(file_exists($zip_name))
{
// push to download the zip
header('Content-type: application/zip');
header('Content-Disposition: attachment; filename="'.$zip_name.'"');
readfile($zip_name);
// remove zip file is exists in temp path
unlink($zip_name);
The output I get is the line : test//checking/checking2addedaddedadded
You forgot session_start() after opening the <?php tag, so your $_SESSION['dir_name'] variable is empty

Unable to view files inside Zip (But has Memory) created using ZipArchive function of php

<?php
$error = "";
$file_folder = "temp/";
// folder to load files
if (extension_loaded('zip')) {
// Checking ZIP extension is available
$zip = new ZipArchive();
// Load zip library
$zip_name = "images_".date("d-m-Y") . ".zip";
// Zip name
if ($zip -> open($zip_name, ZIPARCHIVE::CREATE) !== TRUE) {
// Opening zip file to load files
$error .= "* Sorry ZIP creation failed at this time";
}
$iterator = new RecursiveIteratorIterator(new RecursiveDirectoryIterator("../uploads/"));
$files = iterator_to_array($iterator, true);
foreach ($iterator as $file) {
$zip -> addFile($file_folder . $file);
// Adding files into zip
}
print_r($zip);
//echo $zip_name;
if (file_exists($file_folder.$zip_name)) {
// push to download the zip
header('Content-type: application/zip');
header('Content-Disposition: attachment; filename="' . $zip_name . '"');
readfile($zip_name);
// remove zip file is exists in temp path
unlink($zip_name);
} else {
echo "error";
}
$zip -> close();
//} else
// $error .= "* Please select file to zip ";
} else
$error .= "* You dont have ZIP extension";
?>
I have tried outputting $zip object and got following response:
ZipArchive Object ( [status] => 0 [statusSys] => 0 [numFiles] => 12 [filename] => /var/www/bigb/ajax/images_24-12-2012.zip [comment] => )
Status Zero explains there were no errors while creating zip (reference: http://www.php.net/manual/en/zip.constants.php)
I have referred posts:
1) Download all images from a single directory of a website
2) How to create a zip file using php and delete it after user downloads it?
3) http://www.9lessons.info/2012/06/creating-zip-file-with-php.html
Third one helped me the most and in the other 2 i was getting status as 23.
Issue: I am able to create a zip & no issue downloading it but when i open the zip i don't see any files inside but zip has memory in mbs.
Please Help me out...
Update: Error 23 occurs because of print_r / echo and or trying to overwrite same file.
Update2: Issue solved. It was due to path in RecursiveDirectoryIterator (i.e ../uploads/) once i moved the code to main folder and changed the path to (uploads/) everything started working as it should be. Kudos!!!
It was due to path in RecursiveDirectoryIterator (i.e ../uploads/) once i moved the code to main folder and changed the path to (uploads/) everything started working as it should be. Kudos!!!
I think the file path you are providing to $zip->addFile() is incorrect. You don't need to append anything to $file. Following will work:
foreach ($iterator as $file) {
$zip -> addFile($file);
}
In your case the $file will contain exact relative path of file like ../uploads/file.ext.

how to create rar/zipfile and download [duplicate]

This question already has answers here:
Dynamically creating zip with php
(2 answers)
Closed 9 years ago.
Hi frnds can anyone tel me how to Create a Zip File Using PHP?
Actually i am having 10 files with boxes,if i select more than one check box that files should get zip/rar and i am able to save that in some path..
Please can anyone help in this solution as i am new to php
$zip_name = 'path/to/final.zip'; //the real path of your final zip file on your system
$zip = new ZipArchive;
$zip->open($zip_name, ZIPARCHIVE::CREATE);
foreach($files as $file)
{
$zip->addFile($file);
}
$zip->close();
header('Content-type: application/zip');
header('Content-disposition: filename="' . $zip_name . '"');
header("Content-length: " . filesize($zip_name));
readfile($zip_name);
exit();
// This example creates a ZIP file archive test.zip and add the file /path/to/index.txt. as newname.txt.
$zip = new ZipArchive;
$res = $zip->open('test.zip', ZipArchive::CREATE);
if ($res === TRUE) {
$zip->addFile('/path/to/index.txt', 'newname.txt');
$zip->close();
echo 'ok';
} else {
echo 'failed';
}
//include your connection file
//$file_names[] get your files array
//$error = ""; //error holder
//$file_path='set your image path' folder to load files
if(extension_loaded('zip'))
{ // Checking ZIP extension is available
if(count($file_names) > 0)
{
// Checking files are selected
$zip = new ZipArchive(); // Load zip library
$zip_name = time().".zip"; // Zip name
if($zip->open($zip_name, ZIPARCHIVE::CREATE)!==TRUE){ // Opening zip file to load files
$error .= "* Sorry ZIP creation failed at this time<br/>";
}
foreach($file_names as $file){
$zip->addFile($file_path.$file); // Adding files into zip
}
$zip->close();
if(file_exists($zip_name))
{
// push to download the zip
header('Content-type: application/zip');
header('Content-Disposition: attachment; filename="'.$zip_name.'"');
readfile($zip_name);
// remove zip file is exists in temp path
unlink($zip_name);
}
}
else
{
$error .= "* Please select file to zip <br/>";
}
}
else
{
$error .= "* You dont have ZIP extension<br/>";
}
?>

Categories