Working with Forms, Sessions, and Cookies

CHAPTER 8 Working with Forms, Sessions, and Cookies IN THIS CHAPTER: 8.1 Generating Forms 8.2 Processing Form Input 8.3 Combining a Form and Its Res...
Author: Michael Watkins
7 downloads 0 Views 256KB Size
CHAPTER

8

Working with Forms, Sessions, and Cookies IN THIS CHAPTER: 8.1 Generating Forms 8.2 Processing Form Input 8.3 Combining a Form and Its Result Page 8.4 Creating Drop-Down Lists 8.5 Creating Dependent Drop-Down Lists 8.6 Validating Form Input 8.7 Validating Numbers 8.8 Validating Alphabetic Strings 8.9 Validating Alphanumeric Strings 8.10 Validating Credit Card Numbers 8.11 Validating Telephone Numbers 8.12 Validating Social Security Numbers 8.13 Validating Postal Codes 8.14 Validating E-mail Addresses 8.15 Validating URLs 8.16 Uploading Files Through Forms 8.17 Preserving User Input Across Form Pages

8.18 Protecting Form Submissions with a CAPTCHA 8.19 Storing and Retrieving Session Data 8.20 Deleting Session Data 8.21 Serializing Session Data 8.22 Sharing Session Data 8.23 Storing Objects in a Session 8.24 Storing Sessions in a Database 8.25 Creating a Session-Based Shopping Cart 8.26 Creating a Session-Based User Authentication System 8.27 Protecting Data with Sessions 8.28 Storing and Retrieving Cookies 8.29 Deleting Cookies 8.30 Bypassing Protocol Restrictions on Session and Cookie Headers 8.31 Building GET Query Strings 8.32 Extracting Variables from a URL Path

291

292

PHP Programming Solutions

O

ne of the most critical things you can do to ensure the stability of your Web application is to verify the input it receives through online forms. This might seem trivial, but a failure to build in basic input validation routines can snowball into serious problems, such as data corruption or inconsistent calculations. With this in mind, a good part of this chapter focuses on forms and input validation: processing form input; validating e-mail addresses, URLs, and credit card numbers; uploading files through forms; preserving data across multipage forms; and dynamically generating form elements. That’s not all, though—unlike many other languages, PHP comes with native session and cookie management support, making it possible to track individual client sessions on a Web site and create highly customized Web pages. This chapter explores these features, discussing how to store and retrieve session variables; set and delete cookies; customize how session data is stored; authenticate users and protect pages from unauthorized access; build a session-based shopping cart; and create persistent objects.

NOTE You’ll find the SQL code needed to create the database tables in this chapter in the code archive for this book, at http://www.php-programming-solutions.com .

8.1 Generating Forms Problem You want to generate an HTML form using PHP method calls.

Solution Use PEAR’s HTML_QuickForm class:

Comments PEAR’s HTML_QuickForm class, available from http://pear.php.net/ package/HTML_QuickForm, is a sophisticated PHP class designed for on-the-fly form generation. Once an object of the class has been initialized, you can use the addElement() method to create and attach different types of input elements to the form. Typically, between three and four arguments are passed to addElement(): the element type, the element name, the element label (or value), and an optional array of additional attributes or information. Once the elements have been created, the display() method renders the form in HTML. Figure 8-1 illustrates the output of this listing.

293

294

PHP Programming Solutions

A Web form

Figure 8-1

See more examples of HTML_QuickForm in the listings in “8-5: Creating Dependent Drop-Down Lists,” “8-6: Validating Form Input,” “8-16: Uploading Files Through Forms,” and “8-17: Preserving User Input Across Form Pages.”

TIP In addition to the standard form input types, the HTML_QuickForm class also provides some custom built-ins for linking and grouping form elements. Read more about this at http:// pear.php.net/package/HTML_QuickForm, or look at an example in the listing in “8-5 Creating Dependent Drop-Down Lists.”

8.2 Processing Form Input Problem You want to use the data submitted in a form.

Chapter 8: Working with Forms, Sessions, and Cookies

Solution Access the data through the $_POST or $_GET arrays:

Comments Whenever a form is submitted to a PHP script, all variable-value pairs within that form automatically become available for use within the script through one of two associative arrays: $_POST or $_GET. It’s easy to iterate through these arrays and retrieve the submitted values, or even access specific values by key.

NOTE Remember that data submitted through a form may not necessarily be valid, and it must be checked before it can be saved or used in a calculation. The listing in “8.6: Validating Form Input” discusses how you may do this.

TIP To quickly view data submitted in a form, use the print_r() function with the $_POST and $_GET arrays, like this:

8.3 Combining a Form and Its Result Page Problem You want to use a single PHP script for both a form and its result page.

295

296

PHP Programming Solutions

Solution Use the presence or absence of the form element to decide whether to display the form or its result page: Color:

297

298

PHP Programming Solutions

Comments To dynamically generate a drop-down option list in a form, store the options in an array and use PHP’s foreach() loop to iterate through the array and print HTML elements corresponding to its contents. If you prefer to do this using pure PHP instead of a mixture of HTML code and PHP functions calls, use PEAR’s HTML_QuickForm class, available from http:// pear.php.net/package/HTML_QuickForm. This class enables you to add a drop-down list with the addElement() method, and specify the list items as an input argument to the method. Take a look:

To create drop-down lists that dynamically change their contents on selection, see the listing in “8.5: Creating Dependent Drop-Down Lists.”

8.5 Creating Dependent Drop-Down Lists Problem You want to create a series of dependent drop-down lists, such that a choice in one alters the available choices in another.

Chapter 8: Working with Forms, Sessions, and Cookies

Solution Use PEAR’s HTML_QuickForm class:

299

300

PHP Programming Solutions

Comments PEAR’s HTML_QuickForm class, available from http://pear.php.net/ package/HTML_QuickForm, comes with a special built-in element, hierselect, which is designed specifically to create dependent drop-down lists in forms. Here, the item choices for both primary and secondary drop-down lists are stored in arrays, with the index numbers of the primary array serving as keys to the corresponding items in the multidimensional secondary array. The setMainOptions() and setSecOptions() methods are used to link the arrays to the object. The display() method renders the form, together with the client-side code necessary to change the contents of the secondary drop-down list once a selection is made from the primary one.

8.6 Validating Form Input Problem You want to validate the data submitted in a form.

Solution Check the submitted data using either built-in or custom data validation routines, and only proceed to use it if it’s valid: