Create Dynamic PDF Send As Attachment with Email in PHP

Send pdf file php

I think the way an array of attachments works is kind of cumbersome. Usually the PHP guys are right on the money, but this is just counter-intuitive. It should have been more like:

Array
(
[0] => Array
(
[name] => facepalm.jpg
[type] => image/jpeg
[tmp_name] => /tmp/phpn3FmFr
[error] => 0
[size] => 15476
)

Anyways, here is a fuller example than the sparce one in the documentation above:

foreach ( $_FILES [ «attachment» ][ «error» ] as $key => $error )
$tmp_name = $_FILES [ «attachment» ][ «tmp_name» ][ $key ];
if (! $tmp_name ) continue;

$name = basename ( $_FILES [ «attachment» ][ «name» ][ $key ]);

if ( $error == UPLOAD_ERR_OK )
if ( move_uploaded_file ( $tmp_name , «/tmp/» . $name ) )
$uploaded_array [] .= «Uploaded file ‘» . $name . «‘.
\n» ;
else
$errormsg .= «Could not move uploaded file ‘» . $tmp_name . «‘ to ‘» . $name . «‘
\n» ;
>
else $errormsg .= «Upload error. [» . $error . «] on file ‘» . $name . «‘
\n» ;
>
?>

Do not use Coreywelch or Daevid’s way, because their methods can handle only within two-dimensional structure. $_FILES can consist of any hierarchy, such as 3d or 4d structure.

The following example form breaks their codes:

As the solution, you should use PSR-7 based zendframework/zend-diactoros.

use Psr \ Http \ Message \ UploadedFileInterface ;
use Zend \ Diactoros \ ServerRequestFactory ;

$request = ServerRequestFactory :: fromGlobals ();

if ( $request -> getMethod () !== ‘POST’ ) http_response_code ( 405 );
exit( ‘Use POST method.’ );
>

$uploaded_files = $request -> getUploadedFiles ();

if (
!isset( $uploaded_files [ ‘files’ ][ ‘x’ ][ ‘y’ ][ ‘z’ ]) ||
! $uploaded_files [ ‘files’ ][ ‘x’ ][ ‘y’ ][ ‘z’ ] instanceof UploadedFileInterface
) http_response_code ( 400 );
exit( ‘Invalid request body.’ );
>

$file = $uploaded_files [ ‘files’ ][ ‘x’ ][ ‘y’ ][ ‘z’ ];

if ( $file -> getError () !== UPLOAD_ERR_OK ) http_response_code ( 400 );
exit( ‘File uploading failed.’ );
>

$file -> moveTo ( ‘/path/to/new/file’ );

The documentation doesn’t have any details about how the HTML array feature formats the $_FILES array.

Array
(
[document] => Array
(
[name] => sample-file.doc
[type] => application/msword
[tmp_name] => /tmp/path/phpVGCDAJ
[error] => 0
[size] => 0
)
)

Multi-files with HTML array feature —

Array
(
[documents] => Array
(
[name] => Array
(
[0] => sample-file.doc
[1] => sample-file.doc
)

[type] => Array
(
[0] => application/msword
[1] => application/msword
) [tmp_name] => Array
(
[0] => /tmp/path/phpVGCDAJ
[1] => /tmp/path/phpVGCDAJ
)
Читайте также:  Php language level phpstorm

The problem occurs when you have a form that uses both single file and HTML array feature. The array isn’t normalized and tends to make coding for it really sloppy. I have included a nice method to normalize the $_FILES array.

function normalize_files_array ( $files = [])

foreach( $files as $index => $file )

if (! is_array ( $file [ ‘name’ ])) $normalized_array [ $index ][] = $file ;
continue;
>

foreach( $file [ ‘name’ ] as $idx => $name ) $normalized_array [ $index ][ $idx ] = [
‘name’ => $name ,
‘type’ => $file [ ‘type’ ][ $idx ],
‘tmp_name’ => $file [ ‘tmp_name’ ][ $idx ],
‘error’ => $file [ ‘error’ ][ $idx ],
‘size’ => $file [ ‘size’ ][ $idx ]
];
>

?>

The following is the output from the above method.

Array
(
[document] => Array
(
[0] => Array
(
[name] => sample-file.doc
[type] => application/msword
[tmp_name] => /tmp/path/phpVGCDAJ
[error] => 0
[size] => 0
)

[documents] => Array
(
[0] => Array
(
[name] => sample-file.doc
[type] => application/msword
[tmp_name] => /tmp/path/phpVGCDAJ
[error] => 0
[size] => 0
) [1] => Array
(
[name] => sample-file.doc
[type] => application/msword
[tmp_name] => /tmp/path/phpVGCDAJ
[error] => 0
[size] => 0
)

Источник

How to Create PDF File and Send as Attachment With Email in PHP

How to upload image easily in PHP using MySql

Hello guys! today i will teach you How to Create PDF file and send as attachment with email in PHP. Creating a pdf file from mysql database and sending that dynamically generated pdf file as attachment with email is a very common feature in most of enterprise level of web application.

If any large web application we have to send email with dynamically generated pdf file for providing such type of data information. In this tutorial we will dis]scuss this topic in which we have learn how can we create dynamic pdf file from mysql database by using domPDF library and then after we will send that dynamically created pdf file will send as attachment with email using PHPMailer in PHP script. So, here we have learn PHP send email with PDF attachment. I will describe how to fetch data from Mysql database and create PDF file from that data and attach that PDF file to an HTML email and lastly send it.

Insert this code in Index.ph

prepare($query); $statement->execute(); $result = $statement->fetchAll(); $output = '
'; return $output; > if(isset($_POST["action"])) < include('pdf.php'); $file_name = md5(rand()) . '.pdf'; $html_code = ''; $html_code .= fetch_customer_data($connect); $pdf = new Pdf(); $pdf->load_html($html_code); $pdf->render(); $file = $pdf->output(); file_put_contents($file_name, $file); require 'class/class.phpmailer.php'; $mail = new PHPMailer; $mail->IsSMTP(); //Sets Mailer to send message using SMTP $mail->Host = 'smtpout.secureserver.net'; //Sets the SMTP hosts of your Email hosting, this for Godaddy $mail->Port = '80'; //Sets the default SMTP server port $mail->SMTPAuth = true; //Sets SMTP authentication. Utilizes the Username and Password variables $mail->Username = 'xxxxxxxxxx'; //Sets SMTP username $mail->Password = 'xxxxxxxxxx'; //Sets SMTP password $mail->SMTPSecure = ''; //Sets connection prefix. Options are "", "ssl" or "tls" $mail->From = 'itsourcecode.com'; //Sets the From email address for the message $mail->FromName = 'itsourcecode.com'; //Sets the From name of the message $mail->AddAddress('[email protected]', 'Name'); //Adds a "To" address $mail->WordWrap = 50; //Sets word wrapping on the body of the message to a given number of characters $mail->IsHTML(true); //Sets message type to HTML $mail->AddAttachment($file_name); //Adds an attachment from a path on the filesystem $mail->Subject = 'Customer Details'; //Sets the Subject of the message $mail->Body = 'Please Find Customer details in attach PDF File.'; //An HTML or plain text message body if($mail->Send()) //Send an Email. Return true on success or false on error < $message = '

Create Dynamic PDF Send As Attachment with Email in PHP

Источник

Читайте также:  Php массивы в html

Webslesson

PHP, MySql, Jquery, AngularJS, Ajax, Codeigniter, Laravel Tutorial

Sunday, 12 August 2018

Create Dynamic PDF & Send as Attachment with Email in PHP

If you are trying to create dynamic pdf file from mysql database and then after you want to send that dynamically generated pdf file as attachment with email, this is a very common feature in most of enterprise level web application. Because if any large web application then we have to send email with dynamically generated pdf file for providing such type of data information. So, in this post we have conver this topic in which we have learn how can we create dynamic pdf file from mysql database by using domPDF library and then after we will send that dynamically created pdf file will send as attachment with email using PHPMailer in PHP script. So, here we have learn PHP send email with PDF attachment.

In this tutorial, we will describe you how to fetch data from Mysql database and create PDF from that data and then after attach that PDF file to an HTML email and lastly send it. Here we have use domPDF for PDF generation and PHPMailer for sending email.

After searching on internet regarding how to create PDF file in PHP, so after searching we have found dompdf library which is the best library for create PDF file from HTML. This library simply convert HTML code of any web page and converts it to a PDF. And for sending email we have found PHPMailer library, this library has been easy to use and it can send HTML email with file attachment. So, by using both library we have make our task like create dynamic pdf file and send email as attachment.

Читайте также:  Сколько времени изучать питон

Before learning this topic, in your mind will generate one question how to generate pdf file and then after it will be send as attachment, so here we will be creating PDF file temporary by using domPDF library which a library which has convert HTML info PDF file and then after by using PHPMailer which has been used for send email in our PHP script and after sending of email with attached PDF file, that file will be removed from folder. So, this is whole process of creating PDF file and sending email with attachment in PHP script using Dompdf and PHPMailer library.

Source Code

index.php

 prepare($query); $statement->execute(); $result = $statement->fetchAll(); $output = ' 
'; foreach($result as $row) < $output .= ' '; > $output .= '
Name Address City Postal Code Country
'.$row["CustomerName"].' '.$row["Address"].' '.$row["City"].' '.$row["PostalCode"].' '.$row["Country"].'
'; return $output; > if(isset($_POST["action"])) < include('pdf.php'); $file_name = md5(rand()) . '.pdf'; $html_code = ''; $html_code .= fetch_customer_data($connect); $pdf = new Pdf(); $pdf->load_html($html_code); $pdf->render(); $file = $pdf->output(); file_put_contents($file_name, $file); require 'class/class.phpmailer.php'; $mail = new PHPMailer; $mail->IsSMTP(); //Sets Mailer to send message using SMTP $mail->Host = 'smtpout.secureserver.net'; //Sets the SMTP hosts of your Email hosting, this for Godaddy $mail->Port = '80'; //Sets the default SMTP server port $mail->SMTPAuth = true; //Sets SMTP authentication. Utilizes the Username and Password variables $mail->Username = 'xxxxxxxxxx'; //Sets SMTP username $mail->Password = 'xxxxxxxxxx'; //Sets SMTP password $mail->SMTPSecure = ''; //Sets connection prefix. Options are "", "ssl" or "tls" $mail->From = 'info@webslesson.info'; //Sets the From email address for the message $mail->FromName = 'Webslesson.info'; //Sets the From name of the message $mail->AddAddress('web-tutorial@programmer.net', 'Name'); //Adds a "To" address $mail->WordWrap = 50; //Sets word wrapping on the body of the message to a given number of characters $mail->IsHTML(true); //Sets message type to HTML $mail->AddAttachment($file_name); //Adds an attachment from a path on the filesystem $mail->Subject = 'Customer Details'; //Sets the Subject of the message $mail->Body = 'Please Find Customer details in attach PDF File.'; //An HTML or plain text message body if($mail->Send()) //Send an Email. Return true on success or false on error < $message = ' '; > unlink($file_name); > ?>

Create Dynamic PDF Send As Attachment with Email in PHP





Источник

Оцените статью