This file is loaded in the browser with an ID in the URL to designate which saved postcard is awaiting confirmation, and the script then sends the postcard to the intended recipient.. Cl
Trang 1message TEXT, PRIMARY KEY (email_id) )
ENGINE=MyISAM’;
mysql_query($query, $db) or die (mysql_error($db));
echo ‘Success!’;
?
2 Run db_ch10 - 2.php , and you should see the success message displayed
3 Open up postcard.php in your editor and replace its content with the following code:
< ?phprequire ‘db.inc.php’;
s.onchange = change_postcard_image;
} function change_postcard_image() { var s = document.getElementById(‘postcard_select’);
var i = document.getElementById(‘postcard’);
var x = s.options.selectedIndex;
// update image’s src and alt attributes i.src = s.options[x].value;
i.alt = s.options[x].text;
} < /script >
Trang 2$query = ‘SELECT image_url, description FROM pc_image ORDER BY description’;
$result = mysql_query($query, $db) or die(mysql_error());
while ($row = mysql_fetch_assoc($result)) {
echo ‘ < option value=”’ $row[‘image_url’] ‘” > ’ $row[‘description’]
< img id=”postcard” src=” < ?php echo $image_url; ? >
alt=” < ?php echo $description; ? > ” / >
< textarea cols=”76” rows=”12”
name=”message” > Enter your message here < /textarea >
< /td >
< /tr > < tr >
< td colspan=”2” >
< input type=”submit” value=”Send” / >
< input type=”reset” value=”Reset the form” / >
Trang 34 Next, write sendconfirm.php , the page that sends out the confirmation e - mail to the user.
< ?phprequire ‘db.inc.php’;
$query = ‘SELECT description FROM pc_image WHERE image_url = “’ $postcard ‘”’;
$result = mysql_query($query, $db) or die(mysql_error());
$description = ‘’;
if (mysql_num_rows($result)){
$row = mysql_fetch_assoc($result);
$description = $row[‘description’];
}mysql_free_result($result);
VALUES (NULL, “’ $token ‘”, “’ $to_name ‘”, “’ $to_email ‘”, “’ $from_name ‘”, “’ $from_email ‘”, “’ $subject ‘”, “’ $postcard ‘”, “’ $message ‘”)’;
$headers[] = ‘Content-type: text/html; charset=”iso-8859-1”’;
$headers[] = ‘Content-Transfer-Encoding: 7bit’;
$headers[] = ‘From: no-reply@localhost’;
Trang 4echo ‘ < h1 > Pending Confirmation! < /h1 >
echo ‘ < > A confirmation e-mail has been sent to ‘ $from_email ‘ ‘
‘Open your e-mail and click on the link to confirm that you ‘
‘would like to send this postcard to ‘ $to_name ‘ < /p >
5 Next is confirm.php This file is loaded in the browser with an ID in the URL to designate
which saved postcard is awaiting confirmation, and the script then sends the postcard to the
intended recipient
< ?php
require ‘db.inc.php’;
$db = mysql_connect(MYSQL_HOST, MYSQL_USER, MYSQL_PASSWORD) or
die (‘Unable to connect Check your connection parameters.’);
mysql_select_db(MYSQL_DB, $db) or die(mysql_error($db));
$id = (isset($_GET[‘id’])) ? $_GET[‘id’] : 0;
$token = (isset($_GET[‘token’])) ? $_GET[‘token’] : ‘’;
$query = ‘SELECT email_id, token, to_name, to_email, from_name, from_email,
subject, postcard, message FROM pc_confirmation WHERE
Trang 5}
$boundary = ‘==MP_Bound_xyccr948x==’;
$headers = array();
$headers[] = ‘MIME-Version: 1.0’;
$headers[] = ‘Content-type: multipart/alternative; boundary=”’ $boundary ‘”’;
$headers[] = ‘From: ‘ $from_email;
$postcard_message = ‘ < html >
$postcard_message = ‘ < > Greetings, ‘ $to_name ‘! ‘;
$postcard_message = $from_name ‘ has sent you a postcard today < /p >
‘ & token=’ $token ’ < /a > to view this postcard online < /p > < /html >
$mail_message = ‘This is a Multipart Message in MIME format’ “\n”;
$mail_message = ‘ ’ $boundary “\n”;
$mail_message = ‘Content-type: text/html; charset=”iso-8859-1”’ “\n”;
$mail_message = ‘Content-Transfer-Encoding: 7bit’ “\n\n”;
$mail_message = $postcard_message “\n”;
$mail_message = ‘ ’ $boundary “\n”;
$mail_message = ‘Content-Type: text/plain; charset=”iso-8859-1”’ “\n”;
$mail_message = ‘Content-Transfer-Encoding: 7bit’ “\n\n”;
echo ‘ < > The following postcard has been sent to ‘ $to_name ‘: < br/ > < /p >
echo $postcard_message;
} else { echo ‘ < > < strong > There was an error sending your message < /strong > < /p >
}
? /body >
< /html >
Trang 66 Next, you ’ ll create a form that allows a user to view the postcard Call this one
viewpostcard.php
< ?php
require ‘db.inc.php’;
$db = mysql_connect(MYSQL_HOST, MYSQL_USER, MYSQL_PASSWORD) or
die (‘Unable to connect Check your connection parameters.’);
mysql_select_db(MYSQL_DB, $db) or die(mysql_error($db));
$id = (isset($_GET[‘id’])) ? $_GET[‘id’] : 0;
$token = (isset($_GET[‘token’])) ? $_GET[‘token’] : ‘’;
$query = ‘SELECT email_id, token, to_name, to_email, from_name, from_email,
subject, postcard, message FROM pc_confirmation WHERE
7 Load postcard.php in your browser to verify that it works The results should look similar
to what ’ s shown in Figure 11 - 6
Trang 7Figure 11-6
Trang 88 Enter the appropriate information; remember to put in valid e - mail addresses in the Sender ’ s
E - mail and Recipient ’ s E - mail fields
9 In the Choose a Postcard field, select a postcard from the drop - down list, enter a message, and
click the Send button A screen similar to the one shown in Figure 11 - 7 loads
Figure 11-7
10 Check your e - mail You should receive an e - mail that looks something like Figure 11 - 8
Trang 911 Click the link in the e - mail to confirm that you want to send the postcard
12 Open the e - mail account this postcard was sent to (see Figure 11 - 9 )
You did send it to an e - mail address you have access to, right? If you sent this to your little sister, we sure hope you didn ’ t scare her!
Figure 11-8
Trang 10Figure 11-9
How It Works
Your application is getting more complex However, it is still fairly basic in the functionality it offers
Here ’ s what it does:
The user loads postcard.php and fills out all the fields He or she also selects a postcard to
be sent In the Sender ’ s E - mail field, the user enters his or her e - mail address
❑
Trang 11After clicking Send, the user receives an e - mail showing what the postcard and message look like A link is provided at the bottom of the e - mail for the user to click on, to confirm the postcard
Once the user clicks the confirmation link, the postcard is sent to the intended recipient
Taking a closer look at the start of it, you see in postcard.php that you used a query to retrieve the list of images from the database This is pretty straightforward and is something you ’ ve done several times already But this time you used extract() on the first returned row and then reset the result list ’ s internal pointer back to its beginning with mysql_data_seek() , before generating the options for the select element
< select id=”postcard_select” name=”postcard” >
< ?php
$query = ‘SELECT image_url, description FROM pc_image ORDER BY description’;
$result = mysql_query($query, $db) or die(mysql_error());
$row = mysql_fetch_assoc($result);
extract($row);
mysql_data_seek($result, 0);
while ($row = mysql_fetch_assoc($result)) { echo ‘ < option value=”’ $row[‘image_url’] ‘” > ’ $row[‘description’] ‘ < /option >
}mysql_free_result($result);
?
< /select >
When the page first loads the select list, it shows its first option as the active postcard selection The
$image_url and $description variables populated by extract() are used as the initial values for the postcard ’ s image element, so the two are initially in sync
< img id=”postcard” src=” < ?php echo $image_url; ? >
alt=” < ?php echo $description; ? > ” / >
Only the surface of using PHP, Apache, and MySQL has been scratched, but we ’ re sure you will agree this book is large enough, and that if we were to start discussing the intricacies of JavaScript, then you might give yourself a hernia just trying to take it off the bookshelf! You ’ re right, JavaScript is beyond the scope of this book But because PHP code only runs on the server, not in the client ’ s browser, it cannot be used to keep the displayed images in sync with each other once the page has been generated and sent off Using JavaScript in this situation helps you reduce loading time and round trips to the server The following lines of extra code written in JavaScript are included in the page:
< script type=”text/javascript” >
window.onload = function() { // assign change_postcard_image to select field var s = document.getElementById(‘postcard_select’);
s.onchange = change_postcard_image;
} function change_postcard_image() { var s = document.getElementById(‘postcard_select’);
❑
❑
Trang 12If you want to know more about JavaScript, we recommend starting with ppk on JavaScript , by
Peter - Paul Koch (New Riders, 2006)
Now you move on to sendconfirm.php Much of it is similar to sendmail.php , so we ’ ll just touch
on the script ’ s most important point Before sending the confirmation e - mail, a token is generated and,
together with the message, is stored in the pc_confirmation database table
$token = md5(time());
$query = ‘INSERT INTO pc_confirmation
(email_id, token, to_name, to_email, from_name, from_email, subject,
postcard, message)
VALUES
(NULL, “’ $token ‘”, “’ $to_name ‘”, “’ $to_email ‘”,
“’ $from_name ‘”, “’ $from_email ‘”, “’ $subject ‘”,
“’ $postcard ‘”, “’ $message ‘”)’;
mysql_query($query, $db) or die(mysql_error());
You used the md5() function to create the token This returns a 128 - bit “ fingerprint, ” or “ hash value, ”
of the message passed to it For example, the MD5 hash of “ Hello World ” is b10a8db164e0754105b7a99
be72e3fe5 The MD5 algorithm is designed as a one - way encryption of the data passed in to it, so it
cannot be reversed to discover the original value Using a one - way hash in this manner allows you to
safely have the user click on a link in his or her e - mail to view the postcard If you used a simple
number or keyword, a malicious user could more easily guess the URL and ruin all your fun —
guessing an MD5 hash would take too long to make it worthwhile for the hacker
By passing in a time value, you can be fairly certain that the MD5 hash returned will be a unique
value, which you use as a unique ID for the data It is not 100 percent guaranteed to be unique, but
because it is generated based on the current time in seconds and contains 32 alphanumeric characters,
you can be reasonably sure it will be unique
You should read RFC 1321 if you are interested in finding out more information about the
MD5 hash RFC 1321: “ The MD5 Message - Digest Algorithm ” is available online at
www.faqs.org/rfcs/rfc1321
Trang 13
sendconfirm.php sends an e - mail that includes a link to confirm.php and passes the message ’ s ID and token in the URL string The postcard data sits patiently until the sender receives the confirmation message and follows the link that will finally send the postcard to the intended recipient
$confirm_message = ‘ < > < a href=”http://localhost/confirm.php?id=’ $email_id ‘ & token=’ $token ’” > Click here to confirm < /a > < /p > ’;
When the sender receives the confirmation message, he or she clicks the link, and confirm.php is loaded in a web browser The script takes in the message ID and unique validation token and uses them
to retrieve the message from the database
$id = (isset($_GET[‘id’])) ? $_GET[‘id’] : 0;
$token = (isset($_GET[‘token’])) ? $_GET[‘token’] : ‘’;
if (mysql_num_rows($result) == 0) { echo ‘ < > Oops! Nothing to confirm Please contact your administrator < /p > mysql_free_result($result);
exit;
} else { $row = mysql_fetch_assoc($result);
extract($row);
mysql_free_result($result);
}
Creating a Reusable Mail Class
Now that you ’ ve seen how to perform basic e - mail functions using PHP, it ’ s time to take what you ’ ve learned and make a nice reusable code component PHP objects and classes were discussed briefly, earlier in this book, but you haven ’ t done much with them So, this code will be written as a class The benefit to writing this as a class is that it will be self - contained to make reusability easier
Trang 14Try It Out Creating a Reusable Mail Class
You are going to be creating a very handy file, class.SimpleMail.php This file is going to contain a
PHP class that will supplement PHP ’ s simple mail() function The class will encapsulate sending a
multipart e - mail, which helps keep your source code cleaner when you use it
1 Open your editor, and create a new PHP file called class.SimpleMail.php :
// initialize the message parts with blank or default values
public function construct() {
public function setToAddress($value) {
$this- > toAddress = $value;
}
// set CC address
public function setCCAddress($value) {
$this- > CCAddress = $value;
}
// set BCC address
public function setBCCAddress($value) {
$this- > BCCAddress = $value;
}
// set FROM address
public function setFromAddress($value) {
Trang 15$this- > fromAddress = $value;
} // set message subject public function setSubject($value) { $this- > subject = $value;
} // set whether to send email as text public function setSendText($value) { $this- > sendText = $value;
} // set text email message body public function setTextBody($value) { $this- > sendText = true;
$this- > textBody = $value;
} // set whether to send email as HTML public function setSendHTML($value) { $this- > sendHTML = $value;
} // set text HTML message body public function setHTMLBody($value) { $this- > sendHTML = true;
$this- > HTMLBody = $value;
} // send email public function send($to = null, $subject = null, $message = null, $headers = null) {
$success = false;
if (!is_null($to) & & !is_null($subject) & & !is_null($message)) { $success = mail($to, $subject, $message, $headers);
return $success;
} else { $headers = array();
if (!empty($this- > fromAddress)) { $headers[] = ‘From: ‘ $this- > fromAddress;
}
if (!empty($this- > CCAddress)) { $headers[] = ‘CC: ‘ $this- > CCAddress;
}
if (!empty($this- > BCCAddress)) { $headers[] = ‘BCC: ‘ $this- > BCCAddress;
}
if ($this- > sendText & & !$this- > sendHTML) { $message = $this- > textBody;