PHP Downloading zip created with ziparchive - php

I am new to PHP and am trying to create a ZIP function which is called through Ajax and downloaded to the user.
I get a positive response with the zip but the streaming gives me an error for
filesize():stat failed for ../test.zip and also read file failed to open stream, no such file or directory on the PHP page.
Here is my code below - I have seared pretty hard and can't seem to find an answer that makes sense for my situation
<?php
require("../../common.php");
ini_set('display_startup_errors',1);
ini_set('display_errors',1);
error_reporting(-1);
$thisdir = " ";
$zip = new ZipArchive();
$filename = "../test.zip";
if ($zip->open($filename, ZipArchive::CREATE)!==TRUE) {
exit("cannot open <$filename>\n");
}
$zip->addFromString('insert.pdf' . time(), "#1 This is a test string added as testfilephp.txt.\n");;
$zip->addFile($filename . "../../../folder/pdf_folder/");
echo "numfiles: " . $zip->numFiles . "\n";
echo "status:" . $zip->status . "\n";
echo $filename;
//$size = filesize($zip->filename);
$zip->close();
header("Content-type: application/zip");
header("Content-Disposition: attachment; filename=$filename");
header("Content-length: " . filesize($filename));
header("Pragma: no-cache");
header("Expires: 0");
readfile("$filename");
?>
thank you for any help or guidance
****** edit
here is the error for the code
Warning: filesize(): stat failed for ../test.zip in /var/---/----/---/----/control/ajax/zipAJAX.php on line 21
Warning: readfile(../test.zip): failed to open stream: No such file or directory in /var/---/----/---/----/control/ajax/zipAJAX.php on line 24

You can't add the contents of a folder to a zip file with the addFile method. You have to loop the directory (http://php.net/dir) and add each file to your zip with the addFile method.
Before you send any data back to the user, you can check if the zip file exists.
$zip->close();
if(file_exists($file)) {
header("Content-type: application/zip");
header("Content-Disposition: attachment; filename=$filename");
header("Content-length: " . filesize($filename));
header("Pragma: no-cache");
header("Expires: 0");
readfile("$filename");
}
Also check that the user has write permission in the directory where you want to place the zip file.

Related

php add file to zip returning blank files

I am having an issue with the below code (it works fine on local).
I am using this for an image gallery to download a selection of images using a checkbox. Anyways, this is working fine on my localhost but when I execute this code on my live site it downloads a zip file with the correct file names but the the files are blank.
Any suggestions to why this may be happening?
<?php
function zipFilesAndDownload($file_names, $archive_file_name, $file_path)
{
$zip = new ZipArchive();
//create the file and throw the error if unsuccessful
if ($zip->open($archive_file_name, ZIPARCHIVE::CREATE) !== true) {
exit("cannot open <$archive_file_name>\n");
}
foreach ($file_names as $files) {
# download file
$download_file = file_get_contents($files);
#add it to the zip
$zip->addFromString(basename($files), $download_file);
}
$zip->close();
$zipped_size = filesize($archive_file_name);
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=$archive_file_name");
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("$archive_file_name");
unlink("$archive_file_name"); // Now delete the temp file on the server
exit;
}
if (isset($_POST['formSubmit'])) {
//$file_names=$_POST['files'];//
//$file_names = filter_var_array($_POST['files']);//works but it's the wrong method
$filter = filter_input_array(INPUT_POST, FILTER_SANITIZE_SPECIAL_CHARS); //sanitise files
$file_names = $filter['files'];
//Archive name
$archive_file_name = 'product-images.zip';
//Download Files path
$file_path = getcwd() . '';
//cal the function
zipFilesAndDownload($file_names, $archive_file_name, $file_path);
} else {
header("Refresh: 5; url= ./index.php ");
print '<h1 style="text-align:center">You you shouldn\'t be here ......</pre>
<p style="color: red;"><strong>redirection in 5 seconds</strong></p>
<pre>';
exit;
}
?>
edit: i see this in my php error log:
PHP message: PHP Warning: ZipArchive::close(): Failure to create temporary file: Permission denied in /var/www/html/wp-content/plugins/jig/download-product-images.php on line 19

