BUY THIS BOOK
Add to Cart

Print Book $9.95


Add to Cart

Print+PDF $12.93

Add to Cart

PDF $7.99

Safari Books Online

What is this?

Add to UK Cart

Print Book £6.95

What is this?

Looking to Reprint or License this content?


PHP Pocket Reference
PHP Pocket Reference, Second Edition

By Rasmus Lerdorf
Book Price: $9.95 USD
£6.95 GBP
PDF Price: $7.99

Cover | Table of Contents


Table of Contents

Chapter 1: PHP Pocket Reference
PHP (PHP Hypertext Preprocessor) is a web scripting language. It was specifically designed to solve "the web problem." PHP is easy to learn because it builds on the bits and pieces that most people already know. The pieces that you don't know are filled in by excellent online documentation and many high-quality books. This simple approach to solving the web problem has caught on with an amazing number of people.
This pocket reference further simplifies things by focusing on the absolute essentials. It provides an overview of the main concepts needed for most web applications, followed by quick reference material for most of the main PHP functions.
PHP works with many different web servers in many different ways, but by far the most popular way to run PHP is as an Apache module with Apache 1.3.x. Full installation instructions for all the different ways to install PHP can be found in the PHP documentation. Here, I cover the Apache module installation.
If you are compiling from the PHP source tarball, follow the instructions in the INSTALL file found inside the PHP distribution file. A tarball is a compressed tar file. tar stands for tape archive, but these days it has little to do with tapes. It is simply a way to lump multiple files and directories into a single file for distribution. Normally tarballs have the .tar.gz extension to indicate a tar file compressed with gzip. To untar a tarball, use:
tar zxvf foo.tar.gz
On Windows, many utilities (including WinZip) understand tarballs.
If you are installing from a precompiled binary package such as an rpm file, most of the work should be done for you. But doublecheck that the Apache configuration described below is correct.
When you are using PHP as an Apache module, PHP processing is triggered by a special MIME type. This is defined in the Apache configuration file with a line similar to:
AddType application/x-httpd-php .php
This line tells Apache to treat all files that end with the .php extension as PHP files, which means that any file with that extension is parsed for PHP tags. The actual extension is completely arbitrary and you are free to change it to whatever you wish to 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!
Introduction
PHP (PHP Hypertext Preprocessor) is a web scripting language. It was specifically designed to solve "the web problem." PHP is easy to learn because it builds on the bits and pieces that most people already know. The pieces that you don't know are filled in by excellent online documentation and many high-quality books. This simple approach to solving the web problem has caught on with an amazing number of people.
This pocket reference further simplifies things by focusing on the absolute essentials. It provides an overview of the main concepts needed for most web applications, followed by quick reference material for most of the main PHP functions.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Installation and Configuration
PHP works with many different web servers in many different ways, but by far the most popular way to run PHP is as an Apache module with Apache 1.3.x. Full installation instructions for all the different ways to install PHP can be found in the PHP documentation. Here, I cover the Apache module installation.
If you are compiling from the PHP source tarball, follow the instructions in the INSTALL file found inside the PHP distribution file. A tarball is a compressed tar file. tar stands for tape archive, but these days it has little to do with tapes. It is simply a way to lump multiple files and directories into a single file for distribution. Normally tarballs have the .tar.gz extension to indicate a tar file compressed with gzip. To untar a tarball, use:
tar zxvf foo.tar.gz
On Windows, many utilities (including WinZip) understand tarballs.
If you are installing from a precompiled binary package such as an rpm file, most of the work should be done for you. But doublecheck that the Apache configuration described below is correct.
When you are using PHP as an Apache module, PHP processing is triggered by a special MIME type. This is defined in the Apache configuration file with a line similar to:
AddType application/x-httpd-php .php
This line tells Apache to treat all files that end with the .php extension as PHP files, which means that any file with that extension is parsed for PHP tags. The actual extension is completely arbitrary and you are free to change it to whatever you wish to use.
If you are running PHP as a dynamic shared object (DSO) module, you also need this line in your Apache configuration file:
LoadModule php4_module    modules/libphp4.so
Note that in many default httpd.conf files you will find AddModule lines. These really aren't necessary. They are only needed if you have a ClearModuleList directive somewhere in your httpd.conf file. I would suggest simply deleting the ClearModuleList directive and deleting all your AddModule lines. The idea behind ClearModuleList/AddModule is to make it possible to reorder already loaded modules in case module order is an issue. With most modules, the order that they are loaded -- which governs the order they are called -- is not important. And further, most binary distributions of Apache ship with most modules compiled as dynamically loadable modules, which means that if order is an issue for some reason, you can simply change the order of the
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 HTML
You embed PHP code into a standard HTML page. For example, here's how you can dynamically generate the title of an HTML document:
<html><head><title><?echo $title?></title>
</head>...
The <?echo $title?> portion of the document is replaced by the contents of the $title PHP variable. echo is a basic language statement that you can use to output data.
There are a few different ways to embed your PHP code. As you just saw, you can put PHP code between <? and ?> tags:
<? echo "Hello World"; ?>
This style is the most common way to embed PHP, but it is a problem if your PHP code needs to co-exist with XML, as XML may use that tagging style itself. If this is the case, turn off this style in the php.ini file with the short_open_tag directive. Another way to embed PHP code is within <?php and ?> tags:
<?php echo "Hello World"; ?>
This style is always available and is recommended when your PHP code needs to be portable to many different systems. Embedding PHP within <script> tags is another style that is always available:
<script language="php" > echo "Hello World";
</script>
One final style, in which the code is between <% and %> tags, is disabled by default:
<% echo "Hello World"; %>
You can turn on this style with the asp_tags directive in your php.ini file. The style is most useful when you are using Microsoft FrontPage or another HTML authoring tool that prefers that tag style for HTML-embedded scripts.
You can embed multiple statements by separating them with semicolons:
<?php
  echo "Hello World";
  echo "A second statement";
