More Books
PHP 5 Unleashed
PHP 5 Unleashed
Table of Contents
Copyright
Lead Author
Contributing Authors
Acknowledgments
We Want to Hear from You!
Reader Services
Introduction
Organization of the Book
Part I. Working with PHP for General Web Development
Chapter 1. Basic PHP Development
How PHP Scripts Work
Basic PHP Syntax
Basic PHP Data Types
Variable Manipulation
Control Structures
User-Defined Functions
Dynamic Variables and Functions
Multiple File PHP Scripts
References
Strings in PHP
Comparing Strings
Advanced String Comparison
Search and Replacement
Formatting Strings
Strings and Locales
Formatting Date and Time Values
Summary
Chapter 2. Arrays
Basic Arrays
Implementing Arrays
More Array Materials
Chapter 3. Regular Expressions
The Basics of Regular Expressions
Limitations of the Basic Syntax
POSIX Regular Expressions
Perl-Compatible Regular Expressions (PCRE)
PCRE Modifiers
A Few Final Words
Chapter 4. Working with Forms in PHP
HTML Forms 101
Working with Form Submissions in PHP
Summary
Chapter 5. Advanced Form Techniques
Data Manipulation and Conversion
Form Data Integrity
Form Processing
Summary
Chapter 6. Persistent Data Using Sessions and Cookies
HTTP Cookies
PHP Sessions
Advanced Sessions
Summary
Chapter 7. Using Templates
The What and Why of Templates
The Smarty Template Engine
Summary
Part II. Advanced Web Development
Chapter 8. PEAR
What Is PEAR?
Getting and Installing PEAR
Using the PEAR Package Manager
Using the PEAR Website
Using PEAR Packages in Applications
Summary
Reference
Chapter 9. XSLT and Other XML Concerns
Relating XML to HTML
Using XSLT to Describe HTML Output Using XML Input
PHP4 and XSLT Using the DOM XML Module
PHP4 and XSLT Using the XSLT Module
PHP5 and XSLT
Accessing XML Data Using SimpleXML
Generating XML Documents Using PHP
Summary
References
Chapter 10. Debugging and Optimizations
Debugging Your PHP Scripts
Optimizing Your PHP Scripts
Summary
Chapter 11. User Authentication
Authenticating Users in PHP
Securing PHP Code
Summary
Chapter 12. Data Encryption
Shared Secret Versus Public Key
Shared Secret Algorithms
Public Key Cryptography
Using Public Keys in PHP
Summary
Chapter 13. Object-Oriented Programming in PHP
Why Objects?
Creating Basic Classes
Advanced Classes
Special Methods
Class Autoloading
Object Serialization
Exceptions
Iterators
Summary
Chapter 14. Error Handling
The PHP Error-Handling Model
What to Do About Errors
The Default Error Handler
Error Suppression
Custom Error Handlers
Causing Errors
Putting It All Together
Summary
Chapter 15. Working with HTML/XHTML Using Tidy
Introduction
Basic Tidy Usage
Tidy Configuration Options
Using the Tidy Parser
Applications of Tidy
Summary
Chapter 16. Writing Email in PHP
The MIME Protocol
Implementing MIME Email in PHP
Summary
Part III. Building Applications in PHP
Chapter 17. Using PHP for Console Scripting
Core CLI Differences
Working with PHP CLI
CLI Tools and Extensions
Summary
Chapter 18. SOAP and PHP
What Are Web Services?
Installation
Creating Web Services
Consuming Web Services
Looking for Web Services
Summary
Chapter 19. Building WAP-Enabled Websites
What Is WAP?
System Requirements
Introduction to WML
Serving WAP Content
Sample Applications
Summary
Part IV. I/O, System Calls, and PHP
Chapter 20. Working with the File System
Working with Files in PHP
File Permissions
File Access Support Functions
Summary
Chapter 21. Network I/O
DNS/Reverse DNS Lookups
Socket Programming
Network Helper Functions
Summary
Chapter 22. Accessing the Underlying OS from PHP
Introduction
Unix-Specific OS Functionality
Platform-Independent System Functions
A Brief Note About Security
Summary
Part V. Working with Data in PHP
Chapter 23. Introduction to Databases
Using the MySQL Client
Basic MySQL Usage
Summary
Chapter 24. Using MySQL with PHP
Performing Queries from PHP
A MySQLi Session Handler
What Is a Custom Session Handler?
Summary
Chapter 25. Using SQLite with PHP
What Makes SQLite Unique?
Basic SQLite Functionality
Working with PHP UDFs in SQLite
Odds and Ends
Summary
Chapter 26. PHP's dba Functions
Preparations and Settings
Creating a File-Based Database
Writing Data
Reading Data
Sample Application
Conclusion
Part VI. Graphical Output with PHP
Chapter 27. Working with Images
Basic Image Creation Using GD
Using the PHP/GD Drawing Functions
Working with Colors and Brushes
Using Fonts and Printing Strings
General Image Manipulation
Other Graphics Functions
Summary
Chapter 28. Printable Document Generation
A Note Regarding the Examples in This Chapter
Generating Dynamic RTF Documents
Generating Dynamic PDF Documents
Related Resources
Part VII. Appendixes
Appendix A. Installing PHP5 and MySQL
Installing PHP5
Installing MySQL and PHP Modules
Installing PEAR
Appendix B. HTTP Reference
What Is HTTP?
PHP Programming Libraries for HTTP Work
Understanding an HTTP Transaction
HTTP Client Methods
What Comes Back: Server Response Codes
HTTP Headers
Encoding
Identifying Clients and Servers
The "Referer"
Fetching Content from an HTTP Source
Media Types
Cookies: Preserving State and a Tasty Treat
Security and Authorization
Client-Side Caching of HTTP Content
Appendix C. Migrating Applications from PHP4 to PHP5
Configuration
Object-Oriented Programming (OOP)
New Behavior of Functions
Further Reading
Appendix D. Good Programming Techniques and Performance Issues
Common Style Mistakes
Common Security Concerns
Style and SecurityLogging
Summary
Appendix E. Resources and Mailing Lists
Relevant Websites
Mailing Lists and Newsgroups
Index
SYMBOL
A
B
C
D
E
F
G
H
I
J
K
L
M
N
O
P
Q
R
S
T
U
V
W
X
Y
Z

