Tải bản đầy đủ (.pdf) (30 trang)

Beginning PHP6, Apache, MySQL Web Development- P12 ppt

Bạn đang xem bản rút gọn của tài liệu. Xem và tải ngay bản đầy đủ của tài liệu tại đây (676.32 KB, 30 trang )

Chapter 10: Building Databases
301
< input type=”radio” name=”alignment” value=”evil”
< ?php echo ($character[‘alignment’]==’evil’) ? ‘checked=”checked”’ : ‘’;
? < / > Evil
< /td >
< /tr > < tr >
< /tr > < tr >
< td > Rivalries: < br/ > < small > < em > CTRL-click to select multiple enemies < /em >
< /small >
< /td >
< td >
< ?php
// retrieve and present the list of existing characters (excluding the
character
// being edited)
$query = ‘SELECT
character_id, alias
FROM
comic_character
WHERE
character_id != ‘ . $character_id . ‘
ORDER BY
alias ASC’;
$result = mysql_query($query, $db) or die (mysql_error($db));

if (mysql_num_rows($result) > 0) {
echo ‘ < select multiple name=”rivalries[]” > ’;
while ($row = mysql_fetch_array($result)) {
if (isset($rivalries[$row[‘character_id’]])) {
echo ‘ < option value=”’ . $row[‘character_id’] .


‘” selected=”selected” > ’;
} else {
echo ‘ < option value=”’ . $row[‘character_id’] . ‘” > ’;
}
echo $row[‘alias’] . ‘ < /option > ’;
}
echo ‘ < /select > ’;
} else {
echo ‘ < p > < strong > No Characters entered
< /strong > < /p > ’;
}
mysql_free_result($result);
? >
< /td >
< /tr > < tr >
< td colspan=”2” >
< input type=”submit” name=”action”
value=” < ?php echo $action; ? > Character” / >
< input type=”reset” value=”Reset” >
< ?php
c10.indd 301c10.indd 301 12/10/08 6:00:03 PM12/10/08 6:00:03 PM
Part II: Comic Book Fan Site
302
if ($action == “Edit”) {
echo ‘ < input type=”submit” name=”action” value=”Delete Character” / > ’;
echo ‘ < input type=”hidden” name=”character_id” value=”’ .
$character_id . ‘” / > ’;
}
? >
< /td >

< /tr >
< /table >
< /form >
< p > < a href=”list_characters.php” > Return to Home Page < /a > < /p >
< /body >
< /html >

3. Open your browser and point it to the location of list_characters.php . This is your
Character Database home page. It should look something like Figure 10 - 3 . But because you
don ’ t currently have any characters to look at, let ’ s move on.
Figure 10-3
c10.indd 302c10.indd 302 12/10/08 6:00:04 PM12/10/08 6:00:04 PM
Chapter 10: Building Databases
303
4. Click the Add New Character link. A new page appears, ready for your data input, which
should look like that in Figure 10 - 4 . You will notice that the powers you entered are choices in
the Powers field.
Figure 10-4
5. Enter the appropriate data for your character, and click Add Character. You should be taken
back to the Character Database page, where you ’ ll see the new character listed, as shown in
Figure 10 - 5 .
c10.indd 303c10.indd 303 12/10/08 6:00:04 PM12/10/08 6:00:04 PM
Part II: Comic Book Fan Site
304
6. If you click New Character again, you now see an extra field for rivalries. You can select any
previously created characters in the database as the current character ’ s enemies.
7. From the home page, click one of your characters ’ names. The Edit Character page loads
again, and the character ’ s data will be automatically entered into the fields (see Figure 10 - 6 ). If
you look at the URL for this page, you see
?id=# at the end, where # is the character ’ s

number.
Figure 10-5
c10.indd 304c10.indd 304 12/10/08 6:00:04 PM12/10/08 6:00:04 PM
Chapter 10: Building Databases
305
8. Change some of the data, and click Edit Character. You are taken back to the Character Database
page, where you should immediately see the results of your changes. In fact, if you selected an
enemy for this character, you should see the results change in the enemy ’ s row as well.
How It Works
You created two different files in this exercise, so we ’ re going to take them apart and look at them each
individually here.
list_characters.php
The list_characters.php page has an optional parameter that can be passed: ?o=# , where # is 1, 2,
or 3. This code retrieves that variable if it exists and converts it to the appropriate value if necessary to
determine on which column the display should be sorted. If some smart - aleck types in an invalid value,
or if no value is passed at all, then the script will default its value to 1.