?>
It is legal to switch back and forth between HTML and PHP at any time. For example, if you want to output 100 <br /> tags for some reason, you can do it this way:
<?php for($i=0; $i<100; $i++) { ?>
  <br />
<?php } ?>
Of course, using the str_repeat( ) function here would make more sense.
When you embed PHP code in an HTML file, you need to use the .php file extension for that file, so that your web server knows to send the file to PHP for processing. Or, if you have configured your web server to use a different extension for PHP files, use that extension instead.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Language Syntax
Variable names in PHP are case-sensitive. That means $A and $a are two distinct variables. However, function names in PHP are not case-sensitive. This rule applies to both built-in functions and user-defined functions.
PHP ignores whitespace between tokens. You can use spaces, tabs, and newlines to format and indent your code to make it more readable. PHP statements are terminated by semicolons.
There are three types of comments in PHP:
/* C style comments */
// C++ style comments
# Bourne shell style comments
The C++ and Bourne shell-style comments can be inserted anywhere in your code. Everything from the comment characters to the end of the line is ignored. The C-style comment tells PHP to ignore everything from the start of the comment until the end-comment characters. This means that this style of comment can span multiple lines.
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
In PHP, all variable names begin with a dollar sign ($). The $ is followed by an alphabetic character or an underscore, and optionally followed by a sequence of alphanumeric characters and underscores. There is no limit on the length of a variable name. Variable names in PHP are case-sensitive. Here are some examples:
$i
$counter
$first_name
$_TMP
In PHP, unlike in many other languages, you do not have to explicitly declare variables. PHP automatically declares a variable the first time a value is assigned to it. PHP variables are untyped; you can assign a value of any type to a variable.
PHP uses a symbol table to store the list of variable names and their values. There are two kinds of symbol tables in PHP: the global symbol table, which stores the list of global variables, and the function-local symbol table, which stores the set of variables available inside each function.
Sometimes it is useful to set and use variables dynamically. Normally, you assign a variable like this:
$var = "hello";
Now let's say you want a variable whose name is the value of the $var variable. You can do that like this:
$$var = "World";
PHP parses $$var by first dereferencing the innermost variable, meaning that $var becomes "hello". The expression that's left is $"hello", which is just $hello. In other words, we have just created a new variable named hello and assigned it the value "World". You can nest dynamic variables to an infinite level in PHP, although once you get beyond two levels, it can be very confusing for someone who is trying to read your code.
There is a special syntax for using dynamic variables, and any other complex variable, inside quoted strings in PHP:
echo "Hello ${$var}";
This syntax also helps resolve an ambiguity that occurs when variable arrays are used. Something like $$var[1] is ambiguous because it is impossible for PHP to know which level to apply the array index to. ${$var[1]} tells PHP to dereference the inner level first and apply the array index to the result before dereferencing the outer level. ${$var}[1], on the other hand, tells PHP to apply the index to the outer level.
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 four primitive data types: integers, floating point numbers, strings, and booleans. In addition, there are two compound data types: arrays and objects.
Integers are whole numbers. The range of integers in PHP is equivalent to the range of the long data type in C. On 32-bit platforms, integer values range from -2,147,483,648 to +2,147,483,647. PHP automatically converts larger values to floating point numbers if you happen to overflow the range. An integer can be expressed in decimal (base-10), hexadecimal (base-16), or octal (base-8). For example:
$decimal=16;
$hex=0x10;
$octal=020;
Floating point numbers represent decimal values. The range of floating point numbers in PHP is equivalent to the range of the double type in C. On most platforms, a double can be between 1.7E-308 to 1.7E+308. A double may be expressed either as a regular number with a decimal point or in scientific notation. For example:
$var=0.017;
$var=17.0E-3
PHP also has two sets of functions that let you manipulate numbers with arbitrary precision. These two sets are known as the BC and the GMP functions. See http://www.php.net/bc and http://www.php.net/gmp for more information.
A string is a sequence of characters. A string can be delimited by single quotes or double quotes:
'PHP is cool'
"Hello, World!"
Double-quoted strings are subject to variable substitution and escape sequence handling, while single quotes are not. For example:
$a="World";
echo "Hello\t$a\n";
This displays "Hello" followed by a tab and then "World" followed by a newline. In other words, variable substitution is performed on the variable $a and the escape sequences are converted to their corresponding characters. Contrast that with:
echo 'Hello\t$a\n';
In this case, the output is exactly "Hello\t$a\n". There is no variable substitution or handling of escape sequences.
Another way to assign a string is to use what is known as the heredoc syntax. The advantage with this approach is that you do not need to escape quotes. It looks like this:
$foo = <<<EOD
  This is a "multiline" string
  assigned using the 'heredoc' syntax.