HTML Forms 101

As I mentioned in the introduction to this chapter, this section is devoted to the basics of HTML forms and thus only indirectly relates to PHP. If you are an HTML guru (or at least believe you know enough about HTML forms), feel free to skip this section.

How Forms Are Created

When you're creating a form in HTML, the first thing needed is a <FORM> HTML tag. This tag serves to define the section of the HTML document that contains all the "widgets" that define the form. These widgets are things such as text fields, check boxes, option buttons, and so on. The <FORM> tag itself has a number of attributes associated with it that define its behavior when the form is submitted. These attributes are described in Table 4.1:

Table 4.1. <FORM> Tag Attributes

ACTION

The URL that the form is submitted to

METHOD

The method under which the form is submitted (GET OR POST)

ENCTYPE

The encoding type to use


NOTE

The list of attributes in Table 4.1 is incomplete. As will be the case with the remainder of this chapter, only those attributes that bear relevance to PHP will be discussed.


Although all three of the preceding attributes can be used, none are required. The first attribute, ACTION, represents the URL that will accept the form submission (your PHP script, for example). If the ACTION attribute is omitted, the default behavior is to submit the form back to the same URL that defined the form. The second attribute, METHOD, defines under what HTTP method the form will be submitted to the URL defined in the ACTION attribute. The two possible options for the METHOD attribute are GET or POST. In most cases (although it is client specific) the default value for METHOD is to use GET. The third attribute listed in Table 4.1 is the ENCTYPE attribute. This attribute is used to change the way the client browser sends the form submission to the designated URL. Unless you are dealing with special cases such as file uploading, the ENCTYPE attribute is rarely included in any <FORM> tag and can be safely ignored.

When a <FORM> tag is placed in an HTML document, the only change to the layout of the document is the creation of a new paragraph (similar to the <P> HTML tag). To have the form actually serve its purpose and receive input from the user, you'll need to include the appropriate HTML tags for the form widgets.

HTML Widgets

HTML widgets (at least in our discussion of forms) relate to things such as text fields, check boxes, and so on, which can be displayed to the user to receive input. Because this chapter isn't devoted to HTML, only a brief discussion of each will be presented.

Text and Password Field Widgets

The first widget that I will introduce is the text field widget. This widget is simply a single-line input field and is defined by the <INPUT> tag and by setting the TYPE attribute to TEXT. Table 4.2 is a list of valid tags for a text field and their meanings:

Listing 4.1. Creating a Text Field in HTML
<INPUT TYPE="TEXT" 
       NAME="mytextfield"
       VALUE="My Default Value" 
       SIZE=30 
       MAXLENGTH=30>

Table 4.2. Text Field Attributes

NAME

The name assigned to a text field

SIZE

The size of the text field in the browser in characters

MAXLENGTH

The maximum number of characters to accept in the text field

VALUE

The default value of the text field


Similar to a text field, the password field enables you to create the same single-line input. However, unlike the text field I just discussed, the password field masks the input so that it cannot be read on the screen. To create a password field, set the TYPE attribute of an <INPUT> tag to PASSWORD. Because the text field and password field accept an identical set of attributes, refer to Table 4.2 for a listing of valid password field attributes. Following is an example of a password field in use:

Listing 4.2. Creating a Password Field in HTML
<INPUT TYPE="password" 
       NAME="mypassword"
       VALUE="You cannot read this on the browser">

Option Button and Check Box Widgets

One method that exists for allowing users to choose a single item from a list of options is the option button. In HTML, the option button can be created by setting the TYPE attribute of an <INPUT> tag to RADIO. An option widget allows for only three attributes: NAME, VALUE, and CHECKED. When working with option buttons, note the following:

  • For a group of option buttons to function properly and function as a group (meaning only one can be selected), every option button in that group must have the same value for the NAME attribute.

  • The CHECKED attribute is not assigned a value, and only one CHECKED attribute can exist for each option button group (see Listing 4.3).

Also note that the VALUE attribute is not displayed in the browser, but instead will be the value submitted when the form is submitted. In Listing 4.3, the option button is used to allow users to select their favorite sport:

Listing 4.3. Creating an Option Button Group in HTML
<INPUT TYPE="radio" NAME="myradio" CHECKED VALUE="1"> Football<BR>
<INPUT TYPE="radio" NAME="myradio" VALUE="2"> Soccer<BR>
<INPUT TYPE="radio" NAME="myradio" VALUE="3"> Hockey<BR>
<INPUT TYPE="radio" NAME="myradio" VALUE="4"> Baseball<BR>

Similar to the option button, a check box enables the user to select any number of the provided options. A check box is created by setting the TYPE attribute of an <INPUT> tag to CHECKBOX. Unlike an option button, it is not required that each check box have the same name, nor is there a restriction on how many CHECKED attributes can exist. Check boxes do, however, have the same attributes as an option button (NAME, VALUE, and CHECKED). In Listing 4.4, we use the check box to enable users to select what sports they tend to watch on TV:

NOTE

Not only are you not required to set the name of multiple check boxes to the same name as was the case with option buttons, doing so is strongly discouraged. Check boxes should always be named uniquely to avoid potentially difficult-to-find bugs.


Listing 4.4. Creating Check Boxes in HTML
<INPUT TYPE="checkbox" NAME="mycheckbox1" CHECKED VALUE="1"> Football<BR>
<INPUT TYPE="checkbox" NAME="mycheckbox2" VALUE="2"> Soccer<BR>
<INPUT TYPE="checkbox" NAME="mycheckbox3" CHECKED VALUE="3"> Hockey<BR>
<INPUT TYPE="checkbox" NAME="mycheckbox4" VALUE="4"> Baseball<BR>

File Upload Widget

The next widget that I will review is the file upload widget. This widget provides the means to allow the client browser to browse the local file system and select a file to upload to the Web server. The complete details of how this widget must be used for it to work properly will be discussed later in the chapter in the "Handling File Uploads" section. To create a file upload widget, set the TYPE attribute of an <INPUT> tag to FILE. The possible attributes for a file widget can be found in Table 4.3:

Table 4.3. File Widget Attributes

NAME

The name of the file widget

SIZE

The size of the file widget text field (in characters)

MAXLENGTH

The maximum length of the text field

ACCEPT

The MIME type accepted by the field widget


Listing 4.5 illustrates the use of the file widget allowing the user to upload only files with a MIME type of "image/*" (meaning only images):

Listing 4.5. Using the HTML File Widget
<INPUT TYPE="file" NAME="myfile" ACCEPT="image/*">

Lists and Drop-Down Lists

When you're constructing a form, HTML provides a number of ways to select item(s) from a list. A list can be represented as a single line where the user clicks an arrow to see all the choices (dropdown list), or it can be a standard scrollable list where one (or more) items can be selected. All this functionality is provided by two tags: <SELECT>, which defines a list (much like <FORM> defines a form) and <OPTION>, which is used to represent an item in the list. Tables 4.4 and 4.5 describe the valid attributes for the <SELECT> and <OPTION> tags, respectively:

Table 4.4. Attributes of the <SELECT> Tag

NAME

The name given to the list

SIZE

The number of items to display at once in the list (a value of one indicates a drop-down list)

MULTIPLE

A flag indicating whether multiple items can be selected


Table 4.5. Attributes of the <OPTION> Tag

VALUE

The value to submit if the item is selected

SELECTED

A flag indicating if this item is selected by default


NOTE

Drop-down lists cannot use the MULTIPLE attribute.


In Listing 4.6, two lists are created. The first list is a drop-down list enabling users to select their favorite color, and the second list allows them to pick one or more of their favorite foods:

