How to Upload Phpmailer File in Netbeans

A cantankerous-disciplinary full-stack Web Developer/Designer, Information Analyst, and Content Creator/Author

Sending Attachments with PHPMailer and AJAX Upload

Published Jun 08, 2018 Final updated Dec 05, 2018

Challenge

A few weeks agone, I was asked to create a form that would allow the user to send their feedback with attachments. And then output all the user inputs with the attachments on a pdf file before sending it off to the appropriate recipient.

Solution

And so I decided to utilize PHPMailer and Dompdf to help me to achieve that. Too, I decided to use AJAX upload for a better user experience.

First, y'all need to upload the zipper to the server, grab all the user inputs and print them on a pdf file. This pdf file will be saved to the server too. So we send the attachments with the pdf file to the recipient. We delete the attachment and the pdf after sending the email (if you lot don't desire to go along them in the server).

Slim Framework

The alive site is on WordPress, but I simplified the code for this mail using Slim to demonstrate this solution.

AJAX

To apply AJAX to the file upload, you need FormData object from JavaScript:

                      # Syntax            var formData = new FormData(form)                  

And you need the file input in your HTML, for case:

          <input type="file" id="userfile" name="userfile">                  

So, this is what I take on my HTML (I have ii file inputs and then that the user won't upload more than than ii files):

          <div class="groups row">   <div course="grouping">       <div form="input-file">           <input type="file" proper noun="sender-attachments[]">       </div>       <a href="#" course="button-clear hide" title="Clear the image">           <i class="fi-x-circumvolve"></i>       </a>   </div>    <div form="group">       <div course="input-file">           <input type="file" name="sender-attachments[]">       </div>       <a href="#" class="push-clear hide" title="Clear the image">           <i class="fi-x-circle"></i>       </a>   </div> </div>                  

While on the JavaScript side:

          var formdata = false if (window.FormData) {   formdata = new FormData() }  // Iterate through the elements and append information technology to the form data, with the correct type. target.find('input, textarea').not('input[type=file]').each(function () {   formdata.suspend(this.proper name, this.value) })  // Get file data. var els = certificate.querySelectorAll('input[type=file]') var i = 0 for (i = 0; i < els.length; i++) {   // Make sure the file has content before suspend information technology to the course object.   var file = els[i]    if (file.files.length > 0) {     var fileData = file.files[0]      // Only process paradigm files.     if (!fileData.type.lucifer('image.*')) {       continue     }      // Appends the currently selected File of an <input type="file" id="file"> chemical element the FormData instance     // which is after to be sent as multipart/form-data XHR request body     formdata.append('sender-attachments[]', fileData)   } }                  

Then all the data are sent to the server via jQuery's AJAX:

          $.ajax({   type: 'POST',   url: target.attr('activity'),   data: formdata,   processData: false, // tell jQuery not to process the data   contentType: fake, // tell jQuery not to set contentType   success: function (responseData, textStatus, jqXHR) {   ...   ...   ...                  

$_File

On the server side, you need to procedure the $_FILE data to make sure the file size, the extension, etc are ok:

          private office uploadFiles() {     // Re-adjust the default file array.     $files = [];     if (isset($_FILES['sender-attachments']) && count($_FILES['sender-attachments']) > 0) {         $files = $this->reArrayUploadFiles($_FILES['sender-attachments']);     }      // Validate the uploaded files.     $validated = [];     foreach ($files as $cardinal => $file) {         $validated[] = $this->validateUploadFiles($file, $this->maxsize, $this->whitelist);     }      // Scoop for any mistake.     $error_upload = [];     foreach ($validated equally $key => $file) {         if ($file ['error']) {             if (isset($file ['name'])) {                 $error_upload[] = $file ['name'] . ' - ' . $file ['error'] . ' ';             } else {                 $error_upload[] = $file ['error'] . ' ';             }         }     }      // Make sure no upload errors.     if (count($error_upload) > 0) {         throw new \Exception(implode('; ', $error_upload), 400);     }     return $files; }                  

This tedious process is abstracted into a couple of functions - reArrayUploadFiles() and validateUploadFiles(). What reArrayUploadFiles() does is to re-order the the default array from $_FILES into a cleaner array. For example, when uploading multiple files, the $_FILES assortment is created in the form:

          Array (     [name] => Assortment         (             [0] => foo.txt             [1] => bar.txt         )      [type] => Array         (             [0] => text/plain             [one] => text/evidently         )      [tmp_name] => Array         (             [0] => /tmp/phpYzdqkD             [1] => /tmp/phpeEwEWG         )      [error] => Array         (             [0] => 0             [ane] => 0         )      [size] => Array         (             [0] => 123             [one] => 456         ) )                  

Just this is a cleaner format:

          Array (     [0] => Array         (             [name] => foo.txt             [type] => text/plain             [tmp_name] => /tmp/phpYzdqkD             [mistake] => 0             [size] => 123         )      [1] => Array         (             [name] => bar.txt             [type] => text/plainly             [tmp_name] => /tmp/phpeEwEWG             [error] => 0             [size] => 456         ) )                  

After rearranging the array we tin validate it with validateUploadFiles():

          // Validate the file array. function validateUploadFiles (     $file = '',     $maxsize = two,     $whitelist = [] ) {     // File upload fault messages.     // http://php.cyberspace/transmission/en/features.file-upload.errors.php     $phpFileUploadErrors = [         0 => 'There is no error, the file uploaded with success',         ane => 'The uploaded file exceeds the upload_max_filesize directive in php.ini',         2 => 'The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form',         iii => 'The uploaded file was just partially uploaded',         4 => 'No file was uploaded',         6 => 'Missing a temporary binder',         7 => 'Failed to write file to deejay.',         8 => 'A PHP extension stopped the file upload.',     ];      $max_upload_size = $maxsize * 1024 * 1024; // 2MB      // Use the default whitelist if information technology is not provided.     if (count($whitelist) === 0) {         $whitelist = [             'image/jpeg',             'epitome/png',             'image/gif',             'video/mpeg',             'video/mp4',             'application/msword',             'application/vnd.openxmlformats-officedocument.wordprocessingml.document',             'application/pdf'         ];     }      $result = [];     $issue['mistake'] = 0;      if ($file['error']) {         $issue['proper noun'] = $file['name'];         $result['mistake'] = $phpFileUploadErrors[$file['error']];         return $issue;     }      if (!in_array($file['type'], $whitelist)) {         $event['name'] = $file['name'];         $result['error'] = 'must exist a jpeg, or png';     } elseif(($file['size'] > $max_upload_size)){         $result['name'] = $file['proper name'];         $result['fault'] = $this->convertToReadableSize($file['size']) . ' bytes! Information technology must not exceed ' . $this->convertToReadableSize($max_upload_size) . ' bytes.';     }     render $result; }                  

Dompdf

We simply make the pdf after the file validation:

          private function createDompdf() {     return new Dompdf(); }  individual function makePdf(array $data, array $files) {     // Make pdf.     // Instantiate and utilise the dompdf class     $dompdf = $this->createDompdf();      // Create a DOM object from a HTML file.     $filePath = 'view/pdf.php';     if(file_exists($filePath)) {          // Extract the variables to a local namespace         extract($data);          // Start output buffering         ob_start();          // Include the template file         include $filePath;          // End buffering and return its contents         $html = ob_get_clean();     }      $dompdf->loadHtml($html);      // (Optional) Setup the paper size and orientation     $dompdf->setPaper('A4', 'portrait');      // Render the HTML as PDF     $dompdf->render();      // Save the generated PDF document to disk instead of sending it to the browser.     $output = $dompdf->output();     $pdfOutput = 'Quality_Control_Feedback_' . engagement("YmdHis") . '.pdf';     file_put_contents($this->uploaddir . $pdfOutput, $output);      return $this->uploaddir . $pdfOutput; }                  

The template for the pdf:

          <master>     <div course="row row-pdf">         <div grade="grid-container">             <div grade="grid-x grid-padding-10">                  <div class="large-12 jail cell">                     <p><b>Proper name:</b> <?php echo $information['sender-proper noun']; ?></p>                     <p><b>Contact Email:</b> <?php repeat $information['sender-email']; ?></p>                 </div>                  <div form="large-12 cell">                     <hr>                 </div>                  <div course="large-12 jail cell">                      <p><b>General Description of Problem/Business organization/Fault:</b></p>                      <p><?php echo $information['sender-clarification']; ?></p>                 </div>                  <div class="large-12 prison cell">                     <hr>                 </div>                   <div class="large-12 cell">                      <p><b>Image(s) attached:</b> <?php if (count($files) > 0) { echo 'Aye'; } else { echo 'No'; } ?></p>                 </div>              </div>         </div>     </div>      <div class="row row-attachments">          <?php         // Attachments         if (count($files) > 0) {             foreach ($files as $file) {                 $imagePath = $this->uploaddir . basename($file['name']);                 // $imagePath = 'http://lorempixel.com/400/200/';         ?>             <div class="item-image">                 <img src="<?php repeat $imagePath;?>" alt="dummy"/>                 <p><?php repeat basename($file['name']); ?></p>             </div>         <?php             }         }         ?>      </div> </master>                  

PHPMailer

After the process above is done, here is how PHPMailer comes in:

          private function createPHPMailer(bool $boolean) {     render new PHPMailer($boolean); }  public function sendMail( {     // store the posted data.     $data = $_POST;      $mail = $this->createPHPMailer(true);     ...     ...     ...      $files = $this->uploadFiles();     if (count($files) > 0) {         foreach ($files as $file) {             if (move_uploaded_file($file['tmp_name'], $this->uploaddir . basename( $file['proper name']))) {                 $this->uploaddir . $file['name'];             }              // Add attachments.             $postal service->addAttachment($this->uploaddir . basename($file['name']));         }     }      // Attache pdf.     $pdfPath = $this->makePdf($data, $files);     if (file_exists($pdfPath)) {         // Add attachments.         $postal service->addAttachment($pdfPath);     }      $mail->isHTML(truthful);     $mail->Subject = 'Quality control feedback from ' . $data['sender-name'];     $mail->Trunk = ' ' .         'Proper name: ' . $information['sender-name'] . '<br/>' .         'Contact Email: ' . $data['sender-email'] . '<br/>' .         'General Description of Problem/Business organization/Mistake: ' . $data['sender-description']         ;      $mail->transport();     ...     ...     ... }                  

We delete the uploaded files and the pdf after $post->send():

          // Remove the uploaded files. if (count($files) > 0) {     foreach ($files every bit $file) {         $path = $this->uploaddir . basename($file['name']);         if (file_exists($path)) {             unlink($path);         }     } }  // Delete pdf. if (file_exists($pdfPath)) {     unlink($pdfPath); }                  

Determination

Information technology is not difficult at all to send attachments in PHP and upload files with AJAX. But it tin can be fourth dimension consuming as the process is quite tedious. There are plenty of validation and checking that must be taken into business relationship otherwise it will end up with a bad user experience. Y'all can download this working sample on GitHub and run it on your local machine:

          # Dependencies $ cd [my-app-name] $ composer update  # Product build $ php -S 0.0.0.0:8181 -t public                  

Make certain that the port 8181 is not occupied by any other app before accessing it at http://0.0.0.0:8181/. You should see the post-obit screen shots on your browser:

attachement.png

This is the screen shot from the actual site in which more than input fields are required:

attachement-caremed.png

duncanwilisting.blogspot.com

Source: https://www.codementor.io/@lautiamkok/sending-attachments-with-phpmailer-and-ajax-upload-kaoel5byv

0 Response to "How to Upload Phpmailer File in Netbeans"

Postar um comentário

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel