PHP Cookbook/PEAR

From WikiContent

< PHP Cookbook(Difference between revisions)
Jump to: navigation, search
m (1 revision(s))
Current revision (13:36, 7 March 2008) (edit) (undo)
(Initial conversion from Docbook)

Current revision

PHP Cookbook



PEAR is the PHP Extension and Application Repository, a collection of open source classes that work together. Developers can use PEAR classes to generate HTML, make SOAP requests, send MIME mail, and a variety of other common tasks. A pear is also a tasty fruit.

To find general information on PEAR, read the PEAR manual; to discover the latest PEAR packages, go to A summary of each week's happenings can be found at

Only a few core PEAR packages are bundled with the main PHP release. However, part of PEAR is a program called, appropriately enough, pear , that makes it easy for you to download and install additional PEAR packages. This program is also known as the PEAR package manager. Recipe 21.2 shows how to use the PEAR package manager.

PEAR packages divide into two major parts. One is the PHP Foundation Classes — object-oriented code written in PHP that's high quality and usable in production environments on any platform and web server. The other is PECL, or PHP Extension Code Library. PECL, pronounced pickle, is a series of extensions to PHP written in C. These extensions are just like ones distributed with the main PHP release, but they're of more specialized interest — such as an interface to the XMMS multimedia player or the ImageMagick graphics library.

Additionally, the PEAR package manager allows you to use the PEAR class management infrastructure with your personal projects. By creating your own packages that follow the PEAR format, your users can use pear to download and install the files from your project's web site.

This chapter explains how to find a PEAR package you may want to use and how to install it on your machine. Because PEAR has many classes, you need an easy way to browse them. Recipe 21.3 covers the different ways to find PEAR packages; once you've found a package's name, Recipe 21.4 shows how to view package details and information.

Once you locate a class you want to use, you need to run pear to transfer the class to your machine and install it in the correct location on your server. Installing PEAR packages and PECL extensions are the subjects of Recipe 21.5 and Recipe 21.6, respectively. Recipe 21.7 shows how discover if any upgrades are available to packages on your machine and how to install the latest versions. If you want to remove a package, see Recipe 21.8.

Finally, Recipe 21.9 describes how PEAR developers can write classes that abide by PEAR's coding standards and how to document your class with PHPDoc.

PHP 4.3 includes the first stable release of PEAR. Earlier copies of PHP bundled versions of PEAR prior to PEAR 1.0, but pear and the other packages weren't guaranteed to work, as they were still in beta. If you are having problems using PEAR, you should remove any old files that may be interfering with the release version. This includes the pear application itself; it can't always upgrade itself to the latest release.

If you can't upgrade to PHP 4.3 and need to bootstrap a copy of PEAR onto your system, run the following:

% lynx -source | php -q
Welcome to go-pear!

Go-pear will install the 'pear' command and all the files needed by
it.  This command is your tool for PEAR installation and maintenance.

Go-pear also lets you download and install the PEAR packages bundled
with PHP: DB, Net_Socket, Net_SMTP, Mail, XML_Parser.

If you wish to abort, press Control-C now, or press Enter to continue:

This downloads a PHP script from the PEAR web site and hands it to PHP for execution. The program downloads all files needed to run pear and gets you up and running.

On some Unix systems, you may need to run links instead of lynx. If you have the command-line version of PHP installed, remove the -q flag to PHP; the CLI version automatically suppresses HTTP headers. If go-pear seems to hang, set output_buffering to off in your php.ini configuration file.

Installation on Windows is a two-step process:

C:\> php-cli -r 'readfile("");' > go-pear
c:\> php-cli go-pear

The go-pear script requires PHP 4.1 or greater. For the Windows installation, php-cli is the command-line version of PHP.

PHP installs PEAR by default, so if you're running PHP 4.3, you should be able to use PEAR without any additional setup.[1] Out of the box, PEAR installs pear in the same directory as php and places PEAR packages in prefix/lib/php.[2] To install PEAR in another directory, add --with-pear=DIR when configuring PHP.

Once a PEAR package is installed, use it in your PHP scripts by calling require. For example, here's how to include the Net_Dig package:

require 'Net/Dig.php';

If a package name contains an underscore, replace it with a slash, and add .php to the end.