Listing 4.6. Using HTML Lists
<SELECT NAME="colors" SIZE=1>
<OPTION VALUE="red">I like Red</OPTION>
<OPTION VALUE="blue">I like Blue</OPTION>
<OPTION VALUE="green">I like Green</OPTION>
</SELECT><BR><BR>
<SELECT NAME="foods" SIZE=4 MULTIPLE>
<OPTION VALUE="Chinese">I like Chinese food</OPTION>
<OPTION VALUE="Mexican">I like Mexican food</OPTION>
<OPTION VALUE="American">I like American food</OPTION>
<OPTION VALUE="Italian">I like Italian food</OPTION>
<OPTION VALUE="none">I don't like any of these foods</OPTION>
</SELECT>

Multiple-Line Text Fields

You have already been introduced to the text field at the beginning of this section. However, recall that the text field widget I discussed allows the user to enter only a single line of text. To allow the user to enter multiple lines of text, you'll have to use the <TEXTAREA> widget. The attributes for this widget are shown in Table 4.6:

Table 4.6. Attributes for the HTML <TEXTAREA> Widget

NAME

The name of the widget

COLS

The number of columns wide (in characters) of the text field

ROWS

The number of rows long (in characters) of the text field

WRAP

Determines how the text should be submitted in relation to how it was typed in the text field


Although the attributes COLS and ROWS and NAME are all fairly self-explanatory, the WRAP attribute requires a bit of explanation. The WRAP attribute accepts one of the following values: off, soft, and hard. These values determine how the text will be sent in relation to how it is typed. When off is specified, this indicates that the text field will not wrap at all (it will run past the edge of the text field) and the text will be sent exactly as typed. Soft wrapping means that the text will wrap to the text field; however, it will still be sent exactly as typed. The final option, hard, indicates that the text will wrap to the text field and the submission will likewise contain a newline character at every wrapping point.

Unlike all the other HTML widgets discussed, the <TEXTAREA> widget must be accompanied by a corresponding closing </TEXTAREA> tag. Any default value for the text area should be enclosed between these two tags. In Listing 4.7, a text area is created with the default text This is my text area:

Listing 4.7. Using the Text Area HTML Widget
<TEXTAREA ROWS="5" COLS="30" WRAP="hard">This is my text area</TEXTAREA>

Hidden Form Values

HTML forms, beyond providing a means for the user to input data to be sent to the server, also allow for uneditable data to be sent. This is done using hidden form values. These values are created using the <INPUT> tag and setting the TYPE attribute to HIDDEN. Unlike all the other widgets discussed in this section, the hidden widget (as its name implies) is never displayed on the client browserit is only sent along with the form submission. Use of hidden form elements is very common when working with scripts (as you will see later in this chapter and throughout the book). The attributes for the hidden widget are NAME and VALUE, representing the name of the hidden form element and its value, respectively.

This is illustrated in Listing 4.8 in which a hidden form widget named myvalue is assigned the value foo:

Listing 4.8. Using Hidden Form Elements in HTML
<INPUT TYPE="HIDDEN" NAME="myvalue" VALUE="foo">

Submission Widgets and Button Widgets

The final type of widget that I will be discussing is the button/submission widget. These widgets all are represented by the <INPUT> tag and use the values SUBMIT, IMAGE, and BUTTON for the TYPE attribute. Because both the SUBMIT and IMAGE widgets behave in a similar fashion, I will discuss them first.

As I have already mentioned, for any form data to be sent from the client browser to the server, it must be "submitted." To facilitate this, there are two HTML form widgets that will trigger a submission (when clicked). The first of these is the submission widget, which is a button that uses two attributes: NAME and VALUE. Unless there is a need to identify which submission button was clicked in your scripts, the NAME attribute can be omitted. On the other hand, the VALUE attribute will be used as the action displayed on the button (for example, Submit this form) and is recommended.

The second submission widget is the image widget. This widget behaves identically to the standard submission element described previously; however, instead of displaying a button it displays the specified image. When using this form of the submission widget, all the attributes available to the HTML image tag <IMG> are available. Both of these submission widgets are demonstrated in Listing 4.9:

Listing 4.9. Using the Submit and Image HTML Widgets
<INPUT TYPE="submit" 
       VALUE="This is the Default Submit Button" 
       NAME="mysubmit">
<INPUT TYPE="image" 
       src="/images/mybutton.gif" 
       NAME="myimagesubmit">

The final HTML widget is the button widget. This widget, by itself, looks and functions in the same way as the default submission widget just discussed. However, unlike the widget, the button widget has no default action associated with it. Rather, it must be coupled with a client-side scripting language such as JavaScript to perform any action. Because the topic of JavaScript is an entire book in itself, the details of how this widget works will not be discussed. Its existence has been included only for the sake of completeness of the chapter. Listing 4.10 uses the button widget to display a simple alert box:

Listing 4.10. Using the Button Widget
<INPUT TYPE="button" VALUE="Click me!" 
 onClick="alert('You clicked the button!');">