Create a zip file and download it
Add Content-length
header describing size of zip file in bytes.
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");
Also make sure that there is absolutely no white space before <?
and after ?>
. I see a space here:
↓
<?php
$file_names = array('iMUST Operating Manual V1.3a.pdf','iMUST Product Information Sheet.pdf');
zip and download files using php
Thanks for your answers.
<?php
$files = array('Dear GP.docx','ecommerce.doc');
# create new zip opbject
$zip = new ZipArchive();
# create a temp file & open it
$tmp_file = tempnam('.','');
$zip->open($tmp_file, ZipArchive::CREATE);
# loop through each file
foreach($files as $file){
# download file
$download_file = file_get_contents($file);
#add it to the zip
$zip->addFromString(basename($file),$download_file);
}
# close zip
$zip->close();
# send the file to the browser as a download
header('Content-disposition: attachment; filename=Resumes.zip');
header('Content-type: application/zip');
readfile($tmp_file);
?>
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.
create a zip file. and download it
I solved the problem and here is the right code
PerformExport method :
public String performExport(javax.servlet.http.HttpServletRequest request,javax.servlet.http.HttpServletResponse response,
String p_sBook_ID, String p_sUser_ID, String p_sFormat) {
String sReturn = _Return_OK;
try {
writeServerDebug("performExport(req,resp,'" + p_sBook_ID + "'," + p_sUser_ID + "," + p_sFormat + "):start");
// ====================================================
// = Get the template directory
// ====================================================
FilerManager myFiler = new FilerManager();
String sInputPath = myFiler.getDirectory(
FilerManager.DirectoryKind_Users, true);
// ====================================================
// = Working variables JDBC objects.
// ====================================================
Connection con = null;
Statement stmt = null;
ResultSet rs = null;
String SQL = "";
try {
writeServerDebug("performExport >> START");
// ---------------------------------------------------------
// - Establish the connection.
// ---------------------------------------------------------
con = _RepositoryBridge.getSourceDataBaseConnection();
} catch (Exception ex) {
sReturn = Repository._Return_KO;
}
HashMap<String, Object> _hCacheBook = new HashMap<String, Object>();
try {
int iSrcCount = get_RepositoryBridge().cacheQueryData("SELECT TOP(1) * FROM " + Books.Table + " WHERE " + Books.Column_IDNum + "=" + p_sBook_ID, _hCacheBook, "DataBase_Source");
int iColCount = (Integer) (_hCacheBook.get("SQL_ColumnCount"));
String sColDesc = (String) (_hCacheBook.get("SQL_ColumnDesc"));
String sColValues = (String) (_hCacheBook
.get("SQL_ColumnValues"));
int nbrCol = (Integer) (_hCacheBook.get("SQL_ColumnCount"));
String sContentType = "application/vnd.ms-objx";
response.setContentType(sContentType);
ServletOutputStream outStream = new ServletOutputStream() {
@Override
public void write(int arg0) throws IOException {
// TODO Auto-generated method stub
}
};
outStream = response.getOutputStream();
this.CreatXml(nbrCol, 1, _hCacheBook, outStream, response );
outStream.flush();
outStream.close();
}
catch (Exception ex) {
System.out.println("I AM IN THE EXCEPTION :");
ex.printStackTrace();
}
}
catch (Exception e) {
writeServerDebug("ERROR:" + e.getLocalizedMessage());
sReturn = Repository._Return_KO;
}
return sReturn;
}
CreatXML method:
public ZipOutputStream CreatXml(int nbr_col, int iLineCounter,
HashMap<String, Object> H, ServletOutputStream out , javax.servlet.http.HttpServletResponse response ) throws IOException {
ZipOutputStream zipfile = null;
String BookName = null;
String BookID = null;
int axisID = 11 ;
String TemplateChild = null;
DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = null;
try {
writeServerDebug("call function Create XML");
docBuilder = docFactory.newDocumentBuilder();
} catch (ParserConfigurationException e2) {
e2.printStackTrace();
}
// Element : book_objects
String tableName = "book_objects";
org.w3c.dom.Document doc = docBuilder.newDocument();
Element p_tableName = doc.createElement(tableName);
doc.appendChild(p_tableName);
// Element : object
Element p_object = doc.createElement("object");
String []platformeversion = JavaFunctions.convertStringToArray(Repository.Portal_Version, "=");
p_object.setAttribute("version", platformeversion[1]+" "+getVersion());
p_tableName.appendChild(p_object);
String tabCol = (String) (H.get("SQL_ColumnDesc"));
String[] colName = JavaFunctions.convertStringToArray(tabCol, ", ");
String [][]dep = null;
dep = Dependances.sReturnDependance();
String [][]colVal = new String [9][2];
int c=0;
for (int i = 1; i <= nbr_col; i++) {
String columnName = colName[i - 1];
columnName = columnName.replaceAll(" ", "");
columnName = columnName.replace("(", "");
columnName = columnName.replace(")", "");
Element nomChamps = doc.createElement(columnName);
String value = "";
value = "" + H.get(iLineCounter + "_" + i);
if(columnName.equalsIgnoreCase(Books.Column_Name)){
BookName = value;
}
if(columnName.equalsIgnoreCase(Books.Column_IDNum)){
BookID = value;
}
if(columnName.equalsIgnoreCase(Books.Column_axis_main_idnum)){
axisID = (Integer) H.get(iLineCounter + "_" + i);
}
if(columnName.equalsIgnoreCase(Books.Column_Template_Child)){
TemplateChild = (String) H.get(iLineCounter + "_" + i);
}
//retrieve the columns and their values for the dependencies
for(int cpt=0; cpt<5; cpt++){
if(dep[cpt][0].equalsIgnoreCase(columnName)){
colVal[c][0]=columnName;
colVal[c][1]= value;
c++;
}
}
nomChamps.appendChild(doc.createTextNode((String) value));
p_object.appendChild(nomChamps);
}
String label[] = JavaFunctions.convertStringToArray(TemplateChild, "/");
String path = "C:\\Fovea_Repository/output/";
File outputdirectory = new File (path);
// Create the output file
String fileName ="ExportDirectory"+ BookName +".zip";
response.setHeader( "Content-Disposition", "filename=" + fileName );
Transformer tf = null;
try {
tf = TransformerFactory.newInstance().newTransformer();
} catch (TransformerConfigurationException e1) {
e1.printStackTrace();
}
try {
// Format XML
tf.setOutputProperty(OutputKeys.INDENT, "yes");
tf.setOutputProperty(OutputKeys.METHOD, "xml");
tf.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
tf.setOutputProperty("{http://xml.apache.org/xslt}indent-amount","4");
File directory = new File ("C:/Fovea_Repository/ExportDirectory/");
if(!directory.exists()){
directory.delete();
directory.mkdir();
}
DOMSource source = new DOMSource(doc);
StreamResult res = new StreamResult(new File("C:/Fovea_Repository/ExportDirectory/dependance.xml"));
tf.transform(source, res);
//create a zip file (Export_directory)
AppZip appZip = new AppZip();
String sourcefolder = "C:/Fovea_Repository/ExportDirectory";
String outputfoler = " ";
ZipOutputStream returnFile = appZip.ZipFile(outputfoler , sourcefolder , out, BookName , BookID);
zipfile = returnFile;
} catch (TransformerException e) {
e.printStackTrace();
}
return zipfile;
}
Creating zip of multiple files and download in laravel
Only pure php code.
public function makeZipWithFiles(string $zipPathAndName, array $filesAndPaths): void {
$zip = new ZipArchive();
$tempFile = tmpfile();
$tempFileUri = stream_get_meta_data($tempFile)['uri'];
if ($zip->open($tempFileUri, ZipArchive::CREATE) !== TRUE) {
echo 'Could not open ZIP file.';
return;
}
// Add File in ZipArchive
foreach($filesAndPaths as $file)
{
if (! $zip->addFile($file, basename($file))) {
echo 'Could not add file to ZIP: ' . $file;
}
}
// Close ZipArchive
$zip->close();
echo 'Path:' . $zipPathAndName;
rename($tempFileUri, $zipPathAndName);
}
How to create a ZIP file using PHP and delete it after user downloads it?
Well, you'll have to first create the zipfile, using the ZipArchive
class.
Then, send :
- The right headers, indicating to the browser it should download something as a zip -- see
header()
-- there is an example on that manual's page that should help - The content of the zip file, using
readfile()
And, finally, delete the zip file from your server, using unlink()
.
Note : as a security precaution, it might be wise to have a PHP script running automatically (by crontab, typically), that would delete the old zip files in your temporary directory.
This just in case your normal PHP script is, sometimes, interrupted, and doesn't delete the temporary file.
create and download zip file using php
Why not use the Zip Encoding Class in Codeigniter - it will do this for you
$name = 'mydata1.txt';
$data = 'A Data String!';
$this->zip->add_data($name, $data);
// Write the zip file to a folder on your server. Name it "my_backup.zip"
$this->zip->archive('/path/to/directory/my_backup.zip');
// Download the file to your desktop. Name it "my_backup.zip"
$this->zip->download('my_backup.zip');
https://www.codeigniter.com/user_guide/libraries/zip.html
How to create a zip file and download it?
Within the line
ZipEntry anEntry = new ZipEntry(f.getPath());
you specify the path inside your zip file (i.e. f.getPath()
). If you want a shorter path or none at all just manipulate this part (e.g. f.getName()
).
Related Topics
Gmail Fsockopen(): Ssl Operation Failed Error with Codeigniter and Xampp
How to Show a Where Clause Just for One Field in MySQL
How Can One Run Multiple Versions of PHP 5.X on a Development Lamp Server
Calling a Particular PHP Function on Form Submit
Codeigniter - Why Use Xss_Clean
Why Does Tcpdf Ignore My Inline CSS
Replace String in Text File Using PHP
What Does This Mean? "Parse Error: Syntax Error, Unexpected T_Paamayim_Nekudotayim"
Remove Index.Phproute=Common/Home from Opencart
How to Set a Cookie and Then Redirect in PHP
Simplest Way to Detect Client Locale in PHP
What Is the Max Key Size for an Array in PHP
How to Read a Single File Inside a Zip Archive
PHP Production Server - Turn on Error Messages
Unset a Column in a Multidimensional Array