Some packages may require you to include multiple classes, such as SOAP, so instead of requiring SOAP.php, you include SOAP/Client.php or SOAP/Server.php. Read the documentation to discover if a particular package requires nonstandard file includes.

Because PEAR packages are included as regular PHP files, make sure the directory containing the PEAR classes is in your include_path. If it isn't, include and require can't find PEAR classes.

To view instructions and examples showing how to use a particular PEAR class, check the PEAR Manual at or read the top section of the package's PHP files. For an example of a full-featured PEAR class in action, see the discussion of PEAR's database library in Recipe 10.4.

Using the PEAR Package Manager


You want to use the PEAR package manager, pear. This allows you to install new packages, and upgrade and get information about your existing PEAR packages.


To execute a command with the PEAR package manager, type the command name as the first argument on the command line:

% pear 


Here's how to list all installed PEAR packages with the list command:[3]

% pear list
Installed packages:
=  ==  ==  ==  ==  ==  ==  ==  ==  ==
| Package         | Version  | State  |
| Archive_Tar     | 0.9      | stable |
| Console_Getopt  | 0.11     | beta   |
| DB              | 1.3      | stable |
| HTTP            | 1.2      | stable |
| Mail            | 1.0.1    | stable |
| Mail_Mime       | 1.2.1    | stable |
| Net_SMTP        | 1.0      | stable |
| Net_Socket      | 1.0.1    | stable |
| Net_URL         | 1.0.4    | stable |
| PEAR            | 0.91-dev | beta   |
| XML_Parser      | 1.0      | stable |
| XML_RPC         | 1.0.3    | stable |

For a list of all valid PEAR commands, use list-commands . Many commands also have abbreviated names; for example, list is also just l. These names are usually the first few letters of the command name. See Table 21-1 for a list of frequently used commands.

Table 21-1. PEAR package manager commands

Command name Shortcut Description
install i Download and install packages
upgrade up Upgrade installed packages
uninstall un Remove installed packages
list l List installed packages
list-upgrades lu List all available upgrades for installed packages
search None Search for packages

pear has commands both for using and for developing PEAR classes; as a result, you may not need all the commands. The package command, for example, creates a new PEAR package. If you only run other peoples' packages, you can safely ignore this command.

Like all programs, if you want to run pear, you must have permission to execute it. If you can run pear while running as root, but not as a regular user, make sure the group- or world-execute bit is set. Similarly, for some actions, pear creates a lock file in the directory containing the PEAR files. You must have write permission to the file named .lock located in that directory.

To find where your PEAR packages are located, run the config-get php_dir command. You can check the value of the include_path by calling ini_get('include_path') from within PHP or by looking at your php.ini file. If you can't alter php.ini because you're in a shared hosting environment, add the directory to the include_path at the top of your script before including the file. See Recipe 8.24 for more on setting configuration variables from within PHP.

If you're behind a HTTP proxy server, configure PEAR to use it with the command:

% pear config-set http_proxy

You can configure PEAR package manager settings using:

% pear set-config 
               setting value

Here setting is the name of the parameter to modify and value is the new value. To see all your current settings, use the config-show command:

% pear config-show
=  ==  ==  ==  ==  ==  ==  =
| PEAR executables    | bin_dir         | /usr/local/bin                      |
| directory           |                 |                                     |
| PEAR documentation  | doc_dir         | /usr/local/lib/php/docs             |
| directory           |                 |                                     |
| PHP extension       | ext_dir         | /usr/local/lib/php/extensions/no-de |
| directory           |                 | bug-non-zts-20020429                |
| PEAR directory      | php_dir         | /usr/local/lib/php                  |
| PEAR data directory | data_dir        | /usr/local/lib/php/data             |
| PEAR test directory | test_dir        | /usr/local/lib/php/tests            |
| HTTP Proxy Server   | http_proxy      | <not set>                           |
| Address             |                 |                                     |
| PEAR server         | master_server   |                        |
| PEAR password (for  | password        | <not set>                           |
| maintainers)        |                 |                                     |
| PEAR username (for  | username        | <not set>                           |
| maintainers)        |                 |                                     |
| Preferred Package   | preferred_state | stable                              |
| State               |                 |                                     |
| Unix file mask      | umask           | 18                                  |
| Debug Log Level     | verbose         | 1                                   |

For a brief description of each configuration option, use the config-help command.

Finding PEAR Packages