Figure 10-6
c10.indd 305c10.indd 305 12/10/08 6:00:05 PM12/10/08 6:00:05 PM
Part II: Comic Book Fan Site
306
$order = array(1 = > ‘alias ASC’,
2 = > ‘real_name ASC’,
3 = > ‘alignment ASC, alias ASC’);

$o = (isset($_GET[‘o’]) & & ctype_digit($_GET[‘o’])) ? $_GET[‘o’] : 1;
if (!in_array($o, array_keys($order))) {
$o = 1;
}


This value determines which column the character display will be sorted on: 1 is by alias, 2 is by real
name, and 3 is first by alignment and then by alias. You will use the value
$o as the key to your order
array which will be appended to the appropriate SQL statement later.
You are going to build a table of characters in a moment. A SELECT query retrieves the list of characters
sorted appropriately, and then the number of records is checked. If there are character records returned,
then the table is constructed, but otherwise you want to display a “ No Characters ” message.

$query = ‘SELECT
character_id, alias, real_name, alignment
FROM
comic_character
ORDER BY ‘ . $order[$o];
$result = mysql_query($query, $db) or die (mysql_error($db));

if (mysql_num_rows($result) > 0) {
//
} else {
echo ‘ < p > < strong > No Characters entered < /strong > < /p > ’;
}

The column headers for the Alias, Real Name, and Alignment columns are actually links back to the
same page, but with different sort parameters appended to the address, so the viewer can sort the table
to his or her heart ’ s content by clicking on them.

echo ‘ < tr > < th > < a href=”’ . $_SERVER[‘PHP_SELF’] . ‘?o=1” > Alias < /a > < /th > ’;
echo ‘ < th > < a href=”’ . $_SERVER[‘PHP_SELF’] . ‘?o=2” > Real Name < /a > < /th > ’;
echo ‘ < th > < a href=”’ . $_SERVER[‘PHP_SELF’] . ‘?o=3” > Alignment < /a > < /th > ’;
echo ‘ < th > Powers < /th > ’;
echo ‘ < th > Enemies < /th > < /tr > ’;


Each row is provided with an alternating odd/even class attribute, as you have done in several earlier
chapters, so they can be colorized. Alternating the background color of the rows makes it easier for your
users to read them. You also make the character ’ s name a link to the
edit_character.php page so that
by clicking on it the user can edit the character ’ s details.