EOD;
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
An expression is the basic building block of the language. Anything with a value can be thought of as an expression. Examples include:
5
5+5
$a
$a==5
sqrt(9)
By combining many of these basic expressions, you can build larger, more complex expressions.
Note that the echo statement we've used in numerous examples cannot be part of a complex expression because it does not have a return value. The print statement, on the other hand, can be used as part of complex expression -- it does have a return value. In all other respects, echo and print are identical: they output data.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Operators
Expressions are combined and manipulated using operators. The following table lists the operators from highest to lowest precedence; the second column (A) shows the operators' associativity. These operators should be familiar to you if you have any C, Java, or Perl experience.
Operators
A
!, ~, ++, --, @, (the casting operators)
Right
*, /, %
Left
+, -, .
Left
<<, >>
Left
<, <=, >=, >
Nonassociative
==, !=, ===, !==
Nonassociative
&
Left
^
Left
|
Left
&&
Left
||
Left
? : (conditional operator)
Left
=, +=, -=, *=, /=, %=, ^=, .=, &=, |=, <<=, >>=
Left
AND
Left
XOR
Left
OR
Left
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Control Structures
The control structures in PHP are very similar to those used by the C language. Control structures are used to control the logical flow through a PHP script. PHP's control structures have two syntaxes that can be used interchangeably. The first form uses C-style curly braces to enclose statement blocks, while the second style uses a more verbose syntax that includes explicit ending statements. The first style is preferable when the control structure is completely within a PHP code block. The second style is useful when the construct spans a large section of intermixed code and HTML. The two styles are completely interchangeable, however, so it is really a matter of personal preference which one you use.
The if statement is a standard conditional found in most languages. Here are the two syntaxes for the if statement:
if(expr) {            if(expr):
  statements            statements
} elseif(expr) {      elseif(expr):
  statements            statements
} else {              else:
  statements            statements
}                     endif;
The if statement causes particular code to be executed if the expression it acts on is true. With the first form, you can omit the braces if you only need to execute a single statement.
The switch statement can be used in place of a lengthy if statement. Here are the two syntaxes for switch:
switch(expr) {         switch(expr):
  case expr:             case expr:
    statements             statements
    break;                 break;
  default:               default:
    statements             statements
    break;                 break;
}                      endswitch;
The expression for each case statement is compared against the switch expression and, if they match, the code following that particular case is executed. The break keyword signals the end of a particular case; it may be omitted, which causes control to flow into the next case. If none of the case expressions match the switch expression, the default case is executed.
The while statement is a looping construct that repeatedly executes some code while a particular expression is
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Functions
A function is a named sequence of code statements that can optionally accept parameters and return a value. A function call is an expression that has a value; its value is the returned value from the function. PHP provides a large number of internal functions. The "Function Reference" section lists all of the commonly available functions. PHP also supports user-definable functions. To define a function, use the function keyword. For example:
function soundcheck($a, $b, $c) {
  return "Testing, $a, $b, $c";
}
When you define a function, be careful what name you give it. In particular, you need to make sure that the name does not conflict with any of the internal PHP functions. If you do use a function name that conflicts with an internal function, you get the following error:
Fatal error: Can't redeclare already declared function in 
filename on line N
After you define a function, you call it by passing in the appropriate arguments. For example:
echo soundcheck(4, 5, 6);
You can also create functions with optional parameters. To do so, you set a default value for each optional parameter in the definition, using C++ style. For example, here's how to make all the parameters to the soundcheck() function optional:
function soundcheck($a=1, $b=2, $c=3) {
  return "Testing, $a, $b, $c";
}
There are two ways you can pass arguments to a function: by value and by reference. To pass an argument by value, you pass in any valid expression. That expression is evaluated and the value is assigned to the corresponding parameter defined within the function. Any changes you make to the parameter within the function have no effect on the argument passed to the function. For example:
function triple($x) {
  $x=$x*3;
  return $x;
}
$var=10;
$triplevar=triple($var);
In this case, $var evaluates to 10 when triple() is called, so $x is set to 10 inside the function. When $x is tripled, that change does not affect the value of $var outside the function.
In contrast, when you pass an argument by reference, changes to the parameter within the function do affect the value of the argument outside the scope of the function. That's because when you pass an argument by reference, you must pass a variable to the function. Now the parameter in the function refers directly to the value of the variable, meaning that any changes within the function are also visible outside the function. For example:
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Web-Related Variables
PHP automatically creates variables for all the data it receives in an HTTP request. This can include GET data, POST data, cookie data, and environment variables. The variables are either in PHP's global symbol table or in one of a number of superglobal arrays, depending on the value of the register_globals setting in your php.ini file.
In PHP 4.2.0 and after, the default setting for register_globals is off. With register_globals off, all the various variables that are usually available directly in the global symbol table are now available via individual superglobal arrays. There is a limited set of superglobals and they cannot be created from a user-level script. The superglobal array to use depends on the source of the variable. Here is the list:
$_GET
GET-method variables. These are the variables supplied directly in the URL. For example, with http://www.example.com/script.php?a=1&b=2, $_GET['a'] and $_GET['b'] are set to 1 and 2, respectively.
$_POST
POST-method variables. Form field data from regular POST-method forms.
$_COOKIE
Any cookies the browser sends end up in this array. The name of the cookie is the key and the cookie value becomes the array value.
$_REQUEST
This array contains all of these variables (i.e., GET, POST, and cookie). If a variable appears in multiple sources, the order in which they are imported into $_REQUEST is given by the setting of the variables_order php.ini directive. The default is 'GPC', which means GET-method variables are imported first, then POST-method variables (overriding any GET-method variables of the same name), and finally cookie variables (overriding the other two).
$_SERVER
These are variables set by your web server. Traditionally things like DOCUMENT_ROOT, REMOTE_ADDR, REMOTE_PORT, SERVER_NAME, SERVER_PORT, and many others. To get a full list, have a look at your phpinfo( ) output, or run a script like the following to have a look:
<?php
  foreach($_SERVER as $key=>$val) {
    echo '$_SERVER['.$key."] = $val<br>\n";
  }