You want a listing of PEAR packages. From this list you want to learn more about each package and decide if you want to install the package.


Browse packages at or search for packages at Use pear 's remote-list command to get listing of PEAR packages or the search command to search for packages.


There are a few ways to review PEAR's packages. First, to browse the listings in a directory-style fashion, go to From there you can burrow into each individual PEAR category.

Alternatively, you can search through the listings at The search page allows you to search by package name, author, category, and release date.

You can ask the PEAR package manager to provide you with a listing using the remote-list command:

% pear remote-list
Available packages:
=  ==  ==  ==  ==  ==  ==  ==  ==  ==
| Package              | Version |
| Archive_Tar          | 0.9     |
| Auth                 | 1.0.2   |


| XML_Transformer      | 0.3     |
| XML_Tree             | 1.1     |

The short form of remote-list is rl.

To search for package names from the command line, use the search command:

% pear search auth
Matched packages:
=  ==  ==  ==  ==  ==  ==  ==  ==
| Package   | Latest | Local |                                    |
| Auth      | 1.0.2  | 1.0.2 | Creating an authentication system. |
| Auth_HTTP | 1.0.1  | 1.0.1 | HTTP authentication for PHP        |

This does a case-insensitive search of package names and returns the package name, the latest version number, the version you have installed (if any), and a short description about the package.

See Also

Recipe 21.4 to find out more information about a package.

Finding Information About a Package


You want to gather information about a package, such a description of what it does, who maintains it, what version you have installed, and which license it's released under.


If the package is installed on your machine, use the PEAR package manager's info command:

% pear info Net_URL

Otherwise, use the remote-info command:

% pear remote-info SOAP

You can also view the package's home page on


The info command provides summary information about a package:

% pear info Net_URL
About Net_URL-1.0.4
=  ==  ==  ==  ==  ==  ==  ==  ==  ==
| Package         | Net_URL                                 |
| Summary         | Easy parsing of Urls                    |
| Description     | Provides easy parsing of URLs and their |
|                 | constituent parts.                      |
| Maintainers     | Richard heyes <> (lead)  |
| Version         | 1.0.4                                   |
| Release Date    | 2002-07-27                              |
| Release License | BSD                                     |
| Release State   | stable                                  |
| Release Notes   | License change                          |
| Last Modified   | 2002-08-23                              |

If you don't have the package installed, ask the remote server for a description:

% pear remote-info Net_URL
Package details:
=  ==  ==  ==  ==  ==  ==  ==  =
| Latest      | 1.0.4                                   |
| Installed   | 1.0.4                                   |
| Package     | Net_URL                                 |
| License     | BSD                                     |
| Category    | Networking                              |
| Summary     | Easy parsing of Urls                    |
| Description | Provides easy parsing of URLs and their |
|             | constituent parts.                      |

This request displays a slightly different set of information. It doesn't include the release data but does include the general PEAR category and the latest version number for the package.

The package home page provides a more complete view and also provides links to earlier releases, a change log, and browseable access to the CVS repository. You can also view package download statistics. Figure 21-1 shows a sample package information page.

Figure 21-1. Net_URL Package Information page on PEAR web site

Net_URL Package Information page on PEAR web site

See Also

Recipe 21.3 to search for packages.

Installing PEAR Packages


You want to install a PEAR package.


Download and install the package from your PEAR server using the PEAR package manager:

% pear install 

You can also install from any location on the Internet:

% pear install

Here's how to install if you have a local copy of a package:

% pear install 


To install PEAR packages, you need write permission where the packages are stored; this defaults to /usr/local/lib/php/.

You can also request multiple packages at the same time:

% pear install HTML_Common HTML_Javascript
downloading HTML_Common-1.0.tgz ...
...done: 2,959 bytes
install ok: HTML_Common 1.0
downloading HTML_Javascript-1.0.0.tgz ...
...done: 4,141 bytes
install ok: HTML_Javascript 1.0.0

When installing a package, PEAR checks that you have all the necessary PHP functions and PEAR packages the new package depends on. If this check fails, PEAR reports on the dependencies:

% pear install HTML_Table
downloading HTML_Table-1.1.tgz ...
...done: 5,168 bytes

