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

Implementing Arrays

In total, more than 60 functions currently are dedicated to array manipulation within PHP. Although there are far too many functions to cover in this book, almost all are documented extensively within the PHP documentation available at http://www.php.net/. Rather than simply reiterate the existing documentation, the focus of the remainder of this chapter will be on only the more advanced array functions and the application of those functions in scripts.

Now that you understand the formalities of the basic array, let's take a look at how arrays can be applied using the incredible number of array support functions available natively from within PHP.

Using an Array as a List

Perhaps one of the most common uses for an array is its use as a simple list. In fact, most of the examples discussed thus far have involved using the array as a simple list. In this section, we'll be looking at how a list using an array can be used to accomplish a specific taskthe automatic generation of the necessary HTML to display a group of images.

For this example, you'll define an array, $images, that will contain a list of all the different images that you will be displaying. You'll then use that array to create the necessary <IMG> HTML tags to display those images to the screen. Listing 2.12 shows the code.

Listing 2.12. Dynamic Generation of <IMG> Tags from an Array
<HTML>
<HEAD><TITLE>Using the array as a list</TITLE></HEAD>
<BODY>
<?php
    $images = array('image1.jpg', 'image2.jpg', 'image3.jpg');
    foreach($images as $val): ?>

    <IMG src="/images/<?php echo $val; ?>">

<?php endforeach;?>

</BODY>
</HTML>

Taking this example a step further, how would you use an array to create a script that displays a single random image every time the script executes? To do so using an array, it is probably best that a new PHP function is introducedthe array_rand() function. The syntax of this function is as follows:

array_rand($input [, $num_desired])

As shown, the array_rand() function takes two parameters. The first $input is, as the name implies, the input array. The second optional parameter, $num_desired, is an integer identifying how many random elements to pick from the input array. If the second parameter is not specified, the function defaults to a single random element. When executed, this function returns either a scalar value representing the single key in the original array or an array list of keys picked from the original array.

NOTE

In PHP, anytime a random number is required (for instance, when using the array_rand() function) the srand() function must be called to properly seed the random number generator.


With this knowledge in hand, implementing your random image script becomes trivial, as you can see in Listing 2.13:

Listing 2.13. A Random-Image Script Using array_rand()
<HTML>
<HEAD><TITLE>A random image script</TITLE></HEAD>
<BODY>
<?php
    srand((double)microtime()*1000000);
    $images = array('image1.jpg', 'image2.jpg', 'image3.jpg');
    $rImage = array_rand($images)
?>
<IMG src="<?php echo $images[$rImage]; ?>">
</BODY>
</HTML>

Using Arrays as a Sortable Table

Beyond simple lists, arrays within PHP are also very useful when you're working with and storing data that is designed to be in the form of a table. In this section, you'll learn how to implement simple tables using arrays with PHP, followed by a more complex example that is useful in developing array-based tables that can be sorted by an arbitrary column using PHP's array-sorting functions. Consider the following table:

Pet Name

Owner Name

Weight

Animal

Rosco

John

20

Dog

Icky

Ann

10

Cat

Rex

Cliff

3

Iguana

Buster

Amy

54

Dog

Delta

Hollie

30

Dog


Take a look at the preceding table; how could you implement this table using arrays in PHP? The simplest method would be to create an associative array (based on the name of each pet) whose value is another array containing the remainder of the data for a particular row, as shown in Listing 2.14:

Listing 2.14. Creating a Simple Table Using Arrays
<?php

    $petshack = array('Rosco' => array('name' => 'John',
                                       'weight' => 20,
                                       'animal' => 'Dog'),
                      'Icky' => array('name' => 'Ann',
                                      'weight' => 10,
                                      'animal' => 'Cat'),
                      'Rex' => array('name' => 'Cliff',
                                     'weight' => 3,
                                     'animal' => 'Iguana'),
                      'Buster' => array('name' => 'Amy',
                                        'weight' => 54,
                                        'animal' => 'Dog'),
                      'Delta' => array('name' => 'Hollie',
                                       'weight' => 30,
                                       'animal' => 'Dog'));
