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

User-Defined Functions

Thus far, all the script examples that you have been exposed to have been linear (meaning that they started from the top and executed to the bottom). However, it would be very limiting if this was the only way scripts could be created. To overcome this limitation, you can use functions. For those with prior programming experience, functions probably are already a firm concept requiring little explanation. For those who need a little explanation, read on.

In PHP, functions are defined in the following fashion:

function func_name ([variable [= constant][, ...]) {
    /* Any valid PHP code */
}

The name of the function (labeled by "func_name") is an arbitrary (but descriptive) name following the same rules as those imposed on PHP variables followed by a set of parameters. How many parameters, their default values (if any), and the parameter names are all up to the developer. Functions can also "return" a value using the PHP return statement. An example of a PHP function that determines whether a given year is a leap year is shown in Listing 1.19:

Listing 1.19. User-Defined Function to Determine a Leap Year
<?php

    function is_leapyear($year = 2004) {

        $is_leap = (!($year % 4) && (($year % 100) || !($year % 400)));
        return $is_leap;

    }

?>

NOTE

If you are looking at the preceding function and scratching your head, I'll explain how it works. A year is considered a leap year if

  • The year is divisible by 4 and not by 100.

  • The year is divisible by 4 and 400.


After this function has been defined within your script, it can be used as shown in Listing 1.20:

Listing 1.20. Using User-Defined Functions
<?php

    $answer = is_leapyear(2000);

    if($answer) {

        echo "2000 is a leap year<BR>";

    } else {

        echo "2000 is not a leap year.<BR>";

    }

    /* Use default for the parameter */
    $answer = is_leapyear(); 

    if($answer) {

        echo "2003 is a leap year.<BR>";

    } else {

        echo "2003 is not a leap year.<BR>";

    }

?>

With the introduction of functions comes the discussion of variable scope. The term variable scope refers to how PHP decides which declared variables can be used from where in the PHP script. Up to this point, all your variables have been a part of what is called the global variable scope. However, variables declared within a function are a part of what is called the local function scope unless otherwise defined. What does this mean to you as a developer? Looking back at your is_leapyear() function, this means the $is_leap variable exists only within that specific function and cannot be accessed from outside that function's scope. In fact, you can even create a variable called $is_leap somewhere else in your script (as long as it's not in the is_leapyear() function) without affecting the variable within the function. Furthermore, any variables defined outside the function are similarly not accessible.

Although this concept of scope is incredibly useful and makes development considerably easier, there are times when it would be useful to access variables from another scope from within your functions. To accomplish this, PHP has the global statement. This statement modifies the scope of a given variable from a local scope to the global variable scope. Its syntax is as follows:

global $var1 [, $var2 [, $var3 [, ...]]];

In PHP, the variable passed to the global statement does not have to already be declared in any scope. This can be particularly useful when you want to design a function that "creates" a variable in the global scope, as shown in Listing 1.21:

Listing 1.21. Working with Variable Scope in PHP
<?php

    function createglobal() {

        global $my_global;
        $my_global = 10;

    }

    echo "The value of \$my_global is '$my_global'<BR>";

    createglobal();

    echo "The value of \$my_global is '$my_global'<BR>";
?>

This produces the following output:

The value of $my_global is ''
The value of $my_global is '10'

As you can see, although $my_global was never initialized anywhere in the global scope, through the use of the global statement it was created from within the createglobal() function. Likewise, variables that exist within the global scope may also be brought into the local scope of a function in the same fashion, as shown in Listing 1.22:

Listing 1.22. More Working with Variable Scope
<?php

    function getglobal() {

        global $my_global;
        echo "The value of \$foobar is '$foobar'<BR>";

    }

    $my_global = 20;

    getglobal();
?>

This produces the following output:

The value of $my_global is '20';

NOTE

Although all local variables adhere to the concept of variable scope, certain variables created by PHP, namely $_SERVER, $_GET, $_POST, $_REQUEST, $_GLOBALS, $_COOKIE, $_ENV, $_SESSION, and $_FILES are always available regardless of the current scope (names are case sensitive). These variables, called superglobals, are available anytime during the execution of a PHP script. These superglobals will be explained and used throughout the book; however, a brief introduction to them all can be found online at http://www.php.net/manual/en/language.variables.predefined.php.


Under most circumstances, when a function in PHP is executed, any variables that were created by the function are destroyed when the function is complete. However, like most modern programming languages, PHP supports what are known as static variables, which do not get destroyed when the function terminates. To create a static variable within a function, you use the static statement as follows:

static $varname [= constant [, $var2 [= constant]] ...];

$varname is the name of the variable you would like not to be destroyed, and the optional constant value refers to the initial value of the variable. In the example, the static statement functions as shown in Listing 1.23:

Listing 1.23. Working with Static Variables in Functions
<?php

    function statictest() {

        static $count = 0;

        $count++;

        return $count;

    }

    statictest();
    statictest();

    $foo = statictest();

    echo "The statictest() function ran $foo times.<BR>";

?>

This results in the following output:

The statictest() function ran 2 times.