ebook img

Building effective Web sites PDF

23 Pages·2002·0.072 MB·English
Save to my drive
Quick download
Download
Most books are stored in the elastic cloud where traffic is expensive. For this reason, we have a limit on daily download.

Preview Building effective Web sites

By icarus This article copyright Melonfire 2000−2002. All rights reserved. Building A PHP−Based Mail Client (part 1) Table of Contents Simply M@gical..................................................................................................................................................1 Requiring Immediate Attention.........................................................................................................................2 Start Me Up.........................................................................................................................................................4 Fully Function−al................................................................................................................................................7 Opening Up..........................................................................................................................................................8 Treating Messages As Objects.........................................................................................................................15 Calling The Exterminator................................................................................................................................19 Back To Square One.........................................................................................................................................21 i Simply M@gical It's almost hard to believe that, up until a few years ago, putting pen to paper was still the most common method of corresponding with long−lost relatives or distant business partners. Today, email is all−pervasive − it has a user base ranging from doting grandmothers to over−enthusiastic dot−commers − and is, by far, the fastest, most efficient way to communicate. Arthur C. Clarke once said that any sufficiently advanced technology was indistinguishable from magic; with millions of messages criss−crossing the globe at any given time, email has some pretty potent magic of its own. As a developer, email, and the systems designed to process it, have always fascinated me. Ever since I got my first email account, I've always found there to be something magical about the process by which a text message is encoded and bounced around the world from one mail server to another until it reaches its recipient, thence to be decoded back into its original form and displayed. And so, when I was offered the opportunity to work on a Web−based email client a few weeks back, I jumped at it; here, at last, was my chance to learn a little bit more about what actually happens after you hit the "Send" button... As it turned out, building a mail client wasn't anywhere near as hard as I thought it would be...and with the help of powerful open−source tools like PHP, the process was simplified considerably. Over the course of this article, I'm going to demonstrate how, by building a PHP−based mail client suitable for reading and writing email in any Web browser. The goal here is two−fold: to introduce novice and intermediate programmers to the process of designing and implementing a Web−based application, with special reference to PHP's mail functions, and to offer road warriors, network administrators, email buffs and other interested folk a functional (and fairly good−looking) email solution for use on their corporate intranet or Web site. Lofty goals, you scoff? Well, let's see... Simply M@gical 1 Requiring Immediate Attention Before we get into the nitty−gritty of syntax and structure, it's important to first put down the requirements of the software to be designed. This is a sometimes−tedious but always−necessary precedent to actual implementation of any software project, as it simultaneously offers a "big picture" view of the entire project and also provides a reference for the actual code development. Typically, the software requirements are obtained after an analysis of the problems faced by the customer − an intensive, frequently−frustrating process involving large amounts of caffeine. In this specific case, though, I was able to arrive at the requirements after a fairly short conversation with the customer, during which the following problems became clear: 1. Members of the customer's sales team were frequently on the road chasing down leads. During this period, they had no way of accessing their internal corporate mail. The customer was looking for a tool that would allow employees to get to their mail even if they weren't physically at the workplace. 2. A number of the customer's employees were part−time or freelance workers, who came to the office only occasionally. Rather than assign these part−timers a dedicated computer each, the customer wanted to assign them a single "guest" machine, which could be used by them whenever they came in to work. A Web−based mail solution would be useful here too, as it would allow different users to use a single machine to read their mail. The customer's evaluation of his problems has led him to conclude that he needed a simple Web−based mail client, along the lines of Hotmail (http://www.hotmail.com) or Mail.com (http://www.mail.com). Consequently, the brief was simple enough: a mail client which supported the standard feature set of Windows mail clients like Eudora and Microsoft Outlook, yet was accessible via a Web browser. After a little research, I came up with the following list of software requirements (which was eventually approved by the customer): 1. The application must be capable of connecting to any POP3−compatible mail server (IMAP support was not a requirement) and retrieving a list of messages for a user−specified mailbox on that server. This message list must display important message headers − the sender, subject and size − together with (optionally) an attachment icon. 2. The application must be capable of displaying the contents of any message from the message list. 3. The application must allow the user to create and send a new email message (to multiple recipients simultaneously, if required) 4. The application must allow the user to reply to any message. 5. The application must allow the user to forward any message, with the option to include all, some or none of the message's original attachments. 6. The application must allow the user to delete any message from the server. 7. The application must support mail attachments, and allow the user to download these to his local Requiring Immediate Atten... 2 Building A PHP−Based Mail Client (part 1) workstation, or upload them for attachment to a new message. This is a fairly standard feature set, and you'll find that almost every mail client allows you to perform these actions. Note that the list above is somewhat abridged − the actual requirements document was a bit more detailed, and included some additional items that will not be discussed here − but it still has enough material to give you a fairly good idea of what I'll be covering in this case study. Putting down software requirements is a good starting point for any project, both from the implementation point of view and for other, related activities. Once the requirements are written down and approved by the customer, the developer can begin thinking about how to design and code the application, the interface designer can begin work on the application's user interface, and the QA team can begin building test cases to verify the final release of the code. Requiring Immediate Atten... 3 Start Me Up With the requirements clearly defined, it's time to actually start writing some code. Since I'm a big fan of PHP, I plan to use that as my weapon of choice during this exercise. My natural inclination towards PHP is further influenced by the fact that PHP comes with a full−featured set of commands for working with IMAP and POP3 mailboxes − something I'm going to be needing over the course of this project. This is a good time for you to download the source code, so that you can refer to it throughout this article (you will need a Web server capable of running PHP 4.0.6, with its IMAP extension enabled). mail.zip First up, the user login process, and the scripts which verify the user's password and grant access to the mail server. Here's the initial login form, "index.php": <form name="login" method="POST" action="<? echo $PHP_SELF; ?>"> <table border="0" cellspacing="5" cellpadding="5" align="center" valign="middle"> <tr> <td align="right"><font face="Verdana" size="−1">Email address</font></td> <td align="left"><input type=text name=email size=30></td> </tr> <tr> <td align="right"><font face="Verdana" size="−1">Password</font></td> <td align="left"><input type=password name=pass size=10></td> </tr> <td colspan="2" align="middle"><input name="submit" type="submit" value="Read Mail"></td> </tr> </table> </form> Extremely simple, this − two fields, one for the user's email address, in the form <[email protected]> and one for his password. Here's what it looks like: Start Me Up 4 Building A PHP−Based Mail Client (part 1) Now, this script is actually split into two parts: the first part displays the login form above, while the second part processes the data entered into it. An "if" loop, keyed against the presence of the $submit variable, is used to decide which part of the script to execute. Here's what happens once the form is submitted: <? // index.php − display login form if (!$submit) { // form not yet submitted // display login box } else { ?> // form submitted include("functions.php"); if (!$email || !$pass || !validate_email($email)) { header("Location: error.php?ec=1"); exit; } // separate email address into username and hostname // by splitting on @ symbol $arr = explode('@', $email); $user = trim(stripslashes($arr[0])); $host = trim(stripslashes($arr[1])); $pass = trim(stripslashes($pass)); Start Me Up 5 Building A PHP−Based Mail Client (part 1) // store the details in session variables session_start(); session_register("SESSION"); session_register("SESSION_USER_NAME"); session_register("SESSION_USER_PASS"); session_register("SESSION_MAIL_HOST"); // assign values to the session variables $SESSION_USER_NAME = $user; $SESSION_USER_PASS = $pass; $SESSION_MAIL_HOST = $host; // redirect user to the list page header("Location: list.php"); } ?> The first order of business is to verify that all the information required to connect to the mail server has been entered by the user; this information includes a valid email address and password. Assuming that both are present, the explode() function is used to split the email address into user and host components. Next, a PHP session is initiated, and the username, password and host name are registered as session variables with the session_register() command; these values can then be used by other scripts within the application. Finally, the browser is redirected to another script, "list.php", which uses the information supplied to attempt a POP3 connection and retrieve a list of messages in the user's mailbox. This redirection is accomplished by sending an HTTP header containing the new URL to the browser via PHP's very powerful header() command. It's important to note that calls to header() and session_start() must take place before *any* output is sent to the browser. Even something as minor as whitespace or a carriage return outside the PHP tags can cause these calls to barf all over your script. Start Me Up 6 Fully Function−al Before moving on, a quick word about the "functions.php" file include()d in the script you just saw. "functions.php" is a separate file containing useful function definitions. Every time I write a function that might come in useful elsewhere in the application, I move it into "functions.php" and include that file in my script. An example of this is the validate_email() function used in the script above − here's what it looks like: <? // check if email address is valid function validate_email($val) { if($val != "") { $pattern = "/^([a−zA−Z0−9])+([\.a−zA−Z0−9_−])*@([a−zA−Z0−9_−])+(\.[a−zA−Z0−9_−]+)+/"; if(preg_match($pattern, $val)) { return true; } else { return false; } } else { return false; } } ?> Again, this is fairly simple − I'm using PHP's pattern matching capabilities to verify that the email address supplied conforms to the specified pattern. The function returns true or false depending on whether or not the match was successful. Fully Function−al 7 Opening Up With the session instantiated, the next step is to retrieve and display a list of messages from the user's mailbox on the mail server. This is accomplished via "list.php", a PHP script which opens a connection to the POP3 server, obtains a list of message headers and displays them in a neat table. Before getting into the details of "list.php", I want to take a minute to explain a little something about the user interface. If you look at the sample screenshots in this article, you'll see that every page generated through this application has some common elements: the logo at the top left corner, the copyright note at the top right corner, and a dividing bar containing the page title below both. Since these elements will remain constant through the application, I've placed the corresponding HTML code in a separate header file, and simply include()d them on each page. Take a look at "header.php": <table width="100%" border="0" cellspacing="0" cellpadding="5"> <tr> <td><img src="images/logo.jpg" width=67 height=55 alt="" border="0"></td> <td valign="bottom" align="right"><font size="−2" face="Verdana">Everything here is &copy; <a href="http://www.melonfire.com/">Melonfire</a>, 2001.<br>All rights reserved.</font></td> </tr> <tr> <td bgcolor="#C70D11" align="left"><font size="−1" color="white" face="Verdana"><b><? echo $title; ?></b></font></td> <td bgcolor="#C70D11" align="right"><? if(session_is_registered("SESSION")) { ?><font size="−1" color="white" face="Verdana"><b><a style="color: white" href="logout.php">Log Out</a></b></font><? } ?>&nbsp;</td> </tr> </table> Again, by separating common interface elements into separate files, I've made it easier to customize the look of the application; simply alter these files, and the changes will be reflected on all the pages. Note that the page title needs to be specified as a variable prior to including this header file in a script − you'll see examples of this over the next few pages. Note also the link to log out, which appears only after the user has logged in (I've used the session_is_registered() function to test for the presence of a valid PHP session). Okay, back to "list.php". Here's the script: Opening Up 8

See more

The list of books you might like

Most books are stored in the elastic cloud where traffic is expensive. For this reason, we have a limit on daily download.