• Aucun résultat trouvé

Processing and acknowledging the message

Dans le document DAVID POWERS Y (Page 144-148)

?>

The file corefuncs.php contains the function nukeMagicQuotes(). To prevent errors if corefuncs.php can’t be accessed, the call to nukeMagicQuotes() is wrapped in a conditional statement using function_exists()as described in the last chapter.

5.Save contact.phpand click the Reloadbutton in your browser. Confirm that you want to resend the postdata. The $_POSTarray should now be clear of backslashes, as shown in Figure 5-4. You can check your code with contact03.php.

Figure 5-4. The nukeMagicQuotes()function cleans up the $_POSTarray ready for use in an email.

Processing and acknowledging the message

You can now build the message body with the contents of the $_POSTarray and email it to your inbox. You also need some way of informing the user that the message has been sent or if there is a problem. Rather than redirect the user to a different page, the following PHP Solution displays the result on the same page. I’ve adopted this approach because an improved version later in the chapter redisplays the user’s input if any required fields are missing. Once the final version of the form is complete, you can redirect the user to a sep-arate acknowledgment page by adding only two lines of code.

Continue using the same files. Alternatively, use contact03.phpfrom the download files.

1.Now that you have finished testing the $_POSTarray, delete the following three lines of code that were used to display its contents (they’re just after the closing

</form>tag):

<pre>

<?php if ($_POST) {print_r($_POST);} ?>

</pre>

PHP Solution 5-2: Sending email from the feedback form

5

2.Add the code to process and send the email. It goes immediately before the clos-ing PHP tag of the code block above the DOCTYPE declaration. (If your remote server uses magic quotes, this means immediately after the code you entered in step 3 of PHP Solution 5-1.) The new code looks like this:

// process the email

if (array_key_exists('send', $_POST)) {

$to = 'me@example.com'; // use your own email address

$subject = 'Feedback from Japan Journey site';

This entire section of code is wrapped in an ifstatement, which uses the function array_key_exists(). If you refer to Figures 5-3 and 5-4, you’ll see that the last ele-ment in the $_POSTarray looks like this:

[send] => Send message

This is the nameattribute of the form’s submit button and the label shown on the button. You don’t normally need either of these as part of the email message, but passing the name of the submit button and $_POSTto array_key_exists()is a foolproof way of checking that a form has been submitted. When the page first loads, there’s no way that the submit button can have been clicked, so its name isn’t present in the $_POSTarray. As a result, array_key_exists('send', $_POST) equates to false, and everything inside the ifstatement is ignored. However, as soon as the button is clicked, the page reloads, array_key_exists('send',

$_POST)equates to true, and the email script is processed.

The code that does the processing consists of five stages. The first two lines assign your email address to $toand the subject line of the email to $subject.

The next section labeled “process the $_POSTvariables” reassigns $_POST['name'],

$_POST['email'], and $_POST['comments']to ordinary variables. This makes them easier to handle when you subject them to security checks or style the email later.

Next, you build the body of the email message, which must consist of a single string. By using double quotes, you can embed the variables in the string and use

\nto insert new line characters (see Table 3-4 in Chapter 3). Once the message

body is complete, it’s passed to the wordwrap()function, which takes two argu-ments: a string and an integer that sets the maximum length of each line. Although most mail systems will accept longer lines, it’s recommended to limit each line to 70 characters.

After the message has been built and formatted, the recipient’s address, the subject line, and the body of the message are passed to the mail()function. The function returns a Boolean value indicating whether it succeeded in passing the email to the MTA. So, it’s useful to capture that value as $mailSent. You can then use $mailSent to redirect the user to another page or change the contents of the current one.

3.For the time being, let’s keep everything in the same page, because the rest of the chapter will add further refinements to the basic script. Scroll down and insert the following code just after the page’s main heading (new code is highlighted in bold):

<h1>Contact us</h1>

<?php

if ($_POST && !$mailSent) {

?>

<p class="warning">Sorry, there was a problem sending your message.

Please try later.</p>

<?php }

elseif ($_POST && $mailSent) {

?>

<p><strong>Your message has been sent. Thank you for your feedback.

</strong></p>

<?php } ?>

<p>Ut enim ad minim veniam . . .</p>

This is a straightforward if... elseifconditional statement, but it may look odd if you’re not used to seeing scripts that mix XHTML with PHP logic. What’s happen-ing can be summarized like this:

<p>Ut enim ad minim veniam . . .</p>

As noted before, many developers mistakenly think that you need to use echoor printto display XHTML inside a PHP block. It’s more efficient to switch back to XHTML, except for very short pieces of code. Doing so avoids the need to worry about escaping quotes. Just make sure that you balance your opening and clos-ing braces correctly.

5

Both parts of the conditional statement check the Boolean values of $_POSTand

$mailSent. Although the $_POSTarray is always set, it doesn’t contain any values unless the form has been submitted. Since PHP treats an empty array as false(see

“The truth according to PHP” in Chapter 3), you can use $_POSTon its own to test whether a form has been submitted. So the code in both parts of this conditional statement is ignored when the page first loads.

If the form has been submitted, $_POSTequates to true, so the next condition is tested. The exclamation mark in front of $mailSentis the negative operator, mak-ing it the equivalent of not$mailSent. So, if the email hasn’t been sent, both parts of the test are true, and the XHTML containing the error message is displayed.

However, if $mailSentis true, the XHTML containing the acknowledgment is dis-played instead.

4.Save contact.phpand load it into a browser. Type something into each text field, and click Send message. If everything went well, you should see the following message:

Not long afterward, you should receive the content of your message as an email. If the email fails to arrive, test contact.phpon your remote server. Sometimes email sent from a local test environment is rejected by ISPs, particularly if the SMTP server requires a username and password each time you connect. If that happens, conduct all further tests that involve sending mail on your remote server.

5.The acknowledgment shown in the preceding screenshot is controlled by the if...

elseifconditional statement that you entered in step 3. To prove this, use the site menu to go to another page, and return to contact.php. (If you’re not using the full site, click inside the browser address bar and press Enter/Return. If you use the browser’s Reload button, select the option not to resend the post data.) The acknowledgment should disappear. Your page is becoming truly interactive.

6.The way to test the failure message is to disable the mail()function temporarily.

Comment out the mail()function and hard-code a falsevalue for $mailSentlike this:

// send it

$mailSent = false; // mail($to, $subject, $message);

7.Save contact.phpand try to send another message. This time you should see the failure message as shown in the following screenshot.

8.Again, navigate to a different page and return. The failure message disappears when you come back. Revert the code in step 6 to its original state, so that you can send email again. You can check your code against contact04.php in the download files.

The form contains only 3 input fields, but even if it had 30, the process is the same: extract the contents of each field from the $_POSTarray, and combine them into a single string.

Once you’ve built the message, simply pass the recipient’s address, subject, and message to the mail()function.

Although this is a good start, the feedback form needs a lot of improvement. There’s noth-ing to stop users from sendnoth-ing a blank email. You also need to check the validity of input to make sure that your site isn’t exploited by a spam relay. The rest of the chapter shows you how to make these improvements, plus how to use other form elements: drop-down menus, radio buttons, and check boxes.

Dans le document DAVID POWERS Y (Page 144-148)