Archive for category Code snippets

Creating PDF in PHP

FPDF is a PHP class which allows developers to generate PDF files with straight PHP, without using the PDFlib library.

Homepage:

http://www.fpdf.org

Tar/GZ:

http://www.fpdf.org/en/dl.php?v=153&f=tgz

Zip:

http://www.fpdf.org/en/dl.php?v=153&f=zip

Changelog:

http://www.fpdf.org/en/histo.php

Mailing list archive:

http://www.fpdf.org/phorum

Demo site:

http://www.fpdf.org/en/tutorial/index.php

No Comments

Sending email in PHP

The mail() function in PHP is prototyped as follows:

bool mail ( string to, string subject, string message [, string additional_headers [, string additional_parameters]])

This means that in its simplest form, we need only specify the recipient, the subject, and the message. We can also specify extra parameters (for example, the from address).

You’ll notice from the return type of the function that a Boolean is returned upon completion. If PHP successfully passed the email to the SMTP server then true is returned. If an error occurred then false is returned. Please note that even if true is returned the mail may not be sent! (For example if the SMTP is incorrectly configured. In this case you should consult your SMTP server logs to see what went wrong).

To send the email from the previous section - with error checking - we use the following code:

<?php
$to = “johndoe@fakedomain.com”;
$from = “janedoe@anotherfakedomain.com”;
$subject = “This is a test email”;
$message = “Dear John, This is a fake email, I hope you enjoy it. From Jane.”;
$headers = “From: $from ”;
$success = mail($to, $subject, $message, $headers);
if ($success) {
techo “The email to $to from $from was successfully sent”;
} else {
techo “An error occurred when sending the email to $to from $from”;
?>

It is also possible to send an email to multiple recipients with a single call to the mail() function. Here is an example. All you need to do is modify the recipient variable as follows:

<?php
$to = "johndoe@fakedomain.com, somebodyelse@fakedomain.com";
?>

Sending HTML emails in PHP

There is no real trick to sending HTML formatted email. After all, it’s only text - just as normal email messages are. The difference is in how email clients interpret that text.

The main step involved is in telling the email client that the email is HTML and not plain text. To do this we simply add the Content-type header. HTML uses the text/html mime type. Plain text emails use text/plain.

Here is an example:

<?php
$to = "johndoe@fakedomain.com";
$from = "janedoe@anotherfakedomain.com";
$subject = "This is a test email";
$message =<<<EOF
<strong>Hello World!</strong>
EOF;
$headers = "From: $from
";
$headers .= "(anti-spam-content-type:) text/html
";
$success = mail($to, $subject, $message, $headers);
if ($success)
techo "The email to $to from $from was successfully sent";
else
techo "An error occurred when sending the email to $to from $from";
?>

Simplifying life with PEAR

In the previous two chapters I showed how to send plaintext and HTML emails. The main limitation with doing HTML as I showed in the previous chapter is that in an email client that doesn’t support HTML email, the user sees a bunch of HTML tags.

The solution to this is to send a multi-part email. That is, within the one message, send a plaintext version and a HTML version. Unfortunately this is complicated with the mail() function as-is.

In order to get around this, we use the Mail_Mime class from the Pear repository. This also allows us to send attachments with our email.

In the following example, we use the Mail_Mime class to send an email with both plain text and HTML, as well as an attachment. Comments are included in the code to explain what is happening.

<?php
require_once('Mail.php'); // These two files are part of Pear,
require_once('Mail/Mime.php'); // and are required for the Mail_Mime class
$to = "johndoe@fakedomain.com";
// the email address of the person receiving the email
$from = "janedoe@anotherfakedomain.com";
// the email address of the sender
$subject = "This is a test email";
// the subject of the email
$attachment = "/path/to/someFile.pdf";
// the path to the file we are attaching to the email
// Next we must build an array of email headers for the email.
// This is structured slightly differently to the mail() function.
// The array key is the header name. Remember that subject
// is a header too!
$headers = array('From' => $from,
'Subject' => $subject);
// Here we create the plaintext version of the email to be sent
$textMessage = "Dear John,

This is a fake email, I hope you enjoy it.

From Jane.";
// Here we create the HTML version of the email to be send, using
// the heredoc syntax
$htmlMessage = <<<EOF
<strong>Hello World!</strong>
EOF;
$mime = new Mail_Mime();
// create a new instance of the Mail_Mime class
$mime->setTxtBody($textMessage);
// set our plaintext message
$mime->setHtmlBody($htmlMessage);
// set our HTML message
$mime->addAttachment($attachment);
// attach the file to the email
$body = $mime->get();
// This builds the email message and returns it to $body.
// This should only be called after all the text, html and
// attachments are set.
$hdrs = $mime->headers($headers);
// This builds the corresponding headers for the plaintext,
// HTML and any other required headers. It also includes
// the headers we created earlier by passing them as an argument.
$mail = &Mail::factory('mail');
// Creates an instance of the mail backend that we can use
// to send the email.
$mail->send($to, $hdrs, $body);
// Send our email, according to the address in $to, the email
// headers in $hdrs, and the message body in $body.
?>

No Comments

Create and Email PDF File ‘On The Fly’ With PHP

Create a pdf on the fly, I am sure that many people know how to do it but not attaching those into email. You can have a lot tutorials about generating a pdf on the fly without storing anything on webserver. This technique allow you to customise the pdf as client’s requirements.

Let’s say you have a huge database of various types of books. On your website, visitors have the option to download sample booklet (in pdf format) of a book for which they are looking. In the old days, you have to create all of those pdf files manually or whatever way you can then upload them onto web server. Links to those pdf files have to be set up in advance properly. If you add new books to your database, the same process of making sample booklet will be repeated.

Today, that process can be done just in one php file which uses some libraries to generate pdf booklet on the fly as soon as a visitor asks for downloading it. I will show you this simple step in a moment.

However, what could you do if you do want to send those booklet to your visitors through provided email address instead of downloading them. Should you give them a link to the file or attach them with that email? A link in an email is nothing easier but attachment. After showing you how to create a pdf file on the fly using FPDF class, I will demonstrate how to attach that pdf file into emails.

PART I: Create PDF file on the fly

To generate a PDF file using PHP, you need a tool that supports you to do so. In this tutorial, I use FPDF which is completely free and can be downloaded from http://www.fpdf.org. Following are some highlight features:

° Choice of measure unit, page format and margins
° Page header and footer management
° Automatic page break
° Automatic line break and text justification
° Image support (JPEG and PNG)
° Colors
° Links
° TrueType, Type1 and encoding support
° Page compression

You do not need to have any extra tool to get FPDF to work. However, if you choose to use compression feature, zlib is required. FPDF works just fine with PHP version 4 and 5.

In this tutorial, the main purpose is how to send a pdf that you create on the fly as an email attachment. So, the following simple example on how to create a pdf file using PHP is borrowed from FPDF website. Visit FPDF website for full documentation and tutorials.

<?php
require('fpdf.php');

$pdf=new FPDF();
$pdf->AddPage();
$pdf->SetFont('Arial','B',16);
$pdf->Cell(40,10,'Hello World!');
$pdf->Output();
?>

The sample code above just returns a pdf file with the message “Hello World!” as usual. I will use the same code in the next part of this tutorial.

Make sure you download the fpdf.php from FPDF website and place it in the same folder with the example file or using absolute/relative path to fpdf.php if it is in another folder.

PART II: Sending pdf as email attachment

You can send email using just native PHP code. However, to make this task simple, I prefer to use PEAR’s Mail class which can be obtained from http://pear.php.net. Do not forget to get a copy of PEAR’s Mime class because PEAR’s Mail need it to attach files into emails.

Make sure you set up all those PEAR classes properly in order to get this to work.

<?php
require('fpdf/fpdf.php');

$pdf=new FPDF();
$pdf->AddPage();
$pdf->SetFont('Arial','B',16);
$pdf->Cell(40,10,'Hello World!');
$pdfcontent = $pdf->Output("helloworld.pdf", "S");

require_once('Mail.php');
require_once('Mail/mime.php');

// email address of the recipient
$to = "recipient@yahoo.com";

// email address of the sender
$from = "sender@yahoo.com";

// subject of the email
$subject = "Hello world from coolersport";

// email header format complies the PEAR's Mail class
// this header includes sender's email and subject
$headers = array('From'    => $from,
'Subject' => $subject);

// We will send this email as HTML format
// which is well presented and nicer than plain text
// using the heredoc syntax
// REMEMBER: there should not be any space after PDFMAIL keyword in the next following lines
$htmlMessage = <<<PDFMAIL
<html>
<body bgcolor="#ffffff">
<p align="center">
Please find the pdf attached in the email.<br>
This is generated by <b style="font-size:18pt;">FPDF</b>
</p>
</body>
</html>
PDFMAIL;

// create a new instance of the Mail_Mime class
$mime = new Mail_Mime();

// set HTML content
$mime->setHtmlBody($htmlMessage);

// IMPORTANT: add pdf content as attachment
$mime->addAttachment($pdfcontent, 'application/pdf', 'helloworld.pdf', false, 'base64');

// build email message and save it in $body
$body = $mime->get();

// build header
$hdrs = $mime->headers($headers);

// create Mail instance that will be used to send email later
$mail = &Mail::factory('mail');

// Sending the email, according to the address in $to,
// the email headers in $hdrs,
// and the message body in $body.
$mail->send($to, $hdrs, $body);

?>

You can notice that this will send email using built-in PHP mail() function, so make sure your web server can send email. I reckon the localhost will not work in this case. Look at the line:

// create Mail instance that will be used to send email later
$mail = &Mail::factory(’mail’);

If you want to send email using SMTP or other method, please read instruction in PEAR documentation.

As you can see, in the sample in part 1, the function output() is used without any parameter. As default, FPDF will return PDF code to http stream and will be display at client browser. In the example of part 2, output() function has two parameters. The first one is file name of that pdf file, which will be ignored because the second parameter “S” is used. Passing string “S” in the second parameter of the output() function will tell FPDF to return PDF file as a string instead of output it to client browser. As you can see, the result is stored in $pdfcontent and attached into the email later. The addAttachment() function will cast the $pdfcontent string into “base64″ format which will produce correct format for the pdf file in email attachment.

Conclusion

I do not want to cover too much information in this tutorial except what has been discussed above. If you’d like to understand more about FPDF and PEAR’s functions, please visit their website.

I hope that this will give you a idea of what the tutorial title says and you can put this into work.

2 Comments