HomePHP Page 6 - Building A PHP-Based Mail Client (part 1)
Calling The Exterminator - PHP
Ever wondered how Web-based mail clients work, or what happens toyour email after you hit the "Send" button? This three-part case studydelves into the wild and wacky world of Web-based email applications, usingPHP's built-in POP3 functions to build an email client suitable forrerieving POP3 email via a Web browser. In this introductory segment -connecting to a POP3 server, logging in and out, retrieving message headersfor display, and deleting messages off the server.
You'll remember, from the previous pages, that every message in the message list has a checkbox accompanying it. This box, if checked, indicates that the message is to be deleted from the mail server.
If you take a close look at "list.php", you'll see that every checkbox is associated with the $dmsg array; once the form is submitted, this array will contain the numbers of all the messages selected for deletion. The "delete.php" script then needs only to connect to the mail server and iterate through this array, marking the specified messages for deletion.
Yes, it really is as simple as it sounds - take a look at the script:
<?
// delete.php - delete messages
// session check
session_start();
if (!session_is_registered("SESSION"))
{
header("Location: error.php?ec=2");
exit;
}
// open POP connection
$inbox = @imap_open ("{". $SESSION_MAIL_HOST . "/pop3:110}",
$SESSION_USER_NAME, $SESSION_USER_PASS) or header("Location:
error.php?ec=3");
// delete specified message numbers
for($x=0; $x<sizeof($dmsg); $x++)
{
imap_delete($inbox, $dmsg[$x]);
}
// clean up and go back to list page
imap_close($inbox, CL_EXPUNGE);
header("Location: list.php");
?>
As always, the first step is to check for the existence of a
valid session. Assuming that exists, a connection is opened to the mail server and the imap_delete() function, in combination with the contents of the $dmsg array, is used to mark messages for deletion (if you're familiar with the POP3 protocol, this is equivalent to sending a series of DELE commands to the server).
It should be noted that imap_delete() merely marks messages for deletion; it does not actually remove them from the server. In order to actually erase the marked messages, it's necessary to specify the CL_EXPUNGE argument while closing the mailbox with imap_close() (an alternative here would be to use the equivalent imap_expunge() command).
Once all messages have been deleted, the browser is redirected to the message list. Deleted messages should now no longer appear in this list.