?>

The problem with an array structure such as this is it does not lend itself well to sorting the array by a particular column. As shown in Listing 2.15, to take advantage of PHP's native sorting functionality, each column must be stored in its own separate array (keeping the key values synchronized so that index 1 for each array column corresponds to the appropriate value).

Listing 2.15. Creating a Sortable Table Using Arrays
<?php

    $petshack['name'] = array('Rosco', 'Icky', 'Rex', 'Buster', 'Delta');
    $petshack['owner'] = array('John', 'Ann', 'Cliff', 'Amy', 'Hollie');
    $petshack['weight'] = array(20, 10, 3, 54, 30);
    $petshack['animal'] = array('Dog', 'Cat', 'Iguana', 'Dog', 'Dog');
?>

Compare Listings 2.14 and 2.15; the first thing you'll probably notice is that the second listing appears much cleaner than the original counterpart. Furthermore, because each column in the table is represented by a different PHP array, each column can also be sorted using PHP's internal array functions. To accomplish this sorting, you can use the asort() PHP function.

Although a number of sorting functions are available to the PHP developer, this particular sorting function has been chosen because of one critical detailit maintains the association of key/value pairs (see the discussion of array_filter() earlier in this chapter for more information on the importance of this). The syntax for the asort() function is as follows:

asort($input [, $sort_flag]);

NOTE

The asort() function orders arrays from smallest to largest (or alphabetically from AZ). If the opposite behavior is desired, the arsort() function can be used in the same manner as asort().


$input represents the array to be sorted, and $sort_flag is an optional parameter (a constant) specifying the type of sort to perform. Note that the constants specified by the sort_flag parameter are not PHP variables. They are constant values predefined within PHP (much like what can be created using the define statement). The three possible values for the sort_flag parameter are shown in Table 2.1:

Table 2.1. asort() Constants

SORT_REGULAR

Compare the items normally (default).

SORT_NUMERIC

Compare the items as numeric values.

SORT_STRING

Compare the items as string values.


When executed, the asort() function will sort the $input array as determined by sort_flag (no return value).

Implementing the asort() function to sort and maintain your table structure becomes a relatively simple task because each column of your table is stored in a separate array. Use the asort() function to sort whichever column is desired, and then use the foreach() function to display the sorted data in an HTML table, as shown in Listing 2.16, which sorts the table by the Weight column:

Listing 2.16. Sorting an Array-Based Table Using asort()
<HTML>
<HEAD><TITLE>Sorting Arrays</TITLE></HEAD>
<BODY>
<CENTER>
<H2>Sorting Arrays using the <code>asort()</code> function</H2>
<?php

    $petshack['name'] = array('Rosco', 'Icky', 'Rex', 'Buster', 'Delta');
    $petshack['owner'] = array('John', 'Ann', 'Cliff', 'Amy', 'Hollie');
    $petshack['weight'] = array(20, 10, 3, 54, 30);
    $petshack['animal'] = array('Dog', 'Cat', 'Iguana', 'Dog', 'Dog');

    /* Sort the weights */
    asort($petshack['weight'], SORT_NUMERIC);

?>
<TABLE>
<TR>
    <TD>Pet Name</TD>
    <TD>Pet Owner</TD>
    <TD>Pet Weight</TD>
    <TD>Type of Animal</TD>
</TR>
<?php

    foreach($petshack['weight'] as $key=>$weight) {
        echo "<TR>";
        echo "<TD>{$petshack['name'][$key]}</TD><TD>{$petshack['owner'][$key]} </TD>";
        echo "<TD>{$weight}</TD><TD>{$petshack['animal'][$key]}</TD>";
        echo "</TR>";
    }

?>
</TABLE>
</CENTER>
</BODY>
</HTML>

