1. Trang chủ
  2. » Công Nghệ Thông Tin

Phát triển web với PHP và MySQL - p 67 doc

10 177 0
Tài liệu đã được kiểm tra trùng lặp

Đang tải... (xem toàn văn)

THÔNG TIN TÀI LIỆU

Thông tin cơ bản

Định dạng
Số trang 10
Dung lượng 657,21 KB

Các công cụ chuyển đổi và chỉnh sửa cho tài liệu này

Nội dung

L ISTING 27.5 store_account_settings Function from mail_fns.php—Function to SaveNew Account Details for a User function store_account_settings$auth_user, $settings { if!filled_out$settin

Trang 1

L ISTING 27.5 store_account_settings() Function from mail_fns.php—Function to Save

New Account Details for a User

function store_account_settings($auth_user, $settings)

{

if(!filled_out($settings))

{

echo “All fields must be filled in Try again.<br><br>”;

return false;

}

else

{

if($settings[‘account’]>0)

$query = “update accounts set server = ‘$settings[server]’,

port = $settings[port], type = ‘$settings[type]’, remoteuser = ‘$settings[remoteuser]’,

remotepassword = ‘$settings[remotepassword]’

where accountid = $settings[account]

and username = ‘$auth_user’”;

else

$query = “insert into accounts values (‘$auth_user’,

‘$settings[server]’, $settings[port],

‘$settings[type]’, ‘$settings[remoteuser]’,

‘$settings[remotepassword]’, NULL)”;

if(db_connect() && mysql_query($query)) {

return true;

} else { echo “could not store changes.<br><br><br><br><br><br>”;

return false;

} }

}

As you can see, two choices within this function correspond to inserting a new account or

updating an existing account The function executes the appropriate query to save the account

details

After storing the account details, we go back to index.php, to the main body stage:

case ‘store-settings’ :

case ‘account-setup’ :

case ‘delete-account’ :

{

display_account_setup($auth_user);

break;

}

27

Trang 2

As you can see, we then execute the display_account_setup() function as before to list the user’s account details The newly added account will now be included

Modifying an Existing Account

The process for modifying an existing account is very similar The user can change the account details and click the Save Changes button Again this will trigger the store-settingsaction, but this time it will update the account details instead of inserting them

Deleting an Account

To delete an account, the user can click the Delete Account button that is shown under each account listing This activates the delete-accountaction

In the preprocessing section of the index.phpscript, we will execute the following code: case ‘delete-account’ :

{ delete_account($auth_user, $account);

break;

} This code calls the delete_account()function The code for this function is shown in Listing 27.6 Deleting accounts needs to be handled before the header because a choice of which account to use is inside the header The account list needs to be updated before this can be cor-rectly drawn

L ISTING 27.6 delete_account() Function from mail_fns.php—Function to Delete a Single Account’s Details

function delete_account($auth_user, $accountid) {

//delete one of this user’s accounts from the DB

$query = “delete from accounts where

accountid=’$accountid’ and username = ‘$auth_user’”;

if(db_connect()) {

$result = mysql_query($query);

} return $result;

}

Trang 3

After execution returns toindex.php, the body stage will run the following code:

case ‘store-settings’ :

case ‘account-setup’ :

case ‘delete-account’ :

{

display_account_setup($auth_user);

break;

}

You will recognize this as the same code we ran before—it just displays the list of the user’s

accounts

Reading Mail

After the user has set up some accounts, we can move on to the main game: connecting to

these accounts and reading mail

Selecting an Account

We need to select one of the user’s accounts to read mail from The currently selected account

is stored in the $selected_accountsession variable

If the user has a single account registered in the system, it will be automatically selected when

he logs in, as follows:

if(number_of_accounts($auth_user)==1)

{

$accounts = get_account_list($auth_user);

$selected_account = $accounts[0];

session_register(“selected_account”);

}

Thenumber_of_accounts()function, from mail_fns.php, is used to work out whether the

user has more than one account The get_account_list()function retrieves an array of the

names of the user’s accounts In this case there is exactly one, so we can access it as the

array’s 0value

The number_of_accounts()function is shown in Listing 27.7

L ISTING 27.7 number_of_accounts() Function from mail_fns.php—Function to Work Out

How Many Accounts a User Has Registered

function number_of_accounts($auth_user)

{

// get the number of accounts that belong to this user

27

Trang 4

$query = “select count(*) from accounts where username = ‘$auth_user’”; if(db_connect())

{

$result = mysql_query($query);

if($result) return mysql_result($result, 0, 0);

} return 0;

}

The get_account_list()function is similar to the get_accounts()function we looked at before except that it only retrieves the account names

If a user has multiple accounts registered, he will need to select one to use In this case, the headers will contain a SELECTthat lists the available mailboxes Choosing the appropriate one will automatically display the mailbox for that account You can see this in Figure 27.5

L ISTING 27.7 Continued

F IGURE 27.5

After the localhost account is selected from the SELECTbox, the mail from that account is downloaded and displayed.

Trang 5

This SELECToption is generated in the do_html_header()function from output_fns.php, as

shown in the following code fragment:

<?

// include the account select box only if the user has more than one account

if(number_of_accounts($auth_user)>1)

{

echo “<form target=’index.php?action=open-mailbox’ method=post>”;

echo ‘<td bgcolor = “#ff6600” align = right valign = middle>’;

display_account_select($auth_user, $selected_account);

echo ‘</td>’;

echo “</form>”;

}

?>

We have generally avoided discussing the HTML used in the examples in this book, but the

HTML generated by the function display_account_select()bears a visit

Depending on the accounts the current user has,display_account_select()will generate

HTML like this:

<select onchange=window.location=this.options[selectedIndex].value name=account>

<option value = 0 selected>

Choose Account</a>

<option value = ‘index.php?action=select-account&account=10’>

mail.domain.com

</option>

<option value = ‘index.php?action=select-account&account=11’>

mail.server.com

</option>

<option value = ‘index.php?action=select-account&account=9’>

localhost

</option>

</select>

Most of this code is just an HTML select element, but it also includes a little JavaScript In the

same way that PHP can generate HTML, it can also be used to generate client-side scripts

Whenever a change event happens to this element, JavaScript will set window.locationto the

value of the option If your user selects the first option in the select,window.locationwill be

set to ‘index.php?action=select-account&account=10’ This will result in this URL being

loaded Obviously, if the user has a browser that does not support JavaScript or has JavaScript

disabled, this code will have no effect

The display_account_select()function, from output_fns.php, is used to get the available

account list and display the SELECT It also uses the get_account_list()function we

dis-cussed previously

27

Trang 6

Choosing one of the options in the SELECTactivates the select_accountevent If you look at the URL in Figure 27.5, you can see this appended to the end of the URL, along with the account ID of the chosen account

This has two effects First, in the preprocessing stage of index.php, the chosen account will be stored in the session variable $selected_account, as follows:

case ‘select-account’ : {

// if have chosen a valid account, store it as a session variable if($account&&account_exists($auth_user, $account))

{

$selected_account = $account;

session_register(‘selected_account’);

} } Second, when the body stage of the script is executed, the following code will be executed: case ‘select-account’ :

case ‘view-mailbox’ : {

// if mailbox just chosen, or view mailbox chosen, show mailbox display_list($auth_user, $selected_account);

break;

}

As you can see, we take the same action here as if the user had chosen the View Mailbox option We’ll look at that next

Viewing Mailbox Contents

Mailbox contents can be viewed with the display_list()function This displays a list of all the messages in the mailbox The code for this function is shown in Listing 27.8

L ISTING 27.8 display_list() Function from output_fns.php—Function to Display All Mailbox Messages

function display_list($auth_user, $accountid) {

// show the list of messages in this mailbox global $table_width;

if(!$accountid) {

Trang 7

echo “No mailbox selected<br><br><br><br><br><br>.”;

}

else

{

$imap = open_mailbox($auth_user, $accountid);

if($imap) {

echo “<table width = $table_width cellspacing = 0

cellpadding = 6 border = 0>”;

$headers = imap_headers($imap);

// we could reformat this data, or get other details using // imap_fetchheaders, but this is not a bad summary so we just echo each

$messages = sizeof($headers);

for($i = 0; $i<$messages; $i++) {

echo “<tr><td bgcolor = ‘“;

if($i%2) echo “#ffffff”;

else echo “#ffffcc”;

echo “‘><a href =’index.php?action=view-message&messageid=”.($i+1).”’>”;

echo $headers[$i];

echo “</a></td></tr>\n”;

} echo “</table>”;

} else {

$account = get_account_settings($auth_user, $accountid);

echo “could not open mail box “.$account[‘server’].”.<br><br><br><br>”;

} }

}

In this function, we actually begin to use PHP’s IMAP functions The two key parts of this

function are opening the mailbox and reading the message headers

27

L ISTING 27.8 Continued

Trang 8

We open the mailbox for a user account with a call to the open_mailbox()function that we have written in mail_fns.php This function is shown in Listing 27.9

L ISTING 27.9 open_mailbox() Function from mail_fns.php—This Function Connects to a User Mailbox

function open_mailbox($auth_user, $accountid) {

// select mailbox if there is only one if(number_of_accounts($auth_user)==1) {

$accounts = get_account_list($auth_user);

$selected_account = $accounts[0];

session_register(“selected_account”);

$accountid = $selected_account;

} // connect to the POP3 or IMAP server the user has selected

$settings = get_account_settings($auth_user, $accountid);

if(!sizeof($settings)) return 0;

$mailbox = “{“.$settings[server];

if($settings[type]==’POP3’)

$mailbox = ‘/pop3’;

$mailbox = “:”.$settings[port].”}INBOX”;

// suppress warning, remember to check return value

@ $imap = imap_open($mailbox, $settings[remoteuser],

$settings[remotepassword]);

return $imap;

}

