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

Học php, mysql và javascript p 28

10 231 0

Đ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 1,76 MB

Nội dung

CHAPTER 11 Form Handling The main way that website users interact with PHP and MySQL is through the use of HTML forms These were introduced very early on in the development of the World Wide Web in 1993—even before the advent of e-commerce—and have remained a mainstay ever since, due to their simplicity and ease of use Of course, enhancements have been made over the years to add extra functionality to HTML form handling, so this chapter will bring you up to speed on state-of-the-art form handling and show you the best ways to implement forms for good usability and security Building Forms Handling forms is a multipart process First, a form is created into which a user can enter the required details This data is then sent to the web server, where it is interpreted, often with some error checking If the PHP code identifies one or more fields that require reentering, the form may be redisplayed with an error message When the code is satisfied with the accuracy of the input, it takes some action that usually involves the database, such as entering details about a purchase To build a form, you must have at least the following elements: • • • • An opening and closing tag A submission type specifying either a get or post method One or more input fields The destination URL to which the form data is to be submitted Example 11-1 shows a very simple form created using PHP Type it in and save it as formtest.php 251 Example 11-1 formtest.php—a simple PHP form handler The first thing to notice about this example is that, as you have already seen in this book, rather than dropping in and out of PHP code, the echo Retrieving Submitted Data | 253 The only changes are a couple of lines at the start that check the $_POST associative array for the field name having been submitted The previous chapter introduced the $_POST associative array, which contains an element for each field in an HTML form In Example 11-2, the input name used was name and the form method was post, so element name of the $_POST array contains the value in $_POST['name'] The PHP isset function is used to test whether $_POST['name'] has been assigned a value If nothing was posted, the program assigns the value “(Not entered)”; otherwise, it stores the value that was entered Then a single line has been added after the statement to display that value, which is stored in $name register_globals: An Old Solution Hangs On Before security became such a big issue, the default behavior of PHP was to assign the $_POST and $_GET arrays directly to PHP variables For example, there would be no need to use the instruction $name=$_POST['name']; because $name would already be given that value automatically by PHP at the program start! Initially (prior to version 4.2.0 of PHP), this seemed a very useful idea that saved a lot of extra code-writing, but this practice has now been discontinued and the feature is disabled by default Should you find register_globals enabled on a production web server for which you are developing, you should urgently ask your server administrator to disable it So why disable register_globals? It enables anyone to enter a GET input on the tail of a URL, like this: http://myserver.com?override=1, and if your code were ever to use the variable $override and you forgot to initialize it (for example, through $override=0;), the program could be compromised by such an exploit In fact, because many installations on the Web remain with this gaping hole, I advise you to always initialize every variable you use, just in case your code will ever run on such a system Initialization is also good programming practice, because you can comment each initialization to remind yourself and other programmers what a variable is for If you ever find yourself maintaining code that seems to assume values for certain variables for no apparent reason, you can make an educated guess that the programmer wrote the code using register_globals, and that these values are intended to be extracted from a POST or GET If so, I recommend you rewrite the code to load these variables explicitly from the correct $_POST or $_GET array Default Values Sometimes it’s convenient to offer your site visitors a default value in a web form For example, suppose you put up a loan repayment calculator widget on a real estate 254 | Chapter 11: Form Handling Figure 11-3 Using default values for selected form fields website It could make sense to enter default values of, say, 25 years and percent interest, so that the user can simply type in either the principal sum to borrow or the amount that he or she can afford to pay each month In this case, the HTML for those two values would be something like Example 11-3 Example 11-3 Setting default values Loan Amount Monthly Repayment Number of Years Interest Rate If you wish to try this (and the other HTML code samples) out, type it in and save it with a html file extension, such as test.html, then load that file into your browser Take a look at the third and fourth inputs By populating the value parameter, you display a default value in the field, which the users can then change if they wish With sensible default values you can often make your web forms more user-friendly by minimizing unnecessary typing The result of the previous code looks like Figure 11-3 Of course, this was created just to illustrate default values and, because the program calc.php has not been written, the form will not anything if submitted Default values are also used for hidden fields if you want to pass extra information from your web page to your program, in addition to what users enter We’ll look at hidden fields later in this chapter Retrieving Submitted Data | 255 Input Types HTML forms are very versatile and allow you to submit a wide range of different types of inputs ranging from text boxes and text areas to checkboxes, radio buttons, and more Text Boxes Probably the type of input you will most often use is the text box It accepts a wide range of alphanumeric text and other characters in a single-line box The general format of a text box input is: We’ve already covered the name and value parameters, but two more are introduced here: size and maxlength The size parameter specifies the width of the box, in characters of the current font, as it should appear on the screen, and maxlength specifies the maximum number of characters that a user is allowed to enter into the field The only required parameters are type, which tells the web browser what type of input is to be expected, and name, for providing a name to the input that is then used to process the field upon receipt of the submitted form Text Areas When you need to accept input of more than a short line of text, use a text area This is similar to a text box but, because it allows multiple lines, it has some different parameters Its general format looks like this: The first thing to notice is that has its own tag and is not a subtype of the input tag It therefore requires a closing to end input Instead of a default parameter, if you have default text to display, you must put it before the closing , and it will then be displayed and be editable by the user, like this: This is some default text To control the width and height, use the cols and rows parameters Both use the character spacing of the current font to determine the size of the area If you omit these values, a default input box will be created that will vary in dimensions depending on the browser used, so you should always define them to be certain about how your form will appear 256 | Chapter 11: Form Handling Lastly, you can control how the text entered into the box will wrap (and how any such wrapping will be sent to the server) using the wrap parameter Table 11-1 shows the wrap types available If you leave out the wrap parameter, soft wrapping is used Table 11-1 The wrap types available in a textarea input Type Action off Text does not wrap and lines appear exactly as the user types them soft Text wraps but is sent to the server as one long string without carriage returns and line feeds hard Text wraps and is sent to the server in wrapped format with soft returns and line feeds Checkboxes When you want to offer a number of different options to a user, from which he or she can select one or more items, checkboxes are the way to go The format to use is: If you include the checked parameter, the box is already checked when the browser is displayed (the string you assign to the parameter doesn’t matter; the parameter just has to be present) If you don’t include the parameter, the box is shown unchecked Here is an example of an unchecked box: I Agree If the user doesn’t check the box, no value will be submitted But if they do, a value of “on” will be submitted for the field named agree If you prefer to have your own value submitted instead of the word “on” (such as the number 1), you could use the following syntax: I Agree On the other hand, if you wish to offer a newsletter to your readers when submitting a form, you might want to have the checkbox already checked as the default value: Subscribe? If you want to allow groups of items to be selected at one time, assign them all the same name However, only the last item checked will be submitted, unless you pass an array as the name For example, Example 11-4 allows the user to select his favorite ice creams (see Figure 11-4 for how it displays in a browser) Example 11-4 Offering multiple checkbox choices Vanilla Chocolate Strawberry If only one of the checkboxes is selected, such as the second one, only that item will be submitted (the field named ice would be assigned the value “Chocolate”) But if two Retrieving Submitted Data | 257 Figure 11-4 Using checkboxes to make quick selections or more are selected, only the last value will be submitted, with prior values being ignored If you want exclusive behavior—so that only one item can be submitted—then you should use radio buttons (see the next section), but to allow multiple submissions, you have to slightly alter the HTML, as in Example 11-5 (note the addition of the square brackets, [], following the values of ice): Example 11-5 Submitting multiple values with an array Vanilla Chocolate Strawberry Now, when the form is submitted, if any of these items have been checked, an array called ice will be submitted that contains any and all values In each case, you can extract either the single submitted value, or the array of values, to a variable like this: $ice = $_POST['ice']; If the field ice has been posted as a single value, $ice will be a single string, such as “Strawberry” But if ice was defined in the form as an array (like Example 11-5), $ice will be an array, and its number of elements will be the number of values submitted Table 11-2 shows the seven possible sets of values that could be submitted by this HTML for one, two, or all three selections In each case, an array of one, two, or three items is created Table 11-2 The seven possible sets of values for the array $ice One value submitted Two values submitted Three values submitted $ice[0] => Vanilla $ice[0] => Vanilla $ice[0] => Vanilla $ice[0] => Chocolate $ice[1] => Chocolate $ice[1] => Chocolate $ice[0] => Strawberry $ice[2] => Strawberry $ice[0] => Vanilla $ice[1] => Strawberry 258 | Chapter 11: Form Handling One value submitted Two values submitted Three values submitted $ice[0] => Chocolate $ice[1] => Strawberry If $ice is an array, the PHP code to display its contents is quite simple and might look like this: foreach($ice as $item) echo "$item"; This uses the standard PHP foreach construct to iterate through the array $ice and pass each element’s value into the variable $item, which is then displayed using the echo command The is just an HTML formatting device, to force a new line after each flavor in the display By default, checkboxes are square Radio Buttons Radio buttons are named after the push-in preset buttons found on many older radios, where any previously depressed button pops back up when another is pressed They are used when you want only a single value to be returned from a selection of two or more options All the buttons in a group must use the same name and, because only a single value is returned, you not have to pass an array For example, if your website offers a choice of delivery times for items purchased from your store, you might use HTML like that in Example 11-6 (see Figure 11-5 to see how it displays) Figure 11-5 Selecting a single value with radio buttons Example 11-6 Using radio buttons 8am-Noon| Noon-4pm| 4pm-8pm Retrieving Submitted Data | 259 Here the second option of Noon-4pm has been selected by default This default choice ensures that at least one delivery time will be chosen by the users, which they can change to one of the other two options if they prefer Had one of the items not been already checked, the user might forget to select an option and no value would be submitted at all for the delivery time By default, radio buttons are round Hidden Fields Sometimes it is convenient to have hidden form fields so that you can keep track of the state of form entry For example, you might wish to know whether a form has already been submitted You can achieve this by adding some HTML in your PHP code, such as the following: echo '' This is a simple PHP echo statement that adds an input field to the HTML form Let’s assume the form was created outside the program and displayed to the user The first time the PHP program receives the input, this line of code has not run, so there will be no field named submitted The PHP program recreates the form, adding the input field So when the visitor resubmits the form, the PHP program receives it with the submitted field set to “yes” The code can simply check whether the field is present: if (isset($_POST['submitted'])) { Hidden fields can also be useful for storing other details, such as a session ID string that you might create to identify a user, and so on Never treat hidden fields as secure—because they are not The HTML containing them can easily be viewed using a browser’s View Source feature Select The select tag lets you create a drop-down list of options, offering either single or multiple selections It conforms to the following syntax: The parameter size is the number of lines to display Clicking on the display causes a list to drop down showing all the options If you use the multiple parameter, multiple options can be selected from the list by pressing the Ctrl key when clicking So to ask a user for her favorite vegetable from a choice of five, you might use HTML as in Example 11-7, which offers a single selection 260 | Chapter 11: Form Handling ...Example 11-1 formtest.php—a simple PHP form handler

Ngày đăng: 03/12/2015, 14:21

w