requires package `HTML_Common' >= 1.0
HTML_Table: dependencies failed

To fix this problem, download and install the missing packages first. If you want to ignore these dependencies, force installation with -n or --nodeps. You can then later install the required package.

See Also

Recipe 21.6 for information on installing PECL packages; Recipe 21.7 for more on upgrading an existing package; Recipe 21.8 to uninstall a package.

Installing PECL Packages


You want to install a PECL package; this builds a PHP extension written in C to use inside PHP.


Make sure you have all the necessary extension libraries and then use the PEAR package manager install command:

% pear install xmms

To use the extension from PHP, load it using dl( ) :



The frontend process for installing PECL packages is just like installing PEAR packages for code written in PHP. However, the behind-the-scenes tasks are very different. Because PECL extensions are written in C, the package manager needs to compile the extension and configure it to work with the installed version of PHP. As a result, at present, you can build PECL packages on Unix machines and on Windows machines if you use MSDev.

Unlike PHP-based PEAR packages, PECL extensions don't automatically inform you when you lack a library necessary to compile the extension. Instead, you are responsible for correctly preinstalling these files. If you are having trouble getting a PECL extension to build, check the README file and the other documentation that comes with the package. The package manager installs these files inside the docs directory under your PEAR hierarchy.

When you install a PECL extension, the PEAR package manager downloads the file, extracts it, runs phpize to configure the extension for the version of PHP installed on the machine, and then makes and installs the extension. It may also prompt you for the location of libraries:

% pear install xmms
downloading xmms-0.2.tgz ...
...done: 11,968 bytes
4 source files, building
running: phpize
PHP Api Version        : 20020307
Zend Module Api No     : 20020429
Zend Extension Api No  : 20020731
Xmms library install dir? [autodetect] : 
building in /var/tmp/pear-build-adam/xmms-0.2
running: /tmp/pearKIv63P/xmms-0.2/configure --with-xmms
running: make copied to /tmp/pearKIv63P/xmms-0.2/
install ok: xmms 0.2

If these libraries are in a standard location, hitting Return selects the autodetect option. PHP then searches for the libraries and selects them; you don't need to enter an explicit pathname, as in the case of the xmms library shown earlier.

PECL extensions are stored in different places than non-PECL packages. If you want to run pear, you must be able to write inside the PHP extensions directory. Some PECL packages, such as xmms, install files in the same directory as the PHP binary. Because of this, you may want to install these packages while running as the same user you used to install PHP. Also, check the execute permissions of these files; because most PEAR files aren't executable, your umask may not provide those executable files with the correct set of permissions.

See Also

Recipe 21.5 for information on installing PEAR packages; Recipe 21.7 for more on upgrading an existing package; Recipe 21.8 to uninstall a package.

Upgrading PEAR Packages


You want to upgrade a package on your system to the latest version for additional functionality and bug fixes.


Find out if any upgrades are available and then tell pear to upgrade the packages you want:

% pear list-upgrades
% pear upgrade 


Upgrading to a new version of a package is a simple task with the PEAR Package Manager. If you know a specific package is out of date, you can upgrade it directly. However, you may also want to just periodically check to see if any new releases are available.

To do this, user the list-upgrades command, which prints out a table showing package names, the new version number, and the size of the download:

% pear list-upgrades
Available Upgrades (stable):
=  ==  ==  ==  ==  ==  ==  ==  ==  ==  ==  ==  ==  ==  =
| Package     | Version | Size   |
| Archive_Tar | 0.9     | 8.9kB  |
| Auth        | 1.0.2   | 8.8kB  |
| Auth_HTTP   | 1.0.1   | 1.7kB  |
| DB          | 1.3     | 58kB   |
| HTTP        | 1.1     | 2.9kB  |
| Mail        | 1.0.1   | 11.6kB |
| Mail_Mime   | 1.2.1   | 15.0kB |
| Net_Ping    | 1.0.1   | 2.1kB  |
| Net_SMTP    | 1.0     | 2.8kB  |
| Net_Socket  | 1.0.1   | 3.5kB  |
| PEAR        | 0.9     | 40kB   |
| XML_Parser  | 1.0     | 4.8kB  |
| XML_RPC     | 1.0.3   | 11.9kB |
| XML_RSS     | 0.9.1   | 3.1kB  |
| XML_Tree    | 1.1     | 4.7kB  |

If you're up to date, pear prints:

No upgrades available

To upgrade a particular package, use the upgrade command. For example:

% pear upgrade DB
downloading DB-1.3.tgz ...
...done: 59,332 bytes

The short command for list-upgrades is lu; for upgrade it's up.

PEAR also has an RSS feed listing new packages available at

See Also

Recipe 21.5 and Recipe 21.6 for information on installing PEAR and PECL packages; Recipe 21.8 to uninstall a package; Recipe 12.12 for more on parsing RSS feeds.

Uninstalling PEAR Packages


You wish to remove a PEAR package from your system.


The uninstall command tells the PEAR package manager to delete packages:

% pear uninstall HTML_Common
uninstall HTML_Common ok


Uninstalling a package removes it completely from your system. If you want to reinstall it, you must begin as if the package was never installed. PEAR doesn't warn you if you try to remove a package that's dependent on another package, so be careful when you uninstall.

There is no way to automatically roll back an upgrade to an earlier version of a package using uninstall. Also, PEAR complains if you try to install an earlier version over a later one. To force PEAR to overwrite a newer version, use install -f or install --force:

% pear install --force Net_URL
downloading Net_URL-1.0.4.tgz ...
...done: 3,540 bytes
install ok: Net_URL 1.0.4

The short command for uninstall is un.

See Also

Recipe 21.5 and Recipe 21.6 for information on installing PEAR and PECL packages.

Documenting Classes with PHPDoc


You want to be able to integrate documentation with your code.


Use PHPDoc. This allows PEAR to accurately list your class, and you can use the PHPDoc tools to automatically generate API documentation in HTML and XML.

PHPDoc syntax is based on Javadoc. The following tags are available for use: @access , @author, @package, @param, @return, @since, @var, and @version.

You can then use PEAR's PHPDoc utility to generate documentation.


PHPDoc has a special inline documentation style. By formatting your comments in a particular way, the PHPDoc script can parse your code to not only generate which parameters a function take and what type of variable it returns, but also associate comments and other useful information with objects, functions, and variables.

PHPDoc comments are based on the same formatting and naming conventions as Javadoc. So, to flag a comment block to grab PHPDoc's attention, use a traditional C-style comment but use two asterisks after the opening slash:

* This is a PHPDoc comment block

Inside of a block, certain keywords have special meaning. These keywords all begin with an at sign. Table 21-2 lists the keywords and what they stand for.

Table 21-2. PHPDoc keywords

Keyword Meaning
@access Method access: public or private
@author Package author
@package Package name
@param Function parameter
@return Function return value
@see See also reference
@since Debut version of PHP
@var Object variable
@version Package release number

A more fully fleshed out example looks like this:

* Example_Class is a sample class for demonstrating PHPDoc
* Example_Class is a class that has no real actual code, but merely
* exists to help provide people with an understanding as to how the
* various PHPDoc tags are used.
* Example usage:
* if (Example_Class::example()) {
*    print "I am an example.";
* }
* @package  Example
* @author   David Sklar <>
* @author   Adam Trachtenberg <>
* @version  $Revision: 1.6 $
* @access   public
* @see
class Example extends PEAR
    * returns the sample data
    * @param  string  $sample the sample data
    * @return array   all of the exciting sample options
    * @access private
    function _sampleMe($sample)

Any text following a keyword is treated as the value assigned to it. So, in this example, the value of @package is "Example." It can be okay to have two instances of the same keyword, depending upon the situation. For instance, it's perfectly legal to have multiple @param keywords, but it's illegal to have multiple @return keywords.

PHPDoc and the PEAR web site use this information to generate hyperlinked references, so it's important to use a consistent naming scheme, or the cross-references won't work correctly.

To generate PHPDoc, first install the PHPDoc PEAR package. Inside that package is a program named phpdoc ; run it from the command line, and use the -s flag to pass in the directory of the source files. By default, documentation is generated in /usr/local/doc/pear/, so be sure the phpdoc program has write permission to that location, or use -d to alter the destination directory.

To permanently modify the default values, edit the values at the top of the script. Pass -h for a listing of all possible command-line parameters.

PHPDoc isn't very efficient, so be patient. Generating documentation may take a while, depending upon the size of your files. A faster program is currently under development.

See Also

PEAR coding standards at; PHPDoc at


  1. If you disable building the command-line version of PHP with --disable-cli, PHP doesn't install PEAR.
  2. This is probably /usr/local/lib/php.
  3. In early versions of pear, this command was list-installed.
Personal tools