$odd = true;
while ($row = mysql_fetch_array($result)) {
echo ($odd == true) ? ‘ < tr class=”odd_row” > ’ : ‘ < tr class=”even_row” > ’;
$odd = !$odd;
echo ‘ < td > < a href=”edit_character.php?id=’ . $row[‘character_id’] .
‘” > ’ . $row[‘alias’] . ‘ < /a > < /td > ’;
echo ‘ < td > ’ . $row[‘real_name’] . ‘ < /td > ’;
echo ‘ < td > ’ . $row[‘alignment’] . ‘ < /td > ’;

c10.indd 306c10.indd 306 12/10/08 6:00:05 PM12/10/08 6:00:05 PM
Chapter 10: Building Databases
307
Next are two other SELECT statements to retrieve the appropriate data for the remaining columns:
powers and rivalries. Because they are executed within a loop that is processing your first query ’ s
results,
$query2 , $result2 and $row2 variables are used, so you don ’ t overwrite the first
query ’ s results that are still needed.
The first
SELECT statement fetches the character ’ s powers by JOIN ing the comic_power and comic_
character_power
tables. If powers are returned, then they are listed in the table, but if no powers have
been assigned to the character, then “ none ” is displayed.


$query2 = ‘SELECT
power
FROM
comic_power p
JOIN comic_character_power cp
ON p.power_id = cp.power_id
WHERE
cp.character_id = ‘ . $row[‘character_id’] . ‘
ORDER BY
power ASC’;
$result2 = mysql_query($query2, $db) or die (mysql_error($db));

if (mysql_num_rows($result2) > 0) {
$powers = array();
while ($row2 = mysql_fetch_assoc($result2)) {
$powers[] = $row2[‘power’];
}
echo ‘ < td > ’ . implode(‘, ‘, $powers) . ‘ < /td > ’;
} else {
echo ‘ < td > none < /td > ’;
}
mysql_free_result($result2);

The second SELECT statement fetches the character ’ s rivals. This one is similar to the previous M:N
query, with a couple of exceptions. First of all, you are linking the character table twice. You can see that
you are creating two instances of that table, one for the hero character and one for the villain character.
This distinction is very important.
The other exception is the
ON statement. You have characters that you are attempting to link to other
characters and enemies. Call them opponents, nemeses, or whatever. Typically, you expect good versus

evil, and vice versa. However, you are allowing any character to be the enemy of any other character. That
makes linking more interesting, because you are using a table a with a
hero_id and villain_id . If you
have two evil characters who are enemies to each other, which one gets stored in
hero_id ?
The answer is that it doesn ’ t matter. What you want to do is to make sure that you not only don ’ t have
any duplicates in the
comic_rivalry table, but also that you don ’ t have what we call reverse duplication.
In other words, if you have a row with
hero_id=3 and villain_id=7 , then hero_id=7 and villain_
id=3
must be considered a duplicate. There is no way to prevent that in MySQL using primary keys, so
you must take care of that contingency in your code. You do that in a couple of places.
In this instance, you are combining two queries into one. The first one grabs all instances of each
character where there character ’ s ID is in the
hero_id field, and his enemies ’ IDs are in the villain_id
field. The second part of the
ON statement reverses that and pulls all instances of each character where
c10.indd 307c10.indd 307 12/10/08 6:00:05 PM12/10/08 6:00:05 PM
Part II: Comic Book Fan Site
308
the character ’ s ID is in the villain field, and his enemies ’ IDs are in the hero_id field. This does not
prevent reverse duplication (that is handled elsewhere), but it does make sure you have grabbed every
possible link to a character ’ s enemy.
Again, if enemies are returned, then they are listed in the table. Otherwise, “ none ” is displayed.

$query2 = ‘SELECT
c2.alias
FROM
comic_character c1

JOIN comic_character c2
JOIN comic_rivalry r
ON (c1.character_id = r.hero_id AND
c2.character_id = r.villain_id) OR
(c2.character_id = r.hero_id AND
c1.character_id = r.villain_id)
WHERE
c1.character_id = ‘ . $row[‘character_id’] . ‘
ORDER BY
c2.alias ASC’;
$result2 = mysql_query($query2, $db) or die (mysql_error($db));

if (mysql_num_rows($result2) > 0) {
$aliases = array();
while ($row2 = mysql_fetch_assoc($result2)) {
$aliases[] = $row2[‘alias’];
}
echo ‘ < td > ’ . implode(‘, ‘, $aliases) . ‘ < /td > ’;
} else {
echo ‘ < td > none < /td > ’;
}
mysql_free_result($result2);

edit_character.php
This file does double duty so it ’ s a little longer. But a lot of it is HTML, and much of what it does you
have already done before, so this shouldn ’ t be too difficult.
The default functionality of this page is Add Character mode. If there is a value in
$_GET[‘id’] other
than 0, the script will pull the data and change the default values.


$action = ‘Add’;

$character = array(‘alias’ = > ‘’,
‘real_name’ = > ‘’,
‘alignment’ = > ‘good’,
‘address’ = > ‘’,
‘city’ = > ‘’,
‘state’ = > ‘’,
‘zipcode_id’ = > ‘’);
$character_powers = array();
$rivalries = array();

$character_id = (isset($_GET[‘id’]) & & ctype_digit($_GET[‘id’])) ?
c10.indd 308c10.indd 308 12/10/08 6:00:06 PM12/10/08 6:00:06 PM
Chapter 10: Building Databases
309
$_GET[‘id’] : 0;

if ($character_id != 0) {
//
}

Next, the script gets the basic information about the character from the comic_character , comic_lair ,
and
comic_zipcode tables.
$query = ‘SELECT
c.alias, c.real_name, c.alignment,
l.address, z.city, z.state, z.zipcode_id
FROM
comic_character c, comic_lair l, comic_zipcode z

WHERE
z.zipcode_id = l.zipcode_id AND
c.lair_id = l.lair_id AND
c.character_id = ‘ . $character_id;
$result = mysql_query($query, $db) or die (mysql_error($db));

if (mysql_num_rows($result) > 0) {
$action = ‘Edit’;
$character = mysql_fetch_assoc($result);
}
mysql_free_result($result);

You may realize that the query is also a JOIN if you are an astute reader, although the JOIN keyword is
not used. You can identify such a
JOIN because there are two or more tables, and the WHERE clause
matches columns from each of the tables. The
JOIN in this case is implied, and ON has integrated into the

WHERE clause.
It isn ’ t until we are sure that a character with the provided ID really exists in the database that we switch
the page ’ s action to Edit mode, which acts as a failsafe if someone were to supply an invalid character
ID. If the value of
$action has been changed, then the script will continue retrieving the list of
superpowers and rivals for the character.

if ($action == ‘Edit’) {
$query = ‘SELECT
power_id
FROM
comic_character_power

WHERE character_id = ‘ . $character_id;
$result = mysql_query($query, $db) or die (mysql_error($db));

if (mysql_num_rows($result) > 0) {
while ($row = mysql_fetch_array($result)) {
$character_powers[$row[‘power_id’]] = true;
}
}
mysql_free_result($result);

$query = ‘SELECT
c2.character_id
c10.indd 309c10.indd 309 12/10/08 6:00:06 PM12/10/08 6:00:06 PM
Part II: Comic Book Fan Site
310
FROM
comic_character c1
JOIN comic_character c2
JOIN comic_rivalry r
ON (c1.character_id = r.hero_id AND
c2.character_id = r.villain_id) OR
(c2.character_id = r.hero_id AND
c1.character_id = r.villain_id)
WHERE
c1.character_id = ‘ . $character_id . ‘
ORDER BY
c2.alias ASC’;
$result = mysql_query($query, $db) or die (mysql_error($db));

$rivalries = array();

if (mysql_num_rows($result) > 0) {
while ($row = mysql_fetch_array($result)) {
$rivalries[$row[‘character_id’]] = true;
}
}
}

The queries only retrieve the power IDs and rival IDs and store them in the appropriate array for later
use. They will be used in the form ’ s Powers and Rivalries fields so each assigned to the character will be
automatically selected.
Note the similarity of the SQL statement that retrieves the list of rivalries to the one earlier in
list_
characters.php
.
You next build the HTML form and insert the values into the appropriate places as defaults. This is how
you fill in the fields with character data.

< td > Character Name: < /td >
< td > < input type=”text” name=”alias” size=”40” maxlength=”40”
value=” < ?php echo $character[‘alias’];? > ” > < /td >

When you build the Powers select field, the script loops through each power in the database and checks
its ID against the list gathered earlier and stored in the
$powers array. If that power ’ s key exists in the

$powers array, then the script sets the option element ’ s selected attribute so that it will appear
preselected in the form. In this way, the script builds a field of all powers where the character ’ s chosen
powers are selected in the list. Neat, huh?

< td > Powers: < br/ > < small > < em > CTRL-click to select multiple powers < /em > < /

small >
< /td >
< td >
< ?php
$query = ‘SELECT
power_id, power
FROM
comic_power
ORDER BY
c10.indd 310c10.indd 310 12/10/08 6:00:06 PM12/10/08 6:00:06 PM
Chapter 10: Building Databases
311
power ASC’;
$result = mysql_query($query, $db) or die (mysql_error($db));

if (mysql_num_rows($result) > 0) {
echo ‘ < select multiple name=”powers[]” > ’;
while ($row = mysql_fetch_array($result)) {
if (isset($character_powers[$row[‘power_id’]])) {
echo ‘ < option value=”’ . $row[‘power_id’] . ‘”
selected=”selected” > ’;
} else {
echo ‘ < option value=”’ . $row[‘power_id’] . ‘” > ’;
}
echo $row[‘power’] . ‘ < /option > ’;
}
echo ‘ < /select > ’;
} else {
echo ‘ < p > < strong > No Powers entered < /strong > < /p > ’;
}

mysql_free_result($result);
? >
< /td >


Note the [] in the select ’ s name attribute. That is necessary for PHP to recognize the variable as an
array when it gets posted to the
char_transaction.php page. This is a requirement for any field that
might post with multiple values.
Then the following code creates a set of radio buttons for “ good ” and “ evil ” Alignment. The character ’ s
alignment is preselected with the
checked attribute.
< td > Alignment: < /td >
< td > < input type=”radio” name=”alignment” value=”good”
< ?php echo ($character[‘alignment’]==’good’) ? ‘checked=”checked”’ : ‘’;
? < / > Good < br/ >
< input type=”radio” name=”alignment” value=”evil”
< ?php echo ($character[‘alignment’]==’evil’) ? ‘checked=”checked”’ : ‘’;
? < / > Evil
< /td >

Remember what you did with the Powers field? Ditto all of that for the Enemies field.
< td > Rivalries: < br/ > < small > < em > CTRL-click to select multiple enemies < /em >
< /small >
< /td >
< td >
< ?php
$query = ‘SELECT
character_id, alias
FROM

comic_character
WHERE
character_id != ‘ . $character_id . ‘
ORDER BY
c10.indd 311c10.indd 311 12/10/08 6:00:06 PM12/10/08 6:00:06 PM
Part II: Comic Book Fan Site
312
alias ASC’;
$result = mysql_query($query, $db) or die (mysql_error($db));

if (mysql_num_rows($result) > 0) {
echo ‘ < select multiple name=”rivalries[]” > ’;
while ($row = mysql_fetch_array($result)) {
if (isset($rivalries[$row[‘character_id’]])) {
echo ‘ < option value=”’ . $row[‘character_id’] .
‘” selected=”selected” > ’;
} else {
echo ‘ < option value=”’ . $row[‘character_id’] . ‘” > ’;
}
echo $row[‘alias’] . ‘ < /option > ’;
}
echo ‘ < /select > ’;
} else {
echo ‘ < p > < strong > No Characters entered < /strong > < /p > ’;
}
mysql_free_result($result);
? >
< /td >

If the character entry form is in Edit mode, then the script will include a Delete Character button. The

button won ’ t appear in Add mode, since you can ’ t delete a character you haven ’ t created yet. Also,
the character ID is not passed through any other form fields, so you create a hidden field to hold that
information. You need that ID if you are going to update an existing character, right? Of course, if you
are creating a new character, then the ID will be created for you when you insert all the appropriate data.

if ($action == “Edit”) {
echo ‘ < input type=”submit” name=”action” value=”Delete Character” / > ’;
echo ‘ < input type=”hidden” name=”character_id” value=”’ .
$character_id . ‘” / > ’;
}

Summary
Whew! This chapter covered a lot of ground. You learned about how to plan the design of your
application, including database design. You learned how to normalize your data so that it can easily be
linked and manipulated without having redundant duplication. You created a brand - new database for
your web site and started building your site by creating tables the application needed to access and
update.
Congratulations! You ’ ve just created your first fully functioning web application with a relational
database back end. (That ’ s going to look so good on your resume.)
This chapter is only the beginning, however. With the knowledge you gained here, you can create almost
any application you desire. Here are some examples of what you could do:
Content Management System (CMS): Create a data entry system that will allow users and
administrators to alter the content of the web site and your database without knowing any
HTML.

c10.indd 312c10.indd 312 12/10/08 6:00:07 PM12/10/08 6:00:07 PM
Chapter 10: Building Databases
313
Maintain a database of users visiting your site: You can enable user authentication, e - mail your
users to give them exciting news, sign them up for newsletters, and so on.

Create an online e - commerce site: Create shopping carts where users can store the merchandise
they will purchase. (This can be daunting — many choose to use a third - party shopping - cart
application.)
Create an online discussion forum where your users can go to discuss how wonderful your
site looks!
These are just a few ideas. In fact, you are going to see how to do each of these things over the course of
upcoming chapters. With a little imagination, you can come up with solutions to almost any problem
you might face in building your site.
If any of the ideas presented in this chapter are difficult for you to grasp, that ’ s okay — it is a large
amount of new material crammed into only a few pages. We expected you to learn a lot, especially if you
are a beginning programmer. The great thing about a book is that you can keep coming back! You will
also be revisiting many of these concepts in later chapters. For example, in Chapter 16, where you learn
to build your own forum, you will go through database normalization again, on a new set of databases.
You will also have many more opportunities to create SQL queries, some familiar and some new.
For now, you have the basic knowledge for creating even the most complex sites. You have the first
incarnation installed on your server. Take some time to play with your new toy.
Now all you need to do is let all of your friends and family know about your cool new site. If only you
knew how to send e - mails using PHP. Well, we ’ ll handle that in Chapter 11.
Exercises
See how you might accomplish the following tasks:
1. Add a “ costume description ” field to the character record, and provide a way to modify the cos-
tume description.
2. Modify the character listing to display the characters ’ locations alongside their powers.



c10.indd 313c10.indd 313 12/10/08 6:00:07 PM12/10/08 6:00:07 PM
c10.indd 314c10.indd 314 12/10/08 6:00:07 PM12/10/08 6:00:07 PM
11
Sending E - mail

So far, the chapters in this book have walked you through the creation of a comprehensive web
site. You have designed your site so that users can add and modify data that is stored in databases.
You have built dynamic pages for your users, ensuring that they have a rich and unique
experience when they visit your web site. You are even displaying helpful error messages in case
something goes wrong. But now it ’ s time to get a little more interactive with your users, with
e - mail. We are not talking about standard e - mail — we ’ re talking about sending out e - mails
using PHP.
Why would you want a server - side scripting language to send out e - mails? Perhaps you want to
create a feedback form used for submitting information to an administrator ’ s e - mail address, as
introduced in Chapter 9 . Maybe you want certain errors to be automatically e - mailed to the
webmaster. Perhaps you would like to create an application that allows users to send their friends
and family electronic postcards. (Nod your head in vigorous agreement to the latter, here, because
that is exactly what you are going to do!)
Specifically, this chapter covers:
Sending a basic e - mail
Sending an HTML - formatted e - mail
Using multipart messages
Sending images
Receiving confirmation





c11.indd 315c11.indd 315 12/10/08 6:05:25 PM12/10/08 6:05:25 PM
316
Part II: Comic Book Fan Site
Setting Up PHP to Use E - mail
You need an e - mail server to be able to send e - mail with PHP. This chapter doesn ’ t delve too deeply into
the setup of an e - mail server for PHP, but here are the basics.

If you are working within a UNIX or Linux environment, then you will most likely have sendmail
installed on your server, or it can be installed within minutes. If you are using a shared hosting service,
then check with your provider to see if it uses sendmail or some equivalent.
If you are not using sendmail, or if you have Apache installed on a Windows server, then you have a
couple of choices. You can use your existing SMTP (Simple Mail Transfer Protocol) service, or you can
install an e - mail server such as Mailtraq on your computer. There are many online resources available to
help you, if you have questions about setting up or using an e - mail server.
Once you have your e - mail server up and running, there are a couple of parameters you ’ ll need to
modify in your
php.ini file. Of course, if you are using a hosting service, then your provider should
already have these parameters set up.

SMTP : Set this to the IP address or DNS name of your SMTP server. For example, if you have an
e - mail server installed on the same server as your PHP server, you should be able to set SMTP to

localhost .

smtp_port: Set this to the port PHP uses to connect to the SMTP server.

sendmail_from: The From address used by default by the PHP mail() command.

sendmail_path : The path to the sendmail program. For most servers, this is

usr/sbin/sendmail .

SMTP and smtp_port parameters apply to Windows only, while the sendmail_path parameter applies
to UNIX/Linux only.
That ’ s just about all there is to setting up PHP for e - mail. You will test to make sure it works correctly in
the next section, “ Sending an E - mail. ” You can find more information about setting up PHP for e - mail at
.

Sending an E - mail
The actual method of sending an e - mail is quite simple. Of course, it can be made much more complex
by sending HTML and images. However, you will start off with something simple.




c11.indd 316c11.indd 316 12/10/08 6:05:26 PM12/10/08 6:05:26 PM
Chapter 11: Sending E - mail
317


Try It Out Sending a Simple E - mail
This example is just about the simplest code you can write to send an e - mail. Of course, it ’ s not very
flexible, but it does demonstrate the
mail() function quite well.
1. Start your editor, and enter the following code (make sure you put your own e - mail address
in as the first parameter):
< ?php
mail(‘’, ‘Hello World’,
‘Hi, world. Prepare for our arrival. We are starving!’);
? >
2. Save the file as firstmail.php , and load it in your browser. You should see a blank page and
receive an e - mail shortly at the address entered as the first parameter to
mail() .
How It Works
Pretty cool, huh? That ’ s all there is to it! The mail() function automatically sends an e - mail, using the
following format:

mail(to_address, subject, message, headers, other_parameters)

If you want to send a message to multiple recipients, their addresses must be separated with a comma
in the
to parameter. For example:
mail(‘, ’, ‘Hi’, ‘Whazzup?’)
The parameters headers and other_parameters are optional. We will cover the headers parameter
soon. The
other_parameters are beyond the scope of this book, but if you want more information
about the
mail() function, point your browser to php.net/manual/en/function.mail.php .
You may have noticed when receiving this e - mail that there was no From address (or, maybe it was a
bogus address). Ours says “ www - data. ” In the next example, you ’ ll see how to add a From: address to
your e - mail, and you ’ ll also collect information from the user before sending the e - mail.

Try It Out Collecting Data and Sending an E - mail
In this exercise, you are going to create two web pages, postcard.php and sendmail.php . The file

postcard.php will collect the data you are going to send. The file sendmail.php will actually send
the message, using the data entered.
1. Start up your text editor, and enter the following code:
< html >
< head >
< title > Enter E-mail Data < /title >
< style type=”text/css” >
c11.indd 317c11.indd 317 12/10/08 6:05:26 PM12/10/08 6:05:26 PM
318
Part II: Comic Book Fan Site
td { vertical-align: top; }
< /style >
< /head >
< body >

< form method=”post” action=”sendmail.php” >
< table >
< tr >
< td > To: < /td >
< td > < input type=”text” name=”to_address” size=”40”/ > < /td >
< /tr > < tr >
< td > From: < /td >
< td > < input type=”text” name=”from_address” size=”40”/ > < /td >
< /tr > < tr >
< td > Subject: < /td >
< td > < input type=”text” name=”subject” size=”40”/ > < /td >
< /tr > < tr >
< td valign=”top” > Message: < /td >
< td >
< textarea cols=”60” rows=”10”
name=”message” > Enter your message here. < /textarea >
< /td >
< /tr > < tr >
< td > < /td >
< td >
< input type=”submit” value=”Send”/ >
< input type=”reset” value=”Reset”/ >
< /td >
< /tr >
< /table >
< /form >
< /body >
< /html >
2. Save the page as postcard.php . Note that postcard.php doesn ’ t actually contain any PHP
code in it. It simply collects the required data in an HTML form. You ’ re giving it a

.php
extension because you will be adding PHP code to it later.
3. Start a new text document, and enter the following code:
< ?php
$to_address = $_POST[‘to_address’];
$from_address = $_POST[‘from_address’];
$subject = $_POST[‘subject’];
$message = $_POST[‘message’];

$headers = ‘From: ‘ . $from_address . “\r\n”;
? >
< html >
< head >
< title > Mail Sent! < /title >
< /head >
< body >
< ?php
$success = mail($to_address, $subject, $message, $headers);
c11.indd 318c11.indd 318 12/10/08 6:05:26 PM12/10/08 6:05:26 PM
Chapter 11: Sending E - mail
319
if ($success) {
echo ‘ < h1 > Congratulations! < /h1 > ’;
echo ‘ < p > The following message has been sent: < br/ > < br/ > ’;
echo ‘ < b > To: < /b > ‘ . $to_address . ‘ < br/ > ’;
echo ‘ < b > From: < /b > ‘ . $from_address . ‘ < br/ > ’;
echo ‘ < b > Subject: < /b > ‘ . $subject . ‘ < br/ > ’;
echo ‘ < b > Message: < /b > < /p > ’;
echo nl2br($message);
} else {

echo ‘ < p > < strong > There was an error sending your message. < /strong > < /p > ’;
}
? >
< /body >
< /html >
4. Save this page as sendmail.php . This second page will take the values entered into the first
page and send them in an e - mail.
5. Load up the first page, postcard.php , in your browser and enter some data. Make sure you
use a valid e - mail address so that you can verify the e - mail ’ s receipt. It should look something
like Figure 11 - 1 .
Figure 11-1
c11.indd 319c11.indd 319 12/10/08 6:05:27 PM12/10/08 6:05:27 PM
320
Part II: Comic Book Fan Site
6. Click the Send button. A second page appears, similar to the one shown in Figure 11 - 2 .
Figure 11-2
7. Open your e - mail client, and check your e - mail. You should find the e - mail message, as shown
in Figure 11 - 3 .
c11.indd 320c11.indd 320 12/10/08 6:05:27 PM12/10/08 6:05:27 PM
Chapter 11: Sending E - mail
321
Figure 11-3
How It Works
Once you press the Send button on the form and submit its information, sendmail.php is loaded. The
first step in your PHP code assigns all the fields from
postcard.php to variables.
$to_address = $_POST[‘to_address’];
$from_address = $_POST[‘from_address’];
$subject = $_POST[‘subject’];
$message = $_POST[‘message’];


To specify from whom the e - mail is coming, you use the optional fourth parameter to the mail()
function,
headers . Headers are explained in more detail in the section “ Sending HTML by Using
Headers, ” later in this chapter.

$headers = ‘From: ‘ . $from_address . “\r\n”;

The mail() function returns a value of true if it is successful and false if it fails. You can use this
return value to make your application a little more robust by showing an error message if the message
cannot be sent:
$success = mail($to_address, $subject, $message, $headers);
if ($success) {
echo ‘ < h1 > Congratulations! < /h1 > ’;
echo ‘ < p > The following message has been sent: < br/ > < br/ > ’;
echo ‘ < b > To: < /b > ‘ . $to_address . ‘ < br/ > ’;
echo ‘ < b > From: < /b > ‘ . $from_address . ‘ < br/ > ’;
c11.indd 321c11.indd 321 12/10/08 6:05:27 PM12/10/08 6:05:27 PM
322
Part II: Comic Book Fan Site
echo ‘ < b > Subject: < /b > ‘ . $subject . ‘ < br/ > ’;
echo ‘ < b > Message: < /b > < /p > ’;
echo nl2br($message);
} else {
echo ‘ < p > < strong > There was an error sending your message. < /strong > < /p > ’;
}


Of course, you can modify this to handle errors more elegantly by using the knowledge you acquired
in Chapter 9 to do so.

You have now created your first PHP e - mail application. Congratulations! (Call your mother! She ’ ll be
so proud. Or better yet, e - mail her!) But you ’ ll probably soon get tired of plaintext e - mails. I ’ m sure
you ’ re chomping at the bit to create colorful, formatted e - mails. How else are you going to enable
users to send some pretty postcards?
Dressing Up Your E - mails with HTML
Because you are creating a postcard application, sending plaintext e - mails just won ’ t do. You want to
dress them up a bit and make them look attractive, and you can do that with the addition of HyperText
Markup Language, or HTML for short. In this section, we add HTML to your e - mail code to dress it up
and make it more visually appealing.
Try It Out Sending HTML Code in an E - mail
First, let ’ s try a little experiment. This step isn ’ t vital, but it will help illustrate a point about headers.
1.
Go back to step 5 of the previous “ Try It Out ” section, and send another e - mail. This time, put
some HTML in the message. An example would be:

< html >
< h1 > Hello, World! < /h1 >
< p > Prepare for our arrival we will be there soon! < /p >
< /html >

2. When you have filled out the form and clicked the Send button, check your e - mail again. It
should look something like the e - mail shown in Figure 11 - 4 .
c11.indd 322c11.indd 322 12/10/08 6:05:28 PM12/10/08 6:05:28 PM
Chapter 11: Sending E - mail
323
Figure 11-4
How It Works
Perhaps this heading should be “ How It Doesn ’ t Work. ” That ’ s because your e - mail client does not
know that it has received HTML. Why? Because you didn ’ t tell it! In order for any HTML - capable
client to display HTML, the client needs to be told that the incoming e - mail is going to have some

HTML tags on it. Only then will it know how to properly display your message.

Try It Out Sending HTML by Using Headers
You need a way for your e - mail to tell the client it contains HTML. This is accomplished by using
headers. You already saw how to use headers to include a From: parameter. Now you are going to use
a similar header to tell the client that the e - mail message contains HTML.
1. Edit your copy of sendmail.php in your text editor. Make the following highlighted
modifications to the file:

< ?php
$to_address = $_POST[‘to_address’];
$from_address = $_POST[‘from_address’];
$subject = $_POST[‘subject’];
$message = $_POST[‘message’];

$headers = array();
c11.indd 323c11.indd 323 12/10/08 6:05:28 PM12/10/08 6:05:28 PM
324
Part II: Comic Book Fan Site
$headers[] = ‘MIME-Version: 1.0’;
$headers[] = ‘Content-type: text/html; charset=iso-8859-1’;
$headers[] = ‘Content-Transfer-Encoding: 7bit’;
$headers[] = ‘From: ‘ . $from_address;
? >
< html >
< head >
< title > Mail Sent! < /title >
< /head >
< body >
< ?php

$success = mail($to_address, $subject, $message, join(“\r\n”, $headers));
if ($success) {
echo ‘ < h1 > Congratulations! < /h1 > ’;
echo ‘ < p > The following message has been sent: < br/ > < br/ > ’;
echo ‘ < b > To: < /b > ‘ . $to_address . ‘ < br/ > ’;
echo ‘ < b > From: < /b > ‘ . $from_address . ‘ < br/ > ’;
echo ‘ < b > Subject: < /b > ‘ . $subject . ‘ < br/ > ’;
echo ‘ < b > Message: < /b >
< /p > ’;
echo nl2br($message);
} else {
echo ‘ < p > < strong > There was an error sending your message. < /strong > < /p > ’;
}
? >
< /body >
< /html >

2. Save the file.
3. Load postcard.php into your browser and fill in the fields. Be sure to include some HTML in
the message field.
4. Click the Send button, and then open your e - mail client to see the new message, which will
look something like Figure 11 - 5 .
c11.indd 324c11.indd 324 12/10/08 6:05:28 PM12/10/08 6:05:28 PM
Chapter 11: Sending E - mail
325
Figure 11-5
How It Works
You replaced the $headers variable with an array that stores multiple headers. This allows you to do
many additional things with your e - mail, including sending HTML. This line is required in order to
use extended MIME capabilities (such as HTML).


MIME-Version: 1.0

Note the \r\n . This is a carriage return and new line, which must be entered between each of the
headers. UNIX sometimes allows just
\n , but to be on the safe side, you should always use \r\n .
The following indicates that you will be using HTML in your message:

Content-type: text/html; charset=iso-8859-1
Content-Transfer-Encoding: 7bit

The headers are concatenated using the join() function with a carriage return and newline character
(
\r\n ). The carriage return and newline combination must appear with each header, according to the
specifications that describe the format of e - mails.
That ’ s all there is to adding HTML to your messages. All you have to do is tell the e - mail client to
expect HTML. Now you can get fancy and create e - mail with style sheets, images, and so on.
However, there is still a concern — what if you are using an e - mail program that does not accept or
recognize HTML? You certainly want this application to be as user - friendly as possible, right? Not to
worry — you ’ ll take care of this with multipart (or mixed) messages.

c11.indd 325c11.indd 325 12/10/08 6:05:29 PM12/10/08 6:05:29 PM

×