?>
$_ENV
Any environment variables that were set when you started your web server are available in this array.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Sessions
Sessions are used to help maintain the values of variables across multiple web pages. This is done by creating a unique session ID that is sent to the client browser. The browser then sends the unique ID back on each page request and PHP uses the ID to fetch the values of all the variables associated with this session.
The session ID is sent back and forth in a cookie or in the URL. By default, PHP tries to use cookies, but if the browser has disabled cookies, PHP falls back to putting the ID in the URL. The php.ini directives that affect this are:
session.use_cookies
When on, PHP will try to use cookies
session.use_trans_sid
When on, PHP will add the ID to URLs if cookies are not used
The trans_sid code in PHP is rather interesting. It actually parses the entire HTML file and modifies/mangles every link and form to add the session ID. The url_rewriter.tags php.ini directive can change how the various elements are mangled.
Writing an application that uses sessions is not hard. You start a session using session_start( ), then register the variables you wish to associate with that session. For example:
<?php
  session_start( );
  session_register('foo');
  session_register('bar');

  $foo = "Hello";
  $bar = "World";
?>
If you put the previous example in a file named page1.php and load it in your browser, it sends you a cookie and stores the values of $foo and $bar on the server. If you then load this page2.php page:
<?php
  session_start( );
  echo "foo = $_SESSION[foo]<br />";
  echo "bar = $_SESSION[bar]<br />";
