6.11. Generating Downloadable Files Dynamically

Problem

You want to offer a frequently updated or customized document, such as a coupon or application, that visitors to your site can download and print out.

Solution

Set up a PHP script that dynamically generates a file using code libraries that allow you to build and output custom PDFs, PNGs, JPEGs, and other types of files using built-in functions.

The functions associated with PDFlib library, created by Thomas Merz, have been available to PHP since Version 3. Image-generating functions that are part of Thomas Boutell's GD Graphics Library have been a common PHP installation option since Version 4.3.

Tip

The PDFlib and GD functions must be enabled with PHP when it is installed on your web server. If you're unsure about the availability of either function library, check with your system administrator or web hosting provider.

If you want to create PDFs on the fly, but don't have access to PDFlib, you can use a third-party PHP class that replicates most of the functionality of PDFlib; refer to the "See Also" section in this Recipe for more information.

Discussion

For this Recipe, I'll use the example of creating a coupon (see Figure 6-9) with an expiration date one week from the date the visitor downloads it. Coupons are a great way for a brick and mortar establishment to get regular visitors to its web site. Setting up a script that keeps the coupon up to date, and offers some flexibility about the terms of the offer, will relieve you or ...

Get Web Site Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.