13.09.2016 Views

PHP and MySQL Web Development 4th Ed-tqw-_darksiderg

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Solution Overview<br />

787<br />

Listing 32.3<br />

Continued<br />

$output = str_replace('', $date, $output);<br />

// send the generated document to the browser<br />

echo $output;<br />

}<br />

?><br />

This script performs some basic error checking to make sure that all the user details have<br />

been passed in <strong>and</strong> then moves to the business of creating the certificate.<br />

The output of this script will be an RTF file rather than an HTML file, so you need<br />

to alert the user’s browser to this fact.This is important so that the browser can attempt<br />

to open the file with the correct application or give a Save As… type dialog box if it<br />

doesn’t recognize the .rtf extension.<br />

You specify the MIME type of the file you are outputting by using <strong>PHP</strong>’s header()<br />

function to send the appropriate HTTP header as follows:<br />

header('Content-type: application/msword');<br />

header('Content-Disposition: inline, filename=cert.rtf');<br />

The first header tells the browser that you are sending a Microsoft Word file (not strictly<br />

true, but the most likely helper application for opening the RTF file).<br />

The second header tells the browser to automatically display the contents of the file<br />

<strong>and</strong> that its suggested filename is cert.rtf.This is the default filename the user will see<br />

if he tries to save the file from within his browser.<br />

After the headers are sent, you open <strong>and</strong> read the template RTF file into the $output<br />

variable <strong>and</strong> use the str_replace() function to replace the placeholders with the actual<br />

data that you want to appear in the file. For instance, the line<br />

$output = str_replace('', $name, $output);<br />

replaces any occurrences of the placeholder with the contents of the variable<br />

$name.<br />

Having made your substitutions, it’s just a matter of echoing the output to the browser.<br />

A sample result from the rtf.php script is shown in Figure 32.5.<br />

This approach works very well. The calls to str_replace() run very quickly, even<br />

though the template <strong>and</strong> therefore the contents of $output are fairly long.The main<br />

problem from the point of view of this application is that the user will load the certificate<br />

in his word processor to print it.This is probably an invitation for people to modify<br />

the output. RTF does not allow you to make a read-only document.

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!