BUY THIS BOOK

Safari Books Online

What is this?

Looking to Reprint this content?


Programming PHP
Programming PHP

By Rasmus Lerdorf, Kevin Tatroe

Cover | Table of Contents | Colophon


Table of Contents

Chapter 1: Introduction to PHP
PHP is a simple yet powerful language designed for creating HTML content. This chapter covers essential background on the PHP language. It describes the nature and history of PHP; which platforms it runs on; and how to download, install, and configure it. This chapter ends by showing you PHP in action, with a quick walkthrough of several PHP programs that illustrate common tasks, such as processing form data, interacting with a database, and creating graphics.
PHP can be used in three primary ways:
Server-side scripting
PHP was originally designed to create dynamic web content, and it is still best suited for that task. To generate HTML, you need the PHP parser and a web server to send the documents. Lately, PHP has also become popular for generating XML documents, graphics, Flash animations, PDF files, and more.
Command-line scripting
PHP can run scripts from the command line, much like Perl, awk, or the Unix shell. You might use the command-line scripts for system administration tasks, such as backup and log parsing.
Client-side GUI applications
Using PHP-GTK (http://gtk.php.net), you can write full-blown, cross-platform GUI applications in PHP.
In this book, we'll concentrate on the first item, using PHP to develop dynamic web content.
PHP runs on all major operating systems, from Unix variants including Linux, FreeBSD, and Solaris to such diverse platforms as Windows and Mac OS X. It can be used with all leading web servers, including Apache, Microsoft IIS, and the Netscape/iPlanet servers.
The language is very flexible. For example, you aren't limited to outputting just HTML or other text files—any document format can be generated. PHP has built-in support for generating PDF files, GIF, JPG, and PNG images, and Flash movies.
One of PHP's most significant features is its wide-ranging support for databases. PHP supports all major databases (including MySQL, PostgreSQL, Oracle, Sybase, and ODBC-compliant databases), and even many obscure ones. With PHP, creating web pages with dynamic content from a database is remarkably simple.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
What Does PHP Do?
PHP can be used in three primary ways:
Server-side scripting
PHP was originally designed to create dynamic web content, and it is still best suited for that task. To generate HTML, you need the PHP parser and a web server to send the documents. Lately, PHP has also become popular for generating XML documents, graphics, Flash animations, PDF files, and more.
Command-line scripting
PHP can run scripts from the command line, much like Perl, awk, or the Unix shell. You might use the command-line scripts for system administration tasks, such as backup and log parsing.
Client-side GUI applications
Using PHP-GTK (http://gtk.php.net), you can write full-blown, cross-platform GUI applications in PHP.
In this book, we'll concentrate on the first item, using PHP to develop dynamic web content.
PHP runs on all major operating systems, from Unix variants including Linux, FreeBSD, and Solaris to such diverse platforms as Windows and Mac OS X. It can be used with all leading web servers, including Apache, Microsoft IIS, and the Netscape/iPlanet servers.
The language is very flexible. For example, you aren't limited to outputting just HTML or other text files—any document format can be generated. PHP has built-in support for generating PDF files, GIF, JPG, and PNG images, and Flash movies.
One of PHP's most significant features is its wide-ranging support for databases. PHP supports all major databases (including MySQL, PostgreSQL, Oracle, Sybase, and ODBC-compliant databases), and even many obscure ones. With PHP, creating web pages with dynamic content from a database is remarkably simple.
Finally, PHP provides a library of PHP code to perform common tasks, such as database abstraction, error handling, and so on, with the PHP Extension and Application Repository (PEAR). PEAR is a framework and distribution system for reusable PHP components. You can find out more about it at http://pear.php.net.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
A Brief History of PHP
Rasmus Lerdorf first conceived of PHP in 1994, but the PHP that people use today is quite different from the initial version. To understand how PHP got where it is today, it is useful to know the historical evolution of the language. Here's that story, as told by Rasmus.
Here is the PHP 1.0 announcement that I posted to the Usenet newsgroup comp.infosystems.www.authoring.cgi in June 1995:
From: rasmus@io.org (Rasmus Lerdorf)
Subject: Announce: Personal Home Page Tools (PHP Tools)
Date: 1995/06/08
Message-ID: <3r7pgp$aa1@ionews.io.org>#1/1
organization: none
newsgroups: comp.infosystems.www.authoring.cgi

Announcing the Personal Home Page Tools (PHP Tools) version 1.0.

These tools are a set of small tight cgi binaries written in C.
They perform a number of functions including:

. Logging accesses to your pages in your own private log files
. Real-time viewing of log information
. Providing a nice interface to this log information
. Displaying last access information right on your pages
. Full daily and total access counters
. Banning access to users based on their domain
. Password protecting pages based on users' domains
. Tracking accesses ** based on users' e-mail addresses **
. Tracking referring URL's - HTTP_REFERER support
. Performing server-side includes without needing server support for it
. Ability to not log accesses from certain domains (ie. your own)
. Easily create and display forms
. Ability to use form information in following documents

Here is what you don't need to use these tools:

. You do not need root access - install in your ~/public_html dir
. You do not need server-side includes enabled in your server
. You do not need access to Perl or Tcl or any other script interpreter
. You do not need access to the httpd log files

The only requirement for these tools to work is that you have
the ability to execute your own cgi programs.  Ask your system
administrator if you are not sure what this means.

The tools also allow you to implement a guestbook or any other
form that needs to write information and display it to users
later in about 2 minutes.

The tools are in the public domain distributed under the GNU
Public License.  Yes, that means they are free!

For a complete demonstration of these tools, point your browser
at: http://www.io.org/~rasmus

--
Rasmus Lerdorf
rasmus@io.org
http://www.io.org/~rasmus
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Installing PHP
PHP is available for many operating systems and platforms. The most common setup, however, is to use PHP as a module for the Apache web server on a Unix machine. This section briefly describes how to install Apache with PHP. If you're interested in running PHP on Windows, see Chapter 15, which explains your many options.
To install Apache with PHP, you'll need a Unix machine with an ANSI-compliant C compiler, and around 5 MB of available disk space for source and object files. You'll also need Internet access to fetch the source code for PHP and Apache.
Start by downloading the source distributions of PHP and Apache. The latest files are always available from http://www.php.net and http://www.apache.org, respectively. Store the files in the same directory, so that you have:
-rw-r--r--   1 gnat  wheel  2177983 Oct  9 09:34 apache_1.3.22.tar.gz 
-rw-r--r--   1 gnat  wheel  3371385 Dec 10 14:29 php-4.1.1.tar.gz
Now uncompress and extract the distributions:
# gunzip -c apache_1.3.22.tar.gz | tar xf -
# gunzip -c php-4.1.1.tar.gz | tar xf -
Each distribution unpacks into its own subdirectory, as follows:
drwxr-xr-x   8 gnat  wheel      512 Dec 16 11:26 apache_1.3.22
drwxr-xr-x  16 gnat  wheel     2048 Dec 21 23:48 php-4.1.1
The next step is to configure Apache, then configure PHP, telling it where the Apache source is and specifying the various other features that you want built into PHP. You'll probably want to customize the configurations of Apache and PHP. For instance, provide the --prefix=/some/path option to Apache's configure to change where Apache expects its configuration files and utilities. Similarly, typical options for PHP include --with-apache to identify the location of the Apache source tree, --enable-inline-optimizations to enable compilation options that give a faster PHP interpreter, and --with-mysql to identify where MySQL was installed. Each configuration creates detailed output as it goes:
# cd apache_1.3.22
# ./configure --prefix=/usr/local/apache
Configuring for Apache, Version 1.3.22
 + using installation path layout: Apache (config.layout)
Creating Makefile
Creating Configuration.apaci in src
Creating Makefile in src
 + configured for FreeBSD 4.2 platform
 + setting C compiler to gcc
...
# cd ../php-4.1.1
# ./configure --with-apache=../apache_1.3.22 --enable-inline-optimization \
  --with-mysql=/usr
creating cache ./config.cache
checking for a BSD compatible install... /usr/bin/install -c
checking whether build environment is sane... yes
checking whether make sets ${MAKE}... yes
checking for working aclocal... missing
checking for working autoconf... found
checking for working automake... missing
checking for working autoheader... found
checking for working makeinfo... found
Updated php_version.h
...
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
A Walk Through PHP
PHP pages are HTML pages with PHP commands embedded in them. This is in contrast to many other dynamic web-page solutions, which are scripts that generate HTML. The web server processes the PHP commands and sends their output (and any HTML from the file) to the browser. Example 1-1 shows a complete PHP page.
Example 1-1. hello.php
<html>
  <head>
    <title>Look Out World</title>
  </head>

  <body>
    <?php echo 'Hello, world!' ?>
  </body>
</html>
Save the contents of Example 1-1 to a file, hello.php, and point your browser to it. The results appear in Figure 1-3.
Figure 1-3: Output of hello.php
The PHP echo command produces output (the string "Hello, world!"), which is inserted into the HTML file. In this example, the PHP code is placed between <?php and ?> tags. There are other ways to tag your PHP code—see Chapter 2 for a full description.
The PHP function phpinfo( ) creates an HTML page full of information on how PHP was installed. You can use it to see whether you have particular extensions installed, or whether the php.ini file has been customized. Example 1-2 is a complete page that displays the phpinfo( ) page.
Example 1-2. Using phpinfo( )
<?php phpinfo(  ); ?>
Figure 1-4 shows the first part of the output of Example 1-2.
Figure 1-4: Partial output of phpinfo( )
Example 1-3 creates and processes a form. When the user submits the form, the information typed into the name field is sent back to this page. The PHP code tests for a name field and displays a greeting if it finds one.
Example 1-3. Processing a form
<html>
  <head>
    <title>Personalized Hello World</title>
  </head>

  <body>
    <?php if(!empty($_POST['name'])) {
      echo "Greetings, {$_POST['name']}, and welcome.";
    } ?>

    <form action="<?php echo $PHP_SELF; ?>" method="post">
      Enter your name: <input type="text" name="name" />
      <input type="submit" />
    </form>
  </body>
</html>
The form and the message are shown in Figure 1-5.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Chapter 2: Language Basics
This chapter provides a whirlwind tour of the core PHP language, covering such basic topics as data types, variables, operators, and flow control statements. PHP is strongly influenced by other programming languages, such as Perl and C, so if you've had experience with those languages, PHP should be easy to pick up. If PHP is one of your first programming languages, don't panic. We start with the basic units of a PHP program and build up your knowledge from there.
The lexical structure of a programming language is the set of basic rules that governs how you write programs in that language. It is the lowest-level syntax of the language and specifies such things as what variable names look like, what characters are used for comments, and how program statements are separated from each other.
The names of user-defined classes and functions, as well as built-in constructs and keywords such as echo, while, class, etc., are case-insensitive. Thus, these three lines are equivalent:
echo("hello, world");
ECHO("hello, world");
EcHo("hello, world");
Variables, on the other hand, are case-sensitive. That is, $name, $NAME, and $NaME are three different variables.
A statement is a collection of PHP code that does something. It can be as simple as a variable assignment or as complicated as a loop with multiple exit points. Here is a small sample of PHP statements, including function calls, assignment, and an if test:
echo "Hello, world";
myfunc(42, "O'Reilly");
$a = 1;
$name = "Elphaba";
$b = $a / 25.0;
if ($a == $b) { echo "Rhyme? And Reason?"; }
PHP uses semicolons to separate simple statements. A compound statement that uses curly braces to mark a block of code, such as a conditional test or loop, does not need a semicolon after a closing brace. Unlike in other languages, in PHP the semicolon before the closing brace is not optional:
if ($needed) {
  echo "We must have it!";       // semicolon required here
}                                // no semicolon required here
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Lexical Structure
The lexical structure of a programming language is the set of basic rules that governs how you write programs in that language. It is the lowest-level syntax of the language and specifies such things as what variable names look like, what characters are used for comments, and how program statements are separated from each other.
The names of user-defined classes and functions, as well as built-in constructs and keywords such as echo, while, class, etc., are case-insensitive. Thus, these three lines are equivalent:
echo("hello, world");
ECHO("hello, world");
EcHo("hello, world");
Variables, on the other hand, are case-sensitive. That is, $name, $NAME, and $NaME are three different variables.
A statement is a collection of PHP code that does something. It can be as simple as a variable assignment or as complicated as a loop with multiple exit points. Here is a small sample of PHP statements, including function calls, assignment, and an if test:
echo "Hello, world";
myfunc(42, "O'Reilly");
$a = 1;
$name = "Elphaba";
$b = $a / 25.0;
if ($a == $b) { echo "Rhyme? And Reason?"; }
PHP uses semicolons to separate simple statements. A compound statement that uses curly braces to mark a block of code, such as a conditional test or loop, does not need a semicolon after a closing brace. Unlike in other languages, in PHP the semicolon before the closing brace is not optional:
if ($needed) {
  echo "We must have it!";       // semicolon required here
}                                // no semicolon required here
The semicolon is optional before a closing PHP tag:
<?php
 if ($a == $b) { echo "Rhyme? And Reason?"; }
 echo "Hello, world"             // no semicolon required before closing tag
?>
It's good programming practice to include optional semicolons, as they make it easier to add code later.
In general, whitespace doesn't matter in a PHP program. You can spread a statement across any number of lines, or lump a bunch of statements together on a single line. For example, this statement:
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Data Types
PHP provides eight types of values, or data types. Four are scalar (single-value) types: integers, floating-point numbers, strings, and booleans. Two are compound (collection) types: arrays and objects. The remaining two are special types: resource and NULL. Numbers, booleans, resources, and NULL are discussed in full here, while strings, arrays, and objects are big enough topics that they get their own chapters (Chapter 4, Chapter 5, and Chapter 6).
Integers are whole numbers, like 1, 12, and 256. The range of acceptable values varies according to the details of your platform but typically extends from -2,147,483,648 to +2,147,483,647. Specifically, the range is equivalent to the range of the long data type of your C compiler. Unfortunately, the C standard doesn't specify what range that long type should have, so on some systems you might see a different integer range.
Integer literals can be written in decimal, octal, or hexadecimal. Decimal values are represented by a sequence of digits, without leading zeros. The sequence may begin with a plus (+) or minus (-) sign. If there is no sign, positive is assumed. Examples of decimal integers include the following:
1998
-641
+33
Octal numbers consist of a leading 0 and a sequence of digits from 0 to 7. Like decimal numbers, octal numbers can be prefixed with a plus or minus. Here are some example octal values and their equivalent decimal values:
0755      // decimal 493
+010      // decimal 8
Hexadecimal values begin with 0x, followed by a sequence of digits (0-9) or letters (A-F). The letters can be upper- or lowercase but are usually written in capitals. Like decimal and octal values, you can include a sign in hexadecimal numbers:
0xFF        // decimal 255
0x10        // decimal 16
-0xDAD1     // decimal -56017
If you try to store a too-large integer in a variable, it will automatically be turned into a floating-point number.
Use the is_int( ) function (or its is_integer( ) alias) to test whether a value is an integer:
if (is_int($x)) {
    // $x is an integer
}
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Variables
Variables in PHP are identifiers prefixed with a dollar sign ($). For example:
$name
$Age
$_debugging
$MAXIMUM_IMPACT
A variable may hold a value of any type. There is no compile- or runtime type checking on variables. You can replace a variable's value with another of a different type:
$what = "Fred";
$what = 35;
$what = array('Fred', '35', 'Wilma');
There is no explicit syntax for declaring variables in PHP. The first time the value of a variable is set, the variable is created. In other words, setting a variable functions as a declaration. For example, this is a valid complete PHP program:
$day = 60 * 60 * 24;
echo "There are $day seconds in a day.\n";
There are 86400 seconds in a day.
         
A variable whose value has not been set behaves like the NULL value:
if ($uninitialized_variable === NULL) {
  echo "Yes!";
}
Yes!
         
You can reference the value of a variable whose name is stored in another variable. For example:
$foo = 'bar';
$$foo = 'baz';
After the second statement executes, the variable $bar has the value "baz".
In PHP, references are how you create variable aliases. To make $black an alias for the variable $white, use:
$black =& $white;
The old value of $black is lost. Instead, $black is now another name for the value that is stored in $white:
$big_long_variable_name = "PHP";
$short =& $big_long_variable_name;
$big_long_variable_name .= " rocks!";
print "\$short is $short\n";
print "Long is $big_long_variable_name\n";
$short is PHP rocks!
               
Long is PHP rocks!
$short = "Programming $short";
print "\$short is $short\n";
print "Long is $big_long_variable_name\n";
$short is Programming PHP rocks!
               
Long is Programming PHP rocks!
            
After the assignment, the two variables are alternate names for the same value. Unsetting a variable that is aliased does not affect other names for that variable's value, though:
$white = "snow";
$black =& $white;
unset($white);
print $black;
snow
            
Functions can return values by reference (for example, to avoid copying large strings or arrays, as discussed in Chapter 3):
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Expressions and Operators
An expression is a bit of PHP that can be evaluated to produce a value. The simplest expressions are literal values and variables. A literal value evaluates to itself, while a variable evaluates to the value stored in the variable. More complex expressions can be formed using simple expressions and operators.
An operator takes some values (the operands) and does something (for instance, adds them together). Operators are written as punctuation symbols—for instance, the + and - familiar to us from math. Some operators modify their operands, while most do not.
Table 2-3 summarizes the operators in PHP, many of which were borrowed from C and Perl. The column labeled "P" gives the operator's precedence; the operators are listed in precedence order, from highest to lowest. The column labeled "A" gives the operator's associativity, which can be L (left-to-right), R (right-to-left), or N (non-associative).
Table 2-3: PHP operators
P
A
Operator
Operation
19
N
new
Create new object
18
R
[
Array subscript
17
R
!
Logical NOT
R
~
Bitwise NOT
R
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Flow-Control Statements
PHP supports a number of traditional programming constructs for controlling the flow of execution of a program.
Conditional statements, such as if/else and switch, allow a program to execute different pieces of code, or none at all, depending on some condition. Loops, such as while and for, support the repeated execution of particular code.
The if statement checks the truthfulness of an expression and, if the expression is true, evaluates a statement. An if statement looks like:
if (expression) 
  statement
            
To specify an alternative statement to execute when the expression is false, use the else keyword:
if (expression) 
  statement 
else 
  statement
            
For example:
if ($user_validated)
  echo "Welcome!";
else
  echo "Access Forbidden!";
To include more than one statement in an if statement, use a block —a curly brace-enclosed set of statements:
if ($user_validated) {
  echo 'Welcome!";
  $greeted = 1;
} else {
  echo "Access Forbidden!";
  exit;
}
PHP provides another syntax for blocks in tests and loops. Instead of enclosing the block of statements in curly braces, end the if line with a colon (:) and use a specific keyword to end the block (endif, in this case). For example:
if ($user_validated) :
  echo "Welcome!";
  $greeted = 1;
else :
  echo "Access Forbidden!";
  exit;
endif;
Other statements described in this chapter also have similar alternate style syntax (and ending keywords); they can be useful if you have large blocks of HTML inside your statements. For example:
<?if($user_validated):?>
  <table>
    <tr>
      <td>First Name:</td><td>Sophia</td>
    </tr>
    <tr>
      <td>Last Name:</td><td>Lee</td>
    </tr>
  </table>
<?else:?>
  Please log in.
<?endif?>
Because if is a statement, you can chain them:
if ($good)
  print('Dandy!');
else
  if ($error)
    print('Oh, no!');
  else
    print("I'm ambivalent...");
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Including Code
PHP provides two constructs to load code and HTML from another module: require and include. They both load a file as the PHP script runs, work in conditionals and loops, and complain if the file being loaded can't be found. The main difference is that attempting to require a nonexistent file is a fatal error, while attempting to include such a file produces a warning but does not stop script execution.
A common use of include is to separate page-specific content from general site design. Common elements such as headers and footers go in separate HTML files, and each page then looks like:
<? include 'header.html'; ?>
content
<? include 'footer.html'; ?>
We use include because it allows PHP to continue to process the page even if there's an error in the site design file(s). The require construct is less forgiving and is more suited to loading code libraries, where the page can't be displayed if the libraries don't load. For example:
require 'codelib.inc';
mysub(  );               // defined in codelib.inc
A marginally more efficient way to handle headers and footers is to load a single file and then call functions to generate the standardized site elements:
<? require 'design.inc';
   header(  );
?>
content
<? footer(  ); ?>
If PHP cannot parse some part of a file included by include or require, a warning is printed and execution continues. You can silence the warning by prepending the call with the silence operator; for example, @include.
If the allow_url_fopen option is enabled through PHP's configuration file, php.ini, you can include files from a remote site by providing a URL instead of a simple local path:
include 'http://www.example.com/codelib.inc';
If the filename begins with "http://" or "ftp://", the file is retrieved from a remote site and then loaded.
Files included with include and require can be arbitrarily named. Common extensions are .php, .inc, and .html. Note that remotelyfetching a file that ends in .php from a web server that has PHP enabled fetches the output of that PHP script. For this reason, we recommend you use
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Embedding PHP in Web Pages
Although it is possible to write and run standalone PHP programs, most PHP code is embedded in HTML or XML files. This is, after all, why it was created in the first place. Processing such documents involves replacing each chunk of PHP source code with the output it produces when executed.
Because a single file contains PHP and non-PHP source code, we need a way to identify the regions of PHP code to be executed. PHP provides four different ways to do this.
As you'll see, the first, and preferred, method looks like XML. The second method looks like SGML. The third method is based on ASP tags. The fourth method uses the standard HTML <script> tag; this makes it easy to edit pages with enabled PHP using a regular HTML editor.
Because of the advent of the eXtensible Markup Language (XML) and the migration of HTML to an XML language (XHTML), the currently preferred technique for embedding PHP uses XML-compliant tags to denote PHP instructions.
Coming up with tags to demark PHP commands in XML was easy, because XML allows the definition of new tags. To use this style, surround your PHP code with <?php and ?>. Everything between these markers is interpreted as PHP, and everything outside the markers is not. Although it is not necessary to include spaces between the markers and the enclosed text, doing so improves readability. For example, to get PHP to print "Hello, world", you can insert the following line in a web page:
<?php echo "Hello, world"; ?>
The trailing semicolon on the statement is optional, because the end of the block also forces the end of the expression. Embedded in a complete HTML file, this looks like:
<!doctype html public "-//w3c//dtd html 4.0 transitional//en">
<html>
<head>
  <title>This is my first PHP program!</title>
</head>
<body>
<p>
  Look, ma! It's my first PHP program:<br />
  <?php echo "Hello, world"; ?><br />
  How cool is that?
</p>
</body>
</html>
Of course, this isn't very exciting—we could have done it without PHP. The real value of PHP comes when we put dynamic information from sources such as databases and form values into the web page. That's for a later chapter, though. Let's get back to our "Hello, world" example. When a user visits this page and views its source, it looks like this:
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Chapter 3: Functions
A function is a named block of code that performs a specific task, possibly acting upon a set of values given to it, or parameters , and possibly returning a single value. Functions save on compile time—no matter how many times you call them, functions are compiled only once for the page. They also improve reliability by allowing you to fix any bugs in one place, rather than everywhere you perform a task, and they improve readability by isolating code that performs specific tasks.
This chapter introduces the syntax of function calls and function definitions and discusses how to manage variables in functions and pass values to functions (including pass-by-value and pass-by-reference). It also covers variable functions and anonymous functions.
Functions in a PHP program can be either built-in (or, by being in an extension, effectively built-in) or user-defined. Regardless of their source, all functions are evaluated in the same way:
$some_value = function_name( [ parameter, ... ] );
The number of parameters a function requires differs from function to function (and, as we'll see later, may even vary for the same function). The parameters supplied to the function may be any valid expression and should be in the specific order expected by the function. A function's documentation will tell you what parameters the function expects and what values you can expect to be returned.
Here are some examples of functions:
// strlen(  ) is a built-in function that returns the length of a string
$length = strlen("PHP"); // $length is now 3

// sin() and asin(  ) are the sine and arcsine math functions
$result = sin(asin(1)); // $result is the sine of arcsin(1), or 1.0

// unlink(  ) deletes a file
$result = unlink("functions.txt"); // false if unsuccessful
In the first example, we give an argument, "PHP", to the function strlen( ), which gives us the number of characters in the string it's given. In this case, it returns 3, which is assigned to the variable $length. This is the simplest and most common way to use a function.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Calling a Function
Functions in a PHP program can be either built-in (or, by being in an extension, effectively built-in) or user-defined. Regardless of their source, all functions are evaluated in the same way:
$some_value = function_name( [ parameter, ... ] );
The number of parameters a function requires differs from function to function (and, as we'll see later, may even vary for the same function). The parameters supplied to the function may be any valid expression and should be in the specific order expected by the function. A function's documentation will tell you what parameters the function expects and what values you can expect to be returned.
Here are some examples of functions:
// strlen(  ) is a built-in function that returns the length of a string
$length = strlen("PHP"); // $length is now 3

// sin() and asin(  ) are the sine and arcsine math functions
$result = sin(asin(1)); // $result is the sine of arcsin(1), or 1.0

// unlink(  ) deletes a file
$result = unlink("functions.txt"); // false if unsuccessful
In the first example, we give an argument, "PHP", to the function strlen( ), which gives us the number of characters in the string it's given. In this case, it returns 3, which is assigned to the variable $length. This is the simplest and most common way to use a function.
The second example passes the result of asin(1) to the sin( ) function. Since the sine and arcsine functions are reflexive, taking the sine of the arcsine of any value will always return that same value.
In the final example, we give a filename to the unlink( ) function, which attempts to delete the file. Like many functions, it returns false when it fails. This allows you to use another built-in function, die( ) , and the short-circuiting property of the logic operators. Thus, this example might be rewritten as:
$result = unlink("functions.txt") or die("Operation failed!");
The unlink( ) function, unlike the other two examples, affects something outside of the parameters given to it. In this case, it deletes a file from the filesystem. All such side effects of a function should be carefully documented.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Defining a Function
To define a function, use the following syntax:
function [&] function_name ( [ parameter [, ... ] ] )
{
  statement list
}
The statement list can include HTML. You can declare a PHP function that doesn't contain any PHP code. For instance, the column( ) function simply gives a convenient short name to HTML code that may be needed many times throughout the page:
<? function column(  ) { ?>
</td><td>
<? } ?>
The function name can be any string that starts with a letter or underscore followed by zero or more letters, underscores, and digits. Function names are case-insensitive; that is, you can call the sin( ) function as sin(1), SIN(1), SiN(1), and so on, because all these names refer to the same function.
Typically, functions return some value. To return a value from a function, use the return statement: put return expr inside your function. When a return statement is encountered during execution, control reverts to the calling statement, and the evaluated results of expr will be returned as the value of the function. Although it can make for messy code, you can actually include multiple return statements in a function if it makes sense (for example, if you have a switch statement to determine which of several values to return).
If you define your function with the optional ampersand before the name, the function returns a reference to the returned data rather than a copy of the data.
Let's take a look at a simple function. Example 3-1 takes two strings, concatenates them, and then returns the result (in this case, we've created a slightly slower equivalent to the concatenation operator, but bear with us for the sake of example).
Example 3-1. String concatenation
function strcat($left, $right) {
  $combined_string = $left . $right;
  return $combined_string;
}
The function takes two arguments, $left and $right. Using the concatenation operator, the function creates a combined string in the variable $combined_string. Finally, in order to cause the function to have a value when it's evaluated with our arguments, we return the value
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Variable Scope
Up to this point, if you don't use functions, any variable you create can be used anywhere in a page. With functions, this is no longer always true. Functions keep their own sets of variables that are distinct from those of the page and of other functions.
The variables defined in a function, including its parameters, are not accessible outside the function, and, by default, variables defined outside a function are not accessible inside the function. The following example illustrates this:
$a = 3;

function foo(  ) {
  $a += 2;
}

foo(  );
echo $a;
The variable $a inside the function foo( ) is a different variable than the variable $a outside the variable; even though foo( ) uses the add-and-assign operator, the value of the outer $a remains 3 throughout the life of the page. Inside the function, $a has the value 2.
As we discussed in Chapter 2, the extent to which a variable can be seen in a program is called the scope of the variable. Variables created within a function are inside the scope of the function (i.e., have function-level scope). Variables created outside of functions and objects have global scope and exist anywhere outside of those functions and objects. A few variables provided by PHP have both function-level and global scope.
At first glance, even an experienced programmer may think that in the previous example $a will be 5 by the time the echo statement is reached, so keep that in mind when choosing names for your variables.
If you want a variable in the global scope to be accessible from within a function, you can use the global keyword. Its syntax is:
global var1, var2, ...
Changing the previous example to include a global keyword, we get:
$a = 3;

function foo(  ) {
  global $a;
  $a += 2;
}

foo(  );
echo $a;
Instead of creating a new variable called $a with function-level scope, PHP uses the global $a within the function. Now, when the value of $a is displayed, it will be 5.
You must include the global keyword in a function before any uses of the global variable or variables you want to access. Because they are declared before the body of the function, function parameters can never be global variables.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Function Parameters
Functions can expect, by declaring them in the function definition, an arbitrary number of arguments.
There are two different ways of passing parameters to a function. The first, and more common, is by value. The other is by reference.
In most cases, you pass parameters by value. The argument is any valid expression. That expression is evaluated, and the resulting value is assigned to the appropriate variable in the function. In all of the examples so far, we've been passing arguments by value.
Passing by reference allows you to override the normal scoping rules and give a function direct access to a variable. To be passed by reference, the argument must be a variable; you indicate that a particular argument of a function will be passed by reference by preceding the variable name in the parameter list with an ampersand (&). Example 3-5 revisits our doubler( ) function with a slight change.
Example 3-5. Doubler redux
function doubler(&$value) {
  $value = $value << 1;
}

$a = 3;
doubler($a);
echo $a;
Because the function's $value parameter is passed by reference, the actual value of $a, rather than a copy of that value, is modified by the function. Before, we had to return the doubled value, but now we change the caller's variable to be the doubled value.
Here's another place where a function contains side effects: since we passed the variable $a into doubler( ) by reference, the value of $a is at the mercy of the function. In this case, doubler( ) assigns a new value to it.
A parameter that is declared as being passed by reference can only be a variable. Thus, if we included the statement <?= doubler(7); ?> in the previous example, it would issue an error.
Even in cases where your function does affect the given value, you may want a parameter to be passed by reference. When passing by value, PHP must copy the value. Particularly for large strings and objects, this can be an expensive operation. Passing by reference removes the need to copy the value.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Return Values
PHP functions can return only a single value with the return keyword:
function return_one() {
   return 42;
}
To return multiple values, return an array:
function return_two (  ) {
   return array("Fred", 35);
}
By default, values are copied out of the function. A function declared with an & before its name returns a reference (alias) to its return value:
$names = array("Fred", "Barney", "Wilma", "Betty");
function & find_one($n) {
   return $names[$n];
}
$person =& find_one(1);           // Barney
$person = "Barnetta";             // changes $names[1]
In this code, the find_one( ) function returns an alias for $names[1], instead of a copy of its value. Because we assign by reference, $person is an alias for $names[1], and the second assignment changes the value in $names[1].
This technique is sometimes used to return large string or array values efficiently from a function. However, PHP's copy-on-write/shallow-copy mechanism usually means that returning a reference from a function is not necessary. There is no point in returning a reference to some large piece of data unless you know you are likely to change that data. The drawback of returning the reference is that it is slower than returning the value and relying on the shallow-copy mechanism to ensure that a copy of that data is not made unless it is changed.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Variable Functions
As with variable variables, you can call a function based on the value of a variable. For example, consider this situation, where a variable is used to determine which of three functions to call:
switch($which) {
  case 'first':
    first(  );
    break;

  case 'second':
    second(  );
    break;

  case 'third':
    third(  );
    break;
}
In this case, we could use a variable function call to call the appropriate function. To make a variable function call, include the parameters for a function in parentheses after the variable. To rewrite the previous example:
$which();  // if $which is "first" the function first(  ) is called, etc...
If no function exists for the variable, a runtime error occurs when the code is evaluated. To prevent this, you can use the built-in function function_exists( ) to determine whether a function exists for the value of the variable before calling the function:
$yes_or_no = function_exists(function_name);
For example:
if(function_exists($which)) {
  $which();  // if $which is "first" the function first(  ) is called, etc...
}
Language constructs such as echo( ) and isset( ) cannot be called through variable functions:
$f = 'echo';
$f('hello, world');  // does not work
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Anonymous Functions
Some PHP functions use a function you provide them with to do part of their work. For example, the usort( ) function uses a function you create and pass to it as a parameter to determine the sort order of the items in an array.
Although you can define a function for such purposes, as shown previously, these functions tend to be localized and temporary. To reflect the transient nature of the callback, create and use an anonymous function (or lambda function).
You can create an anonymous function using create_function( ) . This function takes two parameters—the first describes the parameters the anonymous function takes in, and the second is the actual code. A randomly generated name for the function is returned:
$func_name = create_function(args_string, code_string);
Example 3-7 shows an example using usort( ) .
Example 3-7. Anonymous functions
$lambda = create_function('$a,$b', 'return(strlen($a) - strlen($b));');
$array = array('really long string here, boy', 'this', 'middling length', 'larger');
usort($array, $lambda);
print_r($array);
The array is sorted by usort( ), using the anonymous function, in order of string length.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Chapter 4: Strings
Most data you encounter as you program will be sequences of characters, or strings. Strings hold people's names, passwords, addresses, credit-card numbers, photographs, purchase histories, and more. For that reason, PHP has an extensive selection of functions for working with strings.
This chapter shows the many ways to write strings in your programs, including the sometimes-tricky subject of interpolation (placing a variable's value into a string), then covers the many functions for changing, quoting, and searching strings. By the end of this chapter, you'll be a string-handling expert.
There are three ways to write a literal string in your program: using single quotes, double quotes, and the here document (heredoc) format derived from the Unix shell. These methods differ in whether they recognize special escape sequences that let you encode other characters or interpolate variables.
The general rule is to use the least powerful quoting mechanism necessary. In practice, this means that you should use single-quoted strings unless you need to include escape sequences or interpolate variables, in which case you should use double-quoted strings. If you want a string that spans many lines, use a heredoc.
When you define a string literal using double quotes or a heredoc, the string is subject to variable interpolation. Interpolation is the process of replacing variable names in the string with the values of those variables. There are two ways to interpolate variables into strings—the simple way and the complex way.
The simple way is to just put the variable name in a double-quoted string or heredoc:
$who = 'Kilroy';
$where = 'here';
echo "$who was $where";    
Kilroy was here
            
The complex way is to surround the variable being interpolated with curly braces. This method can be used either to disambiguate or to interpolate array lookups. The classic use of curly braces is to separate the variable name from surrounding text:
$n = 12;
echo "You are the {$n}th person";
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Quoting String Constants
There are three ways to write a literal string in your program: using single quotes, double quotes, and the here document (heredoc) format derived from the Unix shell. These methods differ in whether they recognize special escape sequences that let you encode other characters or interpolate variables.
The general rule is to use the least powerful quoting mechanism necessary. In practice, this means that you should use single-quoted strings unless you need to include escape sequences or interpolate variables, in which case you should use double-quoted strings. If you want a string that spans many lines, use a heredoc.
When you define a string literal using double quotes or a heredoc, the string is subject to variable interpolation. Interpolation is the process of replacing variable names in the string with the values of those variables. There are two ways to interpolate variables into strings—the simple way and the complex way.
The simple way is to just put the variable name in a double-quoted string or heredoc:
$who = 'Kilroy';
$where = 'here';
echo "$who was $where";    
Kilroy was here
            
The complex way is to surround the variable being interpolated with curly braces. This method can be used either to disambiguate or to interpolate array lookups. The classic use of curly braces is to separate the variable name from surrounding text:
$n = 12;
echo "You are the {$n}th person";
You are the 12th person
            
Without the curly braces, PHP would try to print the value of the $nth variable.
Unlike in some shell environments, in PHP strings are not repeatedly processed for interpolation. Instead, any interpolations in a double-quoted string are processed, then the result is used as the value of the string:
$bar = 'this is not printed';
$foo = '$bar';     // single quotes
print("$foo");
$bar
            
Single-quoted strings do not interpolate variables. Thus, the variable name in the following string is not expanded because the string literal in which it occurs is single-quoted:
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Printing Strings
There are four ways to send output to the browser. The echo construct lets you print many values at once, while print( ) prints only one value. The printf( ) function builds a formatted string by inserting values into a template. The print_r( ) function is useful for debugging—it prints the contents of arrays, objects, and other things, in a more-or-less human-readable form.
To put a string into the HTML of a PHP-generated page, use echo. While it looks—and for the most part behaves—like a function, echo is a language construct. This means that you can omit the parentheses, so the following are equivalent:
echo "Printy";
echo("Printy");              // also valid
You can specify multiple items to print by separating them with commas:
echo "First", "second", "third";
Firstsecondthird
            
It is a parse error to use parentheses when trying to echo multiple values:
// this is a parse error
echo("Hello", "world");
Because echo is not a true function, you can't use it as part of a larger expression:
// parse error
if (echo("test")) {
  echo("it worked!");
}
Such errors are easily remedied, though, by using the print( ) or printf( ) functions.
The print( ) function sends one value (its argument) to the browser. It returns true if the string was successfully displayed and false otherwise (e.g., if the user pressed the Stop button on her browser before this part of the page was rendered):
if (! print("Hello, world")) {
  die("you're not listening to me!");
}
Hello, world
            
The printf( ) function outputs a string built by substituting values into a template (the format string). It is derived from the function of the same name in the standard C library. The first argument to printf( ) is the format string. The remaining arguments are the values to be substituted in. A % character in the format string indicates a substitution.

Section 4.2.3.1: Format modifiers

Each substitution marker in the template consists of a percent sign (
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Accessing Individual Characters
The strlen( ) function returns the number of characters in a string:
$string = 'Hello, world';
$length = strlen($string);             // $length is 12
You can use array syntax (discussed in detail in Chapter 5) on a string, to address individual characters:
$string = 'Hello';
for ($i=0; $i < strlen($string); $i++) {
  printf("The %dth character is %s\n", $i, $string[$i]);
}
The 0th character is H
            
The 1th character is e
            
The 2th character is l
            
The 3th character is l
            
The 4th character is o
         
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Cleaning Strings
Often, the strings we get from files or users need to be cleaned up before we can use them. Two common problems with raw data are the presence of extraneous whitespace, and incorrect capitalization (uppercase versus lowercase).
You can remove leading or trailing whitespace with the trim( ), ltrim( ), and rtrim( ) functions:
$trimmed = trim(string [, charlist ]);
$trimmed = ltrim(string [, charlist ]);
$trimmed = rtrim(string [, charlist ]);
trim( ) returns a copy of string with whitespace removed from the beginning and the end. ltrim( ) (the l is for left) does the same, but removes whitespace only from the start of the string. rtrim( ) (the r is for right) removes whitespace only from the end of the string. The optional charlist argument is a string that specifies all the characters to strip. The default characters to strip are given in Table 4-3.
Table 4-3: Default characters removed by trim( ), ltrim( ), and rtrim( )
Character
ASCII value
Meaning
" "
0x20
Space
"\t"
0x09
Tab
"\n"
0x0A
Newline (line feed)
"\r"
0x0D
Carriage return
"\0"
0x00
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Encoding and Escaping
Content preview·