Create folder in zip then add contents

What am I missing? I can't seem to get the zip to actually create a folder called "plugin" and then add the contents to that folder inside the zip. This is my code. I've tried adjusting just about everything and nothing seems to create the folder first then add the contents.
function zipFiles($file_names, $ftp_user, $archive_file_name, $file_path){
$zip = new ZipArchive('plugin');
//create the file and throw the error if unsuccessful
if ($zip->open($file_path . '/' . $archive_file_name, ZIPARCHIVE::CREATE )!==TRUE){
exit("cannot open <$archive_file_name>\n");
}
foreach($file_names as $files){
$zip->addFile($file_path . '/plugins/', $files);
}
$zip->close();
$zip_file = 'users/' . $ftp_user . '/' . $archive_file_name;
header("Content-type: application/zip");
header("Content-disposition: attachment; filename=\"" . basename($zip_file) . "\"");
header("Pragma: no-cache");
header("Expires: 0");
readfile("$zip_file");
exit;
}
If it helps - there is an actual folder called plugin that resides on the server, so if zipping that is easier, then that's OK.

php download file: header()

I need some eduction please.
At the end of each month, I want to download some data from my webserver to my local PC.
So, I've written a little script for that, which selects the data from the DB.
Next, I want to download it.
I've tried this:
$file=$month . '.txt';
$handle=fopen($file, "w");
header("Content-Type: application/text");
header("Content-Disposition: attachment, filename=" . $month . '.txt');
while ($row=mysql_fetch_array($res))
{
$writestring = $row['data_I_want'] . "\r\n";
fwrite($handle, $writestring);
}
fclose($handle);
If I run this, then the file is created, but my file doesn't contain the data that I want. Instead I get a dump from the HTML-file in my browser..
What am I doing wrong..
Thanks,
Xpoes
Below script will help you download the file created
//Below is where you create particular month's text file
$file=$month . '.txt';
$handle=fopen($file, "w");
while ($row=mysql_fetch_array($res)){
$writestring = $row['data_I_want'] . "\r\n";
fwrite($handle, $writestring);
}
fclose($handle);
//Now the file is ready with data from database
//Add below to download the text file created
$filename = $file; //name of the file
$filepath = $file; //location of the file. I have put $file since your file is create on the same folder where this script is
header("Cache-control: private");
header("Content-type: application/force-download");
header("Content-transfer-encoding: binary\n");
header("Content-disposition: attachment; filename=\"$filename\"");
header("Content-Length: ".filesize($filepath));
readfile($filepath);
exit;
Your current code does not output a file, it just sends headers.
in order for your script to work add the following code after your fclose statement.
$data = file_get_contents($file);
echo $data;

Path Name and Zip File Name showing when downloading Zip file In PHP