?>
You should see the values of $foo and $bar set in page1.php. Note the use of the $_SESSION superglobal. If you have register_globals on, you would be able to access these as $foo and $bar directly.
You can add complex variables such as arrays and objects to sessions as well. The one caveat with putting an object in a session is that you must load the class definition for that object before you call session_start( ).
A common error people make when using sessions is that they tend to use it as a replacement for authentication -- or sometimes as an add-on to authentication. Authenticating a user once as he first enters your site and then using a session ID to identify that user throughout the rest of the site without further authentication can lead to a lot of problems if another person is somehow able to get the session ID. There are a number of ways to get the session ID:
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Examples
The best way to understand the power of PHP is to examine some real examples of PHP in action, so we'll look at some common uses of PHP in this section.
Here is a simple page that prints out the browser string and the IP address of the HTTP request. Create a file with the following content in your web directory, name it something like example.php3, and load it in your browser:
<html><head><title>PHP Example</title></head>
<body>
   You are using 
    <?php echo $_SERVER['HTTP_USER_AGENT'] ?>
   <br />
   and coming from 
    <?php echo $_SERVER['REMOTE_ADDR'] ?>
</body></html>
You should see something like the following in your browser window:
You are using Mozilla/5.0 (X11; U; Linux i686; en-US; 
rv:1.1b) Gecko/20020722
and coming from 127.0.0.1
Here is a slightly more complex example. We are going to create an HTML form that asks the user to enter a name and select one or more interests from a selection box. We could do this in two files, where we separate the actual form from the data handling code, but instead, this example shows how it can be done in a single file:
<html><head><title>Form Example</title></head>
<body>
<h1>Form Example</h1>
<?
function show_form($first="", $last="", 
                   $interest="") {
 $options = array("Sports", "Business", "Travel", 
                  "Shopping", "Computers");
 if(!is_array($interest)) $interest = array( );
 ?>
 <form action="form.php" method="POST">
 First Name:
 <input type="text" name="first" 
        value="<?echo $first?>">
 <br />
 Last Name:
 <input type="text" name="last" 
        value="<?echo $last?>">
 <br />
 Interests:
 <select multiple name="interest[ ]">
 <?php
  foreach($options as $option) {
   echo "<option";
   if(in_array($option, $interest)) {
    echo " selected ";
   }
   echo "> $option</option>\n";
  }
 ?>
 </select><br />
 <input type=submit>
 </form>
<?php } // end of show_form( ) function

