Page 543 - Beginning PHP 5.3
P. 543
Chapter 16: PHP and the Outside World
echo “<p>Please fill in all the fields below, then click Send Message to
send us an email.</p>”;
$renderer = new HTML_QuickForm_Renderer_Tableless();
$form->accept( $renderer );
echo $renderer->toHtml();
}
Lastly, the sendMessage() function deals with the actual email sending. First it constructs the
recipient string from the owner’s first name, last name, and email address, and sets the From: address
details to those supplied by the visitor in the form:
$recipient = OWNER_FIRST_NAME . “ “ . OWNER_LAST_NAME . “ <” . OWNER_EMAIL_
ADDRESS . “>”;
$headers = “From: “ . $values[“firstName”] . “ “ . $values[“lastName”] . “
<” . $values[“emailAddress”] . “>”;
Then the function calls the built-in mail() function, passing in the recipient string, the supplied
message subject and body, and the additional mail headers (that is, the From: address):
if ( mail( $recipient, $values[“subject”], $values[“message”], $headers ) ) {
If the message was sent successfully, an acknowledgment is displayed; otherwise an error message is
shown and the visitor is invited to try again.
This example shows how easy it is to construct form-to-email scripts in PHP, thanks to PHP’s mail()
function. You can use the same techniques for creating other email functions, such as “tell a friend”
scripts and password reminder functions.
Summary
In this chapter you explored various concepts and PHP features that you can use to write applications
that interact with the outside world:
❑ Date and time functions and classes: You explored the concepts of timestamps and UTC, and
learned how to use time() to retrieve the current timestamp. You also saw how to create your
own timestamps with the mktime() , gmmktime() , and strtotime() functions, as well as how
to use getdate() to extract information from a timestamp. You learned how to format dates
using idate() and date() , how to check that dates are well - formed using checkdate() , and
how to work more precisely with timestamps by using microtime() . Finally, you put theory
into practice with a script to calculate your age in days, and took a brief look at PHP ’ s relatively
new DateTime and DateTimeZone classes for handling dates and times
❑ HTTP requests and responses: You learned how Web browsers and servers communicate using
HTTP. You studied the anatomy of an HTTP request and response, and looked at some common
headers that are sent between browser and server. Finally, you looked at how to modify HTTP
responses within PHP scripts, and how you can use this ability to redirect the browser, return
specific status codes, and send non - HTML content back to the browser
505
9/21/09 9:15:42 AM
c16.indd 505 9/21/09 9:15:42 AM
c16.indd 505