We actually open the mailbox with the imap_open()function This function has the following prototype:

int imap_open (string mailbox, string username, string password [, int flags])

The parameters you need to pass to it are as follows:

• mailbox—This string should contain the server name and mailbox name, and optionally

a port number and protocol The format of this string is

{hostname/protocol:port}boxname

Trang 9

If the protocol is not specified, it defaults to IMAP In the code we have written, you can see that we specify POP3 if the user has specified that protocol for a particular account

For example, to read mail from the local machine using the default ports, we would use the following mailbox name for IMAP

{localhost:143}INBOX and this one for POP3 {localhost/pop3:110}INBOX

• username—The username for the account

• password—The password for the account You can also pass it optional flags to specify options such as “open mailbox in read-only

mode”

One thing to note is that we have constructed the mailbox string piece by piece with the

con-catenation operator before passing it to imap_open() You need to be careful how you construct

this string because strings containing {$cause problems in PHP 4

This function call returns an IMAP stream if the mailbox can be opened, and falseif it cannot

When you are finished with an IMAP stream, you can close it using imap_close(imap_stream)

In our function, the IMAP stream is passed back to the main program We then use the

imap_headers()function to get the email headers for display:

$headers = imap_headers($imap);

This function returns header information for all mail messages in the mailbox we have

con-nected to The information is returned as an array, one line per message We haven’t formatted

this It just outputs one line per message, so you can see from looking at Figure 27.5 what the

output looks like

You can get more information about email headers using the confusing, similarly named

imap_header() In this case, the imap_headers()function gives us enough detail for our

purpose

Reading a Mail Message

We have set up each of the messages in the previous display_list()function to link to

specific email messages

Each link is of the form

index.php?action=view-message&messageid=6

27

Trang 10

The messageidis the sequence number used in the headers we retrieved earlier Note that IMAP messages are numbered from 1, not 0

If the user clicks one of these links, he will see output like that shown in Figure 27.6

F IGURE 27.6

Using the view-messageaction shows us a particular message—in this case, it’s a piece of spam.

When we enter these parameters into the index.phpscript, we execute the following code: case ‘show-headers’ :

case ‘hide-headers’ : case ‘view-message’ : {

// if we have just picked a message from the list, or were looking at // a message and chose to hide or view headers, load a message

$fullheaders = ($action==’show-headers’);

display_message($auth_user, $selected_account, $messageid,

$fullheaders) break;

} You’ll notice that we’re checking the value of the $actionbeing equal to ‘show-headers’ In this case, it will be false, and $fullheaderswill be set equal to false We’ll look at the

‘show-headers’action in a moment

Ngày đăng: 06/07/2014, 19:20

TỪ KHÓA LIÊN QUAN