if($_SERVER['REQUEST_METHOD']!='POST') {
 show_form( );
} else {
 if(empty($_POST['first']) || 
    empty($_POST['last'])  ||
    empty($_POST['interest'])) {
  echo "<p>You did not fill in all the fields,";
  echo "please try again</p>\n";
  show_form($_POST['first'],$_POST['last'], 
            $_POST['interest']);
 }
 else {
  echo "<p>Thank you, $_POST[first] $_POST[last], you ";
  echo 'selected '. 
       join(' and ', $_POST['interest']);
  echo " as your interests.</p>\n";
 }
}
?>
</body></html>
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 Reference
The rest of this book provides an alphabetical summary of the functions that are available in PHP. The synopsis for each function lists the expected argument types for the function, its return type, and the version of PHP in which the function was introduced. The possible types are int, double, string, array, void, and mixed. mixed means that the argument or return type can be of any type. Optional arguments are shown in square brackets. Note that PHP didn't start tracking version numbers for functions until PHP 3.0, so functions that are listed as 3.0 are likely to have existed in Version 2.x.
As of PHP 4.3, approximately 2,750 functions came bundled with PHP. The bulk of these are in optional extensions. Out of these functions, I selected 1,404 for this pocket reference. Even with close to half the functions cut, I'm still pushing the limits of what the average pocket can hold without busting a few seams. Here's a list of the function groups that survived the cut, followed by the ones that didn't:
In
Apache, array, assert, aspell/pspell, base64, bcmath, bz2, calendar, crack, crc32, crypt, ctype, curl, date/time, dba, db, dbx, directory, DNS, exec, exif, file, ftp, gd, gettext, gmp, HTML, iconv, imap, iptc, java, lcg, ldap, link, mail, math, md5, mbstring, mcrypt, mhash, MySQL, Oracle 8, PDF, Perl regex, PostgreSQL, Posix, process control, recode, session, shmop, snmp, sockets, various standard built-in, syslog, SYSV shared mem/sem/msg, xml, xslt, zip, zlib.
Out
COM, cpdf, Cybercash, Cybermut, Cyrus, dbase, direct io, DomXML, Frontbase, FDF, Filepro, Fribidi, Hyperwave, ICAP, Informix, Ingres, Interbase, ircg, mbregex, MCAL, MCVE, Ming, mnogosearch, msession, mSQL, mssql, ncurses, Lotus Notes, Birdstep, ODBC, OpenSSL, Oracle 7, Ovrimos, Payflow Pro, QTDom, readline, aggregation, browscap, cyrillic conversions, libswf, Sybase, Tokenizer, VPopMail, Win32 API, WDDX, XMLRPC, Yaz, YellowPages.
If your favorite functions were left out, please don't take it personally. I had a lot of tough choices to make. One of the hardest was DomXML. At 114 functions, the DomXML extension is huge and there just wasn't room. Leaving out the cool Ming functions was difficult as well. Please do check out the online manual at
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 to PHP Pocket Reference