By changing the array passed to the asort() function (and also changing the foreach() function to loop through the array that had been sorted), this script can be modified with little difficulty to sort based on any of the four columns.

Using Arrays as a Lookup Table

Now that you have an idea of how to use arrays to develop a simple table and how array tables can be designed to provide for the maximum flexibility when dealing with sorting, let's take a look at a different type of tablethe lookup table. Unlike the tables discussed in the previous section of this chapter, a lookup table is not designed to be displayed to the user. Rather, it can be described as a reference table created and used by the PHP script to make a script more efficient or simplify a task. In this section, you'll be looking at a simple application of a lookup table. Specifically, you'll see how to implement a lookup table to create cryptograms (a puzzle game).

Although not as common in the newspaper today, cryptograms can be found in almost any puzzle book from your local supermarket. For those who are not familiar with them, the premise is quite simple: for a given string, replace every character (for instance, the letter A) with a different character. The challenge is then to take the encoded message and determine what the original message was. Although there are various ways to go about creating a cryptogram-generation script, we'll do so using a number of array functions starting with range().

In PHP, the range() function is used to create arrays that contain a specified range of numbers or letters. The syntax for range is as follows:

range(mixed $low, mixed $high)

$low represents the starting point of the range, and $high represents the end. As I have already alluded, these parameters can be numbers (that is, 1 through 10) or letters (that is, d through w). When executed, range() will return an integer-indexed array containing every number or letter between $low and $high. This function will be used to create an array containing all the letters in the alphabet, as well as the letters used to encode the cryptogram.

The second function that requires an introduction is the one actually responsible for determining how the letters are encoded in the final cryptogramthe shuffle() function. This function is similar to the array_rand() function discussed earlier in the chapter, with one significant difference. Instead of creating a new array randomly based on another array, the shuffle() function actually randomizes the contents of an array. The very simple syntax of the shuffle() is as follows:

shuffle($input)

Another function we'll need for this example is one that swaps the key/value pairs (so the keys are values, and the values are keys). To accomplish this, you'll use the array_flip() function, which also has a simple syntax:

array_flip($input)

$input represents the array to flip, and when executed, array_flip() returns the new (flipped) array.

Finally, take a look at your first search function in PHPthe in_array() function. This function takes two parameters (the value being searched for and the array to search) and returns a Boolean value indicating whether the particular value was found as described in the syntax that follows:

in_array($needle, $haystack [, $strict])

Note that the in_array() function also provides a third optional parameter, $strict. This optional Boolean value (false by default) determines whether the value specified in the $needle parameter must match not only the value, but the data type found in the corresponding array, $haystack. Thus, in an array with the string value 10, searching for the integer value 10 would return true. However, by setting the $strict parameter to true the same operation would return false.

Now that you have been introduced to the new functions being used in this example, let's take a look at the first portion of the cryptogram script, as shown in Listing 2.17:

NOTE

In Listing 2.17, the closing PHP tag ?> is intentionally omitted because it is only a fragment of the script.


Listing 2.17. A Cryptogram Generator Using PHP Arrays (Part 1)
<?php

    /* Initialize the random number generator */
    srand((double)microtime() * 1000000);

    $message = "This is my super secret message!";
    $message = strtoupper($message);

    /* Create an alphabet array whose keys are the letters A-Z, and whose
       values are the numbers 0 - 25 respectively */
    $alphabet = array_flip(range('A', 'Z'));
    $cryptogram = range('A', 'Z');

    /* Randomize the lookup table used for the cryptogram generation */
    shuffle($cryptogram);

As shown in Listing 2.17, the first step in your cryptogram script is the initialization of the random-number generator. As was the case with array_rand(), the shuffle() function requires this to function properly. The $message variable (which represents the actual string you are encoding) is then initialized and converted to uppercase using the strtoupper() function. Using a combination of the range() function coupled with the array_flip() function, we create an associative array, $alphabet, which has key values for every letter in the alphabet and associates these values with the integers 0 tHRough 25. Complementing the $alphabet variable is the $cryptogram variable, which is initialized with 26 values representing the letters of the alphabet. The $cryptogram variable will be used to encode the message into the final cryptogram.

