In the previous section, you created two separate files. One file contained the front-end (form), and the other contained the back-end (script). In this section, you earn how to use the $_SERVER[PHP_SELF] variable in a form action to create a single file that holds both form and script, and how to create custom error messages when required fields are not completed.
As you did earlier in this chapter, the first step in creating a form/script pair is to create the front-end form. However, in this all-in-one form, the front-end form is simply the first half of the script and not a separate file.
Open a new file in your text editor.
Type the following HTML:
<HTML> <HEAD> <TITLE>All-In-One Feedback Form</TITLE> </HEAD> <BODY>
Start a PHP block, and then create a variable called $form_block, which will hold he entire form. Start with the form action, and assume that the method is POST and the action is $_SERVER[PHP_SELF]:
<? $form_block = " <FORM METHOD=\"POST\" ACTION=\"$_SERVER[PHP_SELF]\">
| Note |
Because you're putting a long string inside a variable, chances are good that ou'll have a quotation mark or two. Remember to escape all your quotation arks with a backslash! |
Create an input field for the user's name with a text label:
<P><strong>Your Name:</strong><br> <INPUT type=\"text\" NAME=\"sender_name\" SIZE=30></P>
Create an input field for the user's e-mail address with a text label:
Create a text area to hold the message with a text label:
<P><strong>Message:</strong><br> <TEXTAREA NAME=\"message\" COLS=30 ROWS=5 WRAP=virtual></TEXTAREA></P>
Add a submit button:
<P><INPUT TYPE=\"submit\" NAME=\"submit\" VALUE=\"Send This Form\"></P>
Close the form, and then add the ending quotation marks and instruction erminator (semicolon):
</FORM>";
Close the PHP block, and then add some more HTML so that the document is alid:
?> </BODY> </HTML>
Save the file with the name allinone_form.php.
If you looked at this code in our web browser, you'd only see a title in the title bar. The burning question should be, "Why do we need all that HTML in a variable called $form_block?" In the next section, you add to the script so that it displays particular chunks of code based on certain actions. The string in $form_block is one of those chunks.
The plan is to use the global variable $_SERVER[PHP_SELF], which has a value of the script's current name. So really, $_SERVER[PHP_SELF] will have a value of allinone_form.php in this instance. When you use $_SERVER[PHP_SELF] as a form action, you're saying, "When the submit button is clicked, reload this script and do something," instead of, "When the submit button is clicked, go find another script and do something."
Now that you have a shell of a script, think about what this all-in-one script must do:
Display the form
Submit the form
Check for errors
Print error messages without sending the form
Send the form if no errors are found
Make a few modifications to the script to help it determine which actions it should take. Inside the $form_block variable, before the HTML code for the submit button, add this line:
<INPUT type=\"hidden\" name=\"op\" value=\"ds\">
This line creates a hidden variable called $_POST[op], which has a value of ds. The "op" stands for "operation," and "ds" stands for "do something." I made these names up; they have nothing to do with any programming language. You can call them whatever you want, as long as you understand what they do (which you'll soon see).
The $_POST[op] variable is present only if the form has been submitted. So if the value of $_POST[op] is not ds, the user hasn't seen the form. If the user hasn't seen he form, you need to show it, so add the following if…else statement before the end of the PHP block:
You're not done yet, but your code should now look something like this:
You make a few more modifications in the next step, to add your error messages. If the form is submitted, the value of $_POST[op] will be ds, and now you must account for that. Assume that all the form fields are required; after checking for the value of $_POST[op], you check for a value in all the fields.
Continue the if…else statement:
else if ($_POST[op] ==
"ds") {
Add an if statement within the parent statement to check for values. Start with $_POST[sender_name]:
if ($_POST[sender_name] == "") {
Create an error message for $_POST[sender_name] called $name_err:
$name_err = "<font color=red>Please enter your name!</font><br>";
Set the value of $send to "no":
$send = "no";
Create a similar if statement for $_POST[sender_email]:
Create a similar if statement for $_POST[message]:
if ($_POST[message] == "") {
$message_err = "<font color=red>Please enter a message!</font><br>";
$send = "no";
}
Start an if…else statement to handle the value of $send:
if ($send != "no") {
// it's ok to send!
Create a variable to hold the recipient's e-mail address (substitute your own):
$to = "you@youremail.com";
Create a variable to hold the subject of the e-mail:
$subject = "All-in-One Web Site Feedback";
Create a variable to hold additional mail headers:
$mailheaders = "From: My Web Site <genericaddress@yourdomain.com> \n";
Add to the $mailheaders variable:
$mailheaders .= "Reply-To: $_POST[sender_email]\n";
Build the message string:
$msg = "E-MAIL SENT FROM WWW SITE\n"; $msg .= "Sender's Name: $_POST[sender_name]\n"; $msg .= "Sender's E-Mail: $_POST[sender_email]\n"; $msg .= "Message: $_POST[message]\n\n";
Add the mail() function:
mail($to, $subject, $msg, $mailheaders);
Add a simple statement to let the user know the mail has been sent, and lose the if statement:
Continue the if…else statement to deal with a value of "no" for $send:
else if ($send == "no") {
Print the error messages:
echo "$name_err"; echo "$email_err"; echo "$message_err";
Print the form again:
echo "$form_block";
Close the current if…else block and the parent if…else block:
}
}
Save the file.
The entire code should look something like this:
<HTML>
<HEAD>
<TITLE>All-In-One Feedback Form</TITLE>
</HEAD>
<BODY>
<?
$form_block = "
<FORM METHOD=\"POST\" ACTION=\"$PHP_SELF\">
<P><strong>Your Name:</strong><br>
<INPUT type=\"text\" NAME=\"sender_name\" SIZE=30></P>
<P><strong>Your E-Mail Address:</strong><br>
<INPUT type=\"text\" NAME=\"sender_email\" SIZE=30></P>
<P><strong>Message:</strong><br>
<TEXTAREA NAME=\"message\" COLS=30 ROWS=5 WRAP=virtual></TEXTAREA></P>
<INPUT type=\"hidden\" name=\"op\" value=\"ds\">
<P><INPUT TYPE=\"submit\" NAME=\"submit\" VALUE=\"Send This Form\"></p>
</FORM>";
if ($_POST[op] != "ds") {
// they need to see the form
echo "$form_block";
} else if ($_POST[op] == "ds") {
// check value of $_POST[sender_name]
if ($_POST[sender_name] == "") {
$name_err = "<font color=red>Please enter your name!</font><br>";
$send = "no";
}
// check value of $_POST[sender_email]
if ($_POST[sender_email] == "") {
$email_err = "<font color=red>Please enter your
e-mail address!</font><br>";
$send = "no";
}
// check value of $_POST[message]
if ($_POST[message]== "") {
$message_err = "<font color=red>Please enter a message!</font><br>";
$send = "no";
}
if ($send != "no") {
// it's ok to send, so build the mail
$msg = "E-MAIL SENT FROM WWW SITE\n";
$msg .= "Sender's Name: $_POST[sender_name]\n";
$msg .= "Sender's E-Mail: $_POST[sender_email]\n";
$msg .= "Message: $_POST[message]\n\n";
$to = "you@yourdomain.com";
$subject = "All-in-One Web Site Feedback";
$mailheaders = "From: My Web Site
<genericaddress@yourdomain.com>\n";
$mailheaders .= "Reply-To: $_POST[sender_email]\n";
//send the mail
mail($to, $subject, $msg, $mailheaders);
//display confirmation to user
echo "<P>Mail has been sent!</p>";
} else if ($send == "no") {
//print error messages
echo "$name_err";
echo "$email_err";
echo "$message_err";
echo "$form_block";
}
}
?>
Now that you've created both a front-end form and a back-end script, it's time to try them out.
Open your web browser and type http://127.0.0.1/allinone_form.php.
You will see a form containing a text field for the person's name, a text field for the person's e-mail address, a text area for the message, and a button that says Send This Form.
Submit the form without typing anything in any of the fields.
The form, with all three error messages at the top, will appear in your browser window.
Type your name in the Your Name field and then submit the form.
The form will reappear, this time without the name error message.
Type your name in the Your Name field and your e-mail address in the Your E-Mail Address field, and then submit the form.
The form will reappear again, this time with only the message error.
Type your name in the Your Name field, your e-mail address in the Your E-Mail Address field, and the following message:
This all-in-one thing is pretty cool!
Submit the form.
You will see a confirmation that our message has been sent.
One thing you probably noticed in the original script is that if you made an error, the form was reset and you lost the values you had entered. A simple modification to the original $form_block will take care of that problem. Just add a VALUE attribute to the form field to hold any previous value for the given variable.
Open allinone_form.php in your text editor.
Inside the $form_block variable, modify the input field for Your Name:
<INPUT type=\"text\" NAME=\"sender_name\" VALUE=\"$_POST[sender_name]\" SIZE=30></P>
Modify the input field for Your E-Mail Address:
Modify the text area for Message:
<TEXTAREA NAME=\"message\" COLS=30 ROWS=5 WRAP=virtual>$_POST[message]</TEXTAREA></P>
| Note |
There's no VALUE attribute for TEXTAREA. Instead, the value goes between the start and end tags. |
Save the file, and then open your web browser and type http://127.0.0.1/allinone_form.php.
Type your name in the Your Name field, and then submit the form.
The form, complete with error messages, will appear. This time, though, your name has been saved!
Repeat the process for the other fields in the form to verify that the values were saved. You've just mastered another aspect of dynamic content, this time in relation to displaying error messages when users don't perform the proper tasks, such as completing all of the fields in a form.
Whereas this chapter was all about forms and sending mail, the next chapter is all about working with elements of your file system, such as files and directories.