Home > Back-end >  How to create temporary files in php to send them by email?
How to create temporary files in php to send them by email?

Time:10-29

I have this code that allows me to retrieve a string from a base64 encoded XML file. I put it in a TXT file, then I decode it to obtain the desired PDF. Then I send this PDF as an attachment and insert the base64 string in the database. Then I delete the TXT file and PDF from the folders.

Everything works correctly. But I would like a solution to not create these files on the server and then delete them.

I am looking for a more secure solution, I tried the tmpfile function but the file is not sent by mail because it is deleted directly after.

Can you help me?

<?php

            //Function to keep only the content of the <GraphicImage> tags
            function multiSplit($string)
                {
                    $output = array();
                    $cols = explode("<GraphicImage>", $string);

                foreach ($cols as $col)
                {
                    $dashcols = explode("</GraphicImage>", $col);
                    $output[] = $dashcols[0];
                }
                
                return $output;
            }

            $envoi = $submission_id.'_envoi';
            
            //We put the content of the tags in the variable $DHL
            $DHL = multiSplit($output);

            //We create two unique file names  
            $filename1 = $envoi.'.txt';
            $filename2 = $envoi.'.pdf';

            //We write the content of the tags in the txt file 
            $file1 = "D:/Data/Sites/sav/API_label/TXT/$filename1";                       
            file_put_contents($file1, print_r($DHL[1], true) . PHP_EOL, FILE_APPEND | LOCK_EX);

            
            $pdf_base64 = $file1;
            //Get File content from txt file
            $pdf_base64_handler = fopen($pdf_base64,'r');
            $pdf_content = fread ($pdf_base64_handler,filesize($pdf_base64));
            fclose ($pdf_base64_handler);
            //Decode pdf content
            $pdf_decoded = base64_decode ($pdf_content);
            //Write data back to pdf file
            $pdf = fopen ("D:/Data/Sites/sav/API_label/PDF/$filename2",'w');
            fwrite ($pdf,$pdf_decoded);
            //close output file
            fclose ($pdf);
            // echo 'Done';

             //SendGrid Part
             $email = new Mail();
             $email->setFrom("[email protected]", "Sender");
             $email->addTo("$EMAIL", "Recipient");
             $email->setSubject("Etiquettes DHL");
             $email->addContent("text/html", "<strong>Hello</strong>");
 
             $file_encoded = base64_encode(file_get_contents("D:/Data/Sites/sav/retours/API_label/PDF/$filename2"));
             $email->addAttachment($file_encoded, "application/pdf", "$filename2", "attachment");
 
 
             $sendgrid = new \SendGrid('SG.m7481IOix24');
             try {
                 $response = $sendgrid->send($email);

             } catch (Exception $e) {
                 // echo 'Caught exception: ' .  $e->getMessage() . "\n";
             }   

             //Insertion of the values in the database
             try {
                // Connect to db
                $db = new db('mysql:dbname=jotform; host=localhost', 'user', 'password');
                $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

                // Set SQL
                $sql = 'INSERT INTO DHL (submission_id, formID, identite, email, adresse, telephone, label_envoi, commercial_invoice) 
                VALUES (:submission_id, :formID, :NOM, :EMAIL, :ADRESSE, :TELEPHONE, :file_encoded, :COMMERCIAL_INVOICE)';

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

                // Execute query
                $query->execute(array(':submission_id' => $submission_id, ':formID' => $formID, ':NOM' => $NOM, ':EMAIL' => $EMAIL, ':ADRESSE' => $ADRESSE, ':TELEPHONE' => $TELEPHONE, 
                ':file_encoded' => $file_encoded, ':COMMERCIAL_INVOICE' => $COMMERCIAL_INVOICE));
            } catch (PDOException $e) {
                echo 'Error: ' . $e->getMessage();
            } 
            
            //Deleting txt and pdf files
            //PDF
            unlink("D:/Data/Sites/sav/API_label/PDF/$filename2");

            //TXT
            unlink("D:/Data/Sites/sav/API_label/TXT/$filename1"); 

CodePudding user response:

Unless I've misunderstood something, it seems like these two temporary files don't add any value and can be removed - instead you can just directly use the variables you wrote to the files as the inputs to the next steps of the process.

This version should complete the same process without writing to any files:

//Function to keep only the content of the <GraphicImage> tags
function multiSplit($string) {
  $output = array();
  $cols = explode("<GraphicImage>", $string);

  foreach($cols as $col) {
    $dashcols = explode("</GraphicImage>", $col);
    $output[] = $dashcols[0];
  }

  return $output;
}

$envoi = $submission_id.'_envoi';
$filename2 = $envoi.'.pdf';

//We put the content of the tags in the variable $DHL
$DHL = multiSplit($output);

//We write the content of the tags
$print1 = print_r($DHL[1], true).PHP_EOL;

//Decode pdf content
$pdf_decoded = base64_decode($print1);

//SendGrid Part
$email = new Mail();
$email->setFrom("[email protected]", "Sender");
$email->addTo("$EMAIL", "Recipient");
$email->setSubject("Etiquettes DHL");
$email->addContent("text/html", "<strong>Hello</strong>");

$file_encoded = base64_encode($pdf_decoded);
$email->addAttachment($file_encoded, "application/pdf", "$filename2", "attachment");

$sendgrid = new \SendGrid('SG.m7481IOix24');

try {
  $response = $sendgrid->send($email);

} catch (Exception $e) {
  // echo 'Caught exception: ' .  $e->getMessage() . "\n";
}

//Insertion of the values in the database
try {
  // Connect to db
  $db = new db('mysql:dbname=jotform; host=localhost', 'user', 'password');
  $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

  // Set SQL
  $sql = 'INSERT INTO DHL (submission_id, formID, identite, email, adresse, telephone, label_envoi, commercial_invoice)
 VALUES(:submission_id,:formID,:NOM,:EMAIL,:ADRESSE,:TELEPHONE,:file_encoded,:COMMERCIAL_INVOICE)';

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

  // Execute query
  $query->execute(array(':submission_id' => $submission_id, ':formID' => $formID, ':NOM' => $NOM, ':EMAIL' => $EMAIL, ':ADRESSE' => $ADRESSE, ':TELEPHONE' => $TELEPHONE, ':file_encoded' => $file_encoded, ':COMMERCIAL_INVOICE' => $COMMERCIAL_INVOICE));
} catch (PDOException $e) {
  echo 'Error: '.$e->getMessage();
}

It's unclear to me why you use base64_decode to read the first file, since there's no evidence of it having been base64-encoded to begin with (it was just the result of a print_r statement on some XML, as far as I can see). Therefore I've also removed that.

  • Related