Home > Software design >  How to create a zip file with PDF files with the addFromString function in php?
How to create a zip file with PDF files with the addFromString function in php?

Time:10-30

I have this code broken down into two parts:

  • The first one create me a zip file empty and download it.
  • The second one download me from my database a PDF file that I decoded in base64.

Both work well separately. I would like to be able to merge them and download in zip format two PDF files that are in my database.

I would like to use the addFromString function to not create a folder on my server but to download the zip file directly for the user.

Can you help me please? Thanks for your help

<?php


include '../include/classe_PDO.php';

$suivi = $_POST['suivi'];

// //ZIP PART
//Name zip folder with date
$dirzip = date('Ymd His')."_andromeda";

// Zip creation        
$nomzip = "C:/wamp64/www\Dylan/SAV/final/include/$dirzip.zip"; 
$zip = new ZipArchive;
if($zip -> open($nomzip, ZipArchive::CREATE ) === TRUE)
{ 
    $dir = opendir($chemin); 
    while($fichier = readdir($dir)) 
    { 
        if(is_file($chemin.$fichier)) 
        { 
          $zip -> addFromString($file, $decoded);
        } 
    } 
    $zip ->close(); 
} 

//Zip download
header('Content-Type: application/zip');
header('Content-Disposition: attachment; filename="'.basename($nomzip).'"');
header('Content-Length: ' . filesize($nomzip));

flush();
readfile($nomzip);  
         

//DOWNLOAD PART
 try {
  // Connect to db
  $db = new db('mysql:dbname=jotform; host=localhost', 'root', '');
  $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

  // Set SQL
  $sql = "SELECT * FROM `dhl` WHERE `submission_id` = :suivi";

  // Prepare query
  $query = $db->prepare($sql);

  // Execute query
  $query->execute(array(':suivi' => $suivi));

  foreach  ($query as $row) {
    
          $filedata = $row['label_envoi']; //get base64 data from query result
          $decoded = base64_decode($filedata); //decode base64 to binary

          $filedata2 = $row['label_retour']; //Second column
          $decoded2 = base64_decode($filedata2); 
          
          //set suitable HTTP response headers
          header('Content-Description: File Transfer'); 
          header('Content-Type: application/octet-stream'); 
          header('Content-Disposition: attachment; filename="label.pdf"');
          header('Expires: 0'); 
          header('Cache-Control: must-revalidate'); 
          header('Pragma: public'); 
          //output the binary file data in the body of the response
          echo $decoded;
          
  }


} catch (PDOException $e) {
  echo 'Error: ' . $e->getMessage();
}        



?>

CodePudding user response:

You need to loop through your database rows and add each piece of decoded file data to the zip file. Then download the zip at the end.

For example:

include '../include/classe_PDO.php';

$suivi = $_POST['suivi'];

// //ZIP PART
//Name zip folder with date
$dirzip = date('Ymd His')."_andromeda";

// Zip creation        
$nomzip = "C:/wamp64/www/Dylan/SAV/final/include/$dirzip.zip"; 
$zip = new ZipArchive;

if ($zip->open($nomzip, ZipArchive::CREATE ) === TRUE)
{
  try {
    //connect to DB
    $db = new db('mysql:dbname=jotform; host=localhost', 'root', '');
    $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

    //prepare and execute query
    $sql = "SELECT * FROM `dhl` WHERE `submission_id` = :suivi";
    $query = $db->prepare($sql);
    $query->execute(array(':suivi' => $suivi));

    foreach ($query as $row) {
      //decode base64 to binary
      $decoded = base64_decode($row['label_envoi']); 
      $decoded2 = base64_decode($row['label_retour']);
    
      //add to zip
      //N.B. if there could be more than one row returned by the database, you'll need to ensure the PDFs have unique names instead of these hard-coded ones
      $zip->addFromString("label1.pdf", $decoded);
      $zip->addFromString("label2.pdf", $decoded2);
    }
  }
  catch (PDOException $e) {
    echo 'Error: ' . $e->getMessage();
  }

  $zip ->close();

  //Zip download
  header('Content-Type: application/zip');
  header('Content-Disposition: attachment; filename="'.basename($nomzip).'"');
  header('Content-Length: ' . filesize($nomzip));

  flush();
  readfile($nomzip);
}
else
{
  echo "Error - Zip file could not be created";
}
  • Related