With all the initialization complete, you randomize your cryptogram lookup table using the shuffle() function discussed earlier and begin encoding your cryptogram (see Listing 2.18):

Listing 2.18. A Cryptogram Generator Using PHP Arrays (Part 2)
$encoded = "";

/* Cycle through each character of the message to encode */
for($i = 0; $i < strlen($message); $i++) {

    $char = $message[$i];

    /* Determine if the current character is encodable
    by searching for it in the $cryptogram lookup table */
    if(!in_array($char, $cryptogram)) {

     /* if character is not encodable, copy straight to
        the encoded string */
     $encoded .= $char;

    } else {

     /* if the character is encoded, replace it with the
        matching character from $cryptogram */
         $encoded .= $cryptogram[$alphabet[$char]];

        }

    }

    echo $encoded;
?>

NOTE

Although not arrays, a string within PHP can behave like an array; it allows the developer to access a single character from the string by referencing it using the square-bracket syntax shown in Listing 2.18. Note that although strings can behave as arrays, they cannot be used with array manipulation statements, such as foreach(), or array functions.


With all the initialization complete, the next step in the script is to cycle through each individual character within the message to encode using a for() loop starting from 0 to the length returned by the strlen() function. The strlen() function returns the length of the provided string (strings are discussed in detail in Chapter 1). Because a number of cryptogram-generated characters don't translate (punctuation, whitespace, and so on) it is necessary to check to see that each character in the message being encoded exists prior to attempting to encode it. To do so, use the in_array() function to ensure that the character exists within the $cryptogram lookup table. If there is no translation available for the particular character (meaning in_array() returned false) it is passed straight into the encoded message stored in the $encoded variable. Otherwise, the character is translated based on the $cryptogram array. However, because the $cryptogram array's keys are not characters (recall that they are integer values 025) the $alphabet array is used to retrieve the particular integer value for the given character.

After the message is processed character-by-character, $encoded contains the complete cryptogram for the message (which is then displayed to the client). Because this script generates a completely new cryptogram every time it is executed, it is impossible to display the exact output. However, when this script was executed, my output was the following:

DPYM YM RJ MHAXB MXUBXD RXMMOEX!

Converting from Strings to Arrays and Back

As introduced in Chapter 1, you can use a number of methods for processing strings in PHP. One very common use of arrays is processing a list of items represented as a string, such as the following:

John Coggeshall, Max Smith, Mary Johnston

When processing such a list, PHP provides a function that allows you to tokenize (separate) string values by a constant separatorthe explode() function with the following syntax:

explode($separator, $string [, $limit]);

$separator is the string that will represent the separator that $string will be broken into. Optionally, you can also pass the $limit parameter, which represents the maximum number of splits to occur. When executed, the explode() function breaks a string into individual array elements using the value of $separator to indicate where each split will occur. Using our earlier string list, to break apart each name the comma character (,) would be used as shown in Listing 2.19:

Listing 2.19. Using the explode() Function
<?php

    $input_string = "John Coggeshall, Max Smith, Mary Johnston";

    $pieces = explode(",", $input_string);

    echo "Names in List: <BR/>\n";
    foreach($pieces as $name) {
        echo trim($name) . "<BR/>\n";
    }

?>

Conversely, PHP also provides a function that will take all of the individual elements within an array and create a string from them. This function is the implode() function and has the following syntax:

implode($glue, $pieces);

$glue is the string used to "glue" each element of the array specified by $pieces together. Listing 2.20 uses this function to re-create our original string after it has been exploded:

Listing 2.20. Using the implode() Function
<?php

    $input_array = array("John Coggeshall",
                         "Max Smith",
                         "Mary Johnston");

    $orig_string  = implode(", ", $input_array);

?>