I am trying to write a PHP program which delivers a zip file for download. I have searched on the internet and tried all the solutions but my issue is not getting solved.
My problem is when the zip file is downloaded to a user's computer the entire path is displayed as the name of the zip file.
For Example:
Path to the Zip File: "http://www.websitename.com/folder1/folder2/"
Name of Zip File: "zbc123.zip"
When the Browser downloads the zip file, the Name of the file is as follows:
http-_www.websitename.com_folder1_folder2_zbc123.zip
I do not want the path to be the name of the downloaded zip file.
I only want the actual zip file to be displayed.
Here is my codespec:
$m_item_path_name = "http://www.websitename.com/folder1/folder2/";
$m_zip_file_name = "zbc123.zip"
//Combining the Path and the Zip file name and storing into memory variable
$m_full_path = $m_item_path_name.$m_zip_file_name;
header("Pragma: public");
header("Expires: 0");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Cache-Control: public");
header("Content-Description: File Transfer");
header("Content-type: application/octet-stream");
header("Content-Disposition: attachment; filename=\"".$m_zip_file_name."\"");
header("Content-Transfer-Encoding: binary");
header("Content-Length: ".filesize($m_item_path_name.$m_zip_file_name));
ob_end_flush();
#readfile($m_item_path_name.$m_zip_file_name);
Can anyone help me to solve this issue.
Any kind of help will be appreciated.
Thanks a lot.
try this:
<?php
$file_names = array('file1.pdf','file2.pdf');
//Archive name
$archive_file_name=$name.'Name_u_want.zip';
//Download Files path
$file_path=$_SERVER['DOCUMENT_ROOT'].'/files/';
zipFilesAndDownload($file_names,$archive_file_name,$file_path);
function zipFilesAndDownload($file_names,$archive_file_name,$file_path)
{
//echo $file_path;die;
$zip = new ZipArchive();
//create the file and throw the error if unsuccessful
if ($zip->open($archive_file_name, ZIPARCHIVE::CREATE )!==TRUE) {
exit("cannot open <$archive_file_name>\n");
}
//add each files of $file_name array to archive
foreach($file_names as $files)
{
$zip->addFile($file_path.$files);
}
$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("Content-length: " . filesize($archive_file_name));
header("Pragma: no-cache");
header("Expires: 0");
readfile("$archive_file_name");
exit;
}
?>

php header question

I'm trying to mask my download links using the code below.
It is almost working - it seems to get the file correctly however when it downloads the file is only 4kB in size.
Can anyone offer any suggestions??
Thanks!
Also please let me know if you need any additional details - I'm running this on MAMP using FF3.5.13
<?php
$filename="download.zip";
$folder = 'downloads';
$abs_path = $_SERVER['DOCUMENT_ROOT'];
$path = $abs_path . "/" . $folder ."/" .$filename; // the location of the file.
$mm_type="application/zip"; //this is for .zip files - Change this for other file types.
header("Expires: 0");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Cache-Control: public");
header("Content-Description: File Transfer");
header("Content-Type: " . $mm_type);
header('Content-Disposition: attachment; filename="'.basename($path).'"');
header("Content-Length: " . filesize($path)); // **code edited as per comments below**
header("Content-Transfer-Encoding: binary");
readfile($path); //Output file for download.
exit();
?>
UPDATE: here is what is inside the file generated
Warning: filesize() [function.filesize]: stat failed for /Applications/MAMP/htdocs/downloads/download.zip in /Applications/MAMP/htdocs/CURRENT/test.php on line 15
Warning: Cannot modify header information - headers already sent by (output started at /Applications/MAMP/htdocs/CURRENT/test.php:15) in /Applications/MAMP/htdocs/CURRENT/test.php on line 15
Warning: Cannot modify header information - headers already sent by (output started at /Applications/MAMP/htdocs/CURRENT/test.php:15) in /Applications/MAMP/htdocs/CURRENT/test.php on line 16
Warning: readfile(/Applications/MAMP/htdocs/downloads/download.zip) [function.readfile]: failed to open stream: No such file or directory in /Applications/MAMP/htdocs/CURRENT/test.php on line 17
I think this is where you got wrong:
header("Content-Length: " . filesize($file));
Change it to:
header("Content-Length: " . filesize($path));
header("Content-Length: " . filesize($file));
Where is $file being set?
This message
Warning: filesize() [function.filesize]: stat failed for /Applications/MAMP/htdocs/downloads/download.zip in /Applications/MAMP/htdocs/CURRENT/test.php on line 15
is clear enough: Your file doesn't exist.
Try:
header ("Content-Disposition: attachment; filename=".$name."\n\n");
header ("Content-Type: application/octet-stream");
header ("Content-Length: ".filesize($complete_path_file));
readfile($complete_path_file);
or also changing the content type to header("Content-type: application/force-download");

Categories