html2pdf zip multiple pdf files php mysql - php

I need to zip multiple pdf documents generated with html2pdf. I managed to create the pdf files in the tmp/ directory but the zip file created cannot be opened. Any idea ?
This is what I did:
<?php
$tmp='/opt/lampp/htdocs/rapport/tmp';
$file = '/opt/lampp/htdocs/rapport/tmp/my-pdf.zip';
$zip = new ZipArchive();
$zip->open($file, ZipArchive::OVERWRITE);
ob_start();
Here the part to save the zip file with all the pdf files inside:
try
{
$html2pdf = new Html2Pdf('P', 'A4', 'fr');
$html2pdf->pdf->SetDisplayMode('fullpage');
$html2pdf->writeHTML($content, isset($_GET['vuehtml']));
//$content=ob_end_clean();
//$html2pdf->Output($tablename.'-'.$idEcht.'-NGSReport.pdf','F');
//$html2pdf->Output(__DIR__ .$tablename.'-'.$idEcht.'-NGSReport.pdf','F');
$html2pdf->Output('/opt/lampp/htdocs/rapport/tmp/'.$tablename.'-'.$idEcht.'-NGSReport.pdf','F');
// ADD PDF FILE TO ZIP
$zip->addFile('/opt/lampp/htdocs/rapport/tmp/'.$tablename.'-'.$idEcht.'-NGSReport.pdf');
unset($html2pdf);
}
catch(HTML2PDF_exception $e) {
echo $e;
exit;
}
}
}
//After I loop ends, I close the zip file and force download
$zip->close();
header('Content-type: application/zip');
header('Content-Disposition: attachment; filename="my-pdf.zip"');
readfile('my-pdf.zip');
mysqli_close($conn);

Related

Add files to zip and download zip using 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.

PHP Download Multiple Files in Zip folder [duplicate]

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

creating zip of big folder with pdf files

I'm creating zip of folder with pdf and txt files, its working well. but where I creating zip of folder with above 30 files ( 389 KB each file) i getting empty zip. why?
here's my code:
include("include/zip_min.inc");
if($_GET['create_zip'])
{
include("include/zip_min.inc");
$zipfile = new zipfile();
$files_arr=scandir($_GET['path']);
foreach ($files_arr as $folder)
{
if(( strpos("-".$folder,".pdf") || strpos("-".$folder,".TXT") ) )//&& $k<30
{
$k++;
$fileonserver = $_GET['path']."/".$folder;//"path/to/file/oldfilename.txt";
$filename =$folder;
$zipfile -> addFile(file_get_contents($fileonserver), $filename);
}
}
// Force download the zip
header("Content-type: application/octet-stream");
header("Content-disposition: attachment; filename=test.zip");
echo $zipfile -> file();
}

Php code to compress all files as zip not working fine

I have this script to download all files as zip from database, but it only gets the first file saved in database - the others are not showing.
Below is a list of the files I have in the database, which I want to include in the zip:
lginin
logersutil.php
lgininh.js
Readme.md
And my code:
<?php
if(isset($_POST['download'])){
try{
$db_conn = new PDO('mysql:host='.DB_HOST.';dbname='.DB_NAME,DB_USERNAME,DB_PASSWORD);
$db_conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$post_stmt = $db_conn->prepare("SELECT * FROM jailorgchild WHERE jailchildbasname = :BasNameJa");
$post_stmt->bindParam(':BasNameJa', basename(dirname(__FILE__)));
$post_stmt->execute();
while ($rowss = $post_stmt->fetch(PDO::FETCH_ASSOC)){
$files = array(''.$rowss["jailchillink"].'','codejail.cj');
# 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='.basename(dirname(__FILE__)).'.zip');
header('Content-type: application/zip');
readfile($tmp_file);
} }catch (PDOException $e){ echo 'Connection failed: ' . $e->getMessage();}
}
?>
In your current code, you're basically making 1 new zip file and returning it for each row. Since the client can only read 1 response, they will obviously never see more than 1 row.
So what you need to do, is make sure to add all files to the zip before you send it out. Like so:
<?php
if(isset($_POST['download'])){
try{
$db_conn = new PDO('mysql:host='.DB_HOST.';dbname='.DB_NAME,DB_USERNAME,DB_PASSWORD);
$db_conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$post_stmt = $db_conn->prepare("SELECT * FROM jailorgchild WHERE jailchildbasname = :BasNameJa");
$post_stmt->bindParam(':BasNameJa', basename(dirname(__FILE__)));
$post_stmt->execute();
// here we create a temporary array to hold all the filenames
// and fill it with the file you always want to have inserted
$files = array('codejail.cj');
while ($rowss = $post_stmt->fetch(PDO::FETCH_ASSOC)){
// now fill the array with your files
$files[] = $rowss['jailchillink'];
}
// and now we finally start processing them all, after having finished reading from the DB
# 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='.basename(dirname(__FILE__)).'.zip');
header('Content-type: application/zip');
readfile($tmp_file);
} catch (PDOException $e){
echo 'Connection failed: ' . $e->getMessage();
}
}
?>

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