Getting Started with PEAR – PHP’s Low Hanging Fruit

Share this article

The last time you built an application with PHP, how much time did you spend plumbing?

“Plumbing?!?” you cry. “I was writing code, not fixing the drain!”

What I’m really talking about is this: in your last PHP project, how much time did you spend writing code that had been done before? Did you develop a complete user authentication system? How long did it take you to build that menu system? Did you struggle to send HTML emails with PHP? You know — all those things that have been done time and again in PHP.

In this article, I’ll be introducing you to PEAR, which, in short, helps you avoid becoming a plumber, and focus instead on getting projects done on time. On the menu today:

  • Why pick PEAR? Keep the doctor away!
  • A Short History: Of PEAR and confusion
  • Installing PEAR: Get up and running
  • The Package Manager: Finding your way around
  • Instant RSS: Feed yourself with PEAR
Why Pick PEAR?

Your client asks you to build an online shop. Where do you begin? With budget and time constraints in mind, the less effort you expend reinventing wheel the better.

PHP comes with loads of built in functionality, like htmlentities() and strip_tags(), which do a lot to make building Web applications easier, but you won’t find functions like shopping_cart(), for obvious reasons.

The more time you spend writing “plumbing code” — stuff that could apply to many Web applications — the greater the risk of your project missing deadlines or going over-budget.

Enter: PEAR. Although images of fruit come to mind, PEAR actually stands for “The PHP Extension and Application Repository” and is touted as “a framework and distribution system for reusable PHP components.” Put another way, PEAR provides the plumbing you need to finish your project on time.

Taking a step back; one way to characterize source code is to consider it in terms of the domain it applies to, as described here.

PEAR primarily targets the “Architecture Domain”: code that can be re-used in many applications, but targets a particular architecture (namely, Web applications). The majority of the “packages” provided by PEAR solve specific problems that are commonly encountered by those building Web apps, irrespective of the type site being built.

For example, PEAR::Validate provides a library of common validation routines, helping you to validate anything from a URL (very important if you want to prevent XSS exploits) to International Bank Account Numbers (IBAN). You could easily find reasons to re-use PEAR::Validate in all sorts of applications, saving yourself a lot of effort and avoiding the possibility that your alternative — a regular expression — has a nasty hole in it (because there was no time for careful testing).

A Short History

If you want to observe “wild and varied reactions”, mention PEAR to a crowd a PHP developers. As a subject for debate, it provokes all kinds of responses, and it quickly becomes apparent that there’s some confusion surrounding PEAR.

The PEAR project began in the mind of Stig Bakken (who’s name you’ve probably run into via the PHP Manual). Legend has it that Stig wanted to create something like Perl’s CPAN (a massive repository of re-usable Perl solutions) for PHP.

Work on PEAR began in November, 1999, with the beginnings of what is probably PEAR’s most widely used package, PEAR::DB. Over the next three years, a small community of contributors grew up around PEAR, gradually shaping it into its first Public Release (1.0) in January, 2003.

In fact, “Public Release” is rather a misnomer. As with many Open Source projects, PEAR’s development was always “public”, via the PHP CVS servers, while the PEAR Website first showed up in October 2000, albeit “under construction”. This may inadvertently have set expectations too early. To talk about a “release” of PEAR may also be little confusing; PEAR::DB, for example, was available ahead of time, as a stable release, in April 2002 (version 1.2). PEAR is, after all, not a single entity, but an infrastructure for code distribution and the all libraries (or packages) stored in the repository.

The end effect was that we had developers who knew what was going on with PEAR, talking about it as far back as May 2001 (An Introduction to PEAR), while the rest of us were left somewhat baffled.

What the Public Release really signified was the first stable release of the PEAR Installer and Package Manager (the infrastructure), which make it really easy to fetch packages from PEAR, as we’ll see shortly. The Release was also an invitation to all to give PEAR a go.

Another confusing aspect of PEAR raises this question: “If PEAR really is a repository for PHP code, why does it have an installer?” Everyone knows, from Hotscripts, that to install a PHP application, you just unzip and go, right? That’s very true; PHP code is generally very easy to deploy. But how often have you run into error messages like this: “Failed opening ‘lib/someClass.php’ for inclusion”, when using third party PHP code (because PHP couldn’t find someClass.php in your include_path)? PEAR has a standard approach to providing off-the-shelf PHP components, which uses a fixed include path. What that means, so long as your have PEAR set up correctly, is that including PEAR::Cache_Lite, for example, can always be accomplished with the following:

require_once 'Cache/Lite.php';

What about when you’re mixing numerous external libraries into your application? Do all the different coding styles mix well? What do you do when some Open Source project you rely on, starts generating all sorts of error messages, thanks to a PHP upgrade? Is the owner still supporting it? That’s not to mention all those other PHP “gotchas”, like magic_quotes and register_globals.

There are a lot of experienced PHP developers contributing to PEAR and, with the help of user feedback, bug fixing is relatively quick with issues like magic_quotes ironed out speedily, if they happen at all. There’s also a willingness to pick up slack, so if one of PEAR’s contributors drops out, the package will usually be handed on to someone else.

There are also signs that, despite being inspired by Perl’s CPAN, the PEAR team are aiming at a more integrated library — something more Java-like. For example, PEAR::DB_DataObject (as you’ve seen before on SitePoint here) provides a database persistence layer, allowing you to treat tables like objects and, for the most part, forget SQL. DB_DataObject uses PEAR::DB to make the real calls to your database, allowing you to benefit from the functionality it provides, no matter what database engine you’re using. Also, the new PEAR Package Proposal System (PEPr) provides a level screening of what code gets into PEAR in the first place. Not quite the Java Community Process, but a step in the right direction.

The question of how PEAR packages are designed leads to a discussion that divides many PHP developers. Search around (perhaps on the SitePoint Forums) and you’ll find opinions on PEAR and the packages found within, ranging from “It sucks!” to “It rocks!” — and covering everything in between. So, why these diverging reactions to PEAR?

PEAR, as a project, is many things to many people. Alongside positive reactions come remarks like “it didn’t do what I needed”, and “it’s bloated”, to general questions of Object Oriented application design. To some extent, PHP is a unique language in that there’s no such thing as a typical PHP coder. It attracts developers from all backgrounds, from Perl hackers to Java gurus, from Web designers to career programmers. Building something to suit everyone is impossible. You will find gems in PEAR. More often, although a package you’ve chose wasn’t “perfect”, it was good enough for the problem you’re trying to solve.

There’s also the social aspect. The PEAR developer community is changing shape. From a relatively small group of developers who knew each other and were able to coordinate easily, PEAR is now attracting much more input from the PHP community as a whole. While that’s a good thing, it also leads to growing pains. The effort required to manage this new input is significant and there are, fortunately, people giving up their free time to do so. On occasion, a poor response to someone’s “How do I…” question or an undiplomatic critique of a PEAR package (someone else’s hard work) has, in the past, lead to grudges being held.

Finally, there’s the issue of documentation, covering both how to use PEAR, and the details of packages stored in it. Simply put, there’s not a lot of documentation. And, where detailed instructions do exist, don’t be surprised if they’re out of date.

That said, having been a little involved with PEAR over the last seven months, I see a project that’s getting better and better. The PEAR regulars are very open to newcomers and are willing to listen to constructive feedback. They’re even more willing to accept offers of help, whether it be in adding new packages, maintaining existing ones, helping out with (much needed) documentation, or just getting involved in the mailing lists.

Whatever your preconceptions about PEAR, (or even if you’ve never heard of it), it’s a project of great value. The current code base already represents the sum of many thousands of hours’ work. More to the point, PEAR represents a chance to evolve PHP itself. From the basic framework (that you download from php.net) plus many other incoherent projects scattered around Sourceforge and the like, PEAR presents the opportunity for a unified and well-supported library of components, re-used by PHP developers world-wide, cutting everyone’s development time significantly.

So if there’s something you don’t like, don’t sit on the sidelines. Get involved and reform it. Evolution works better than revolution, after all!

Installing PEAR

OK, enough talk. It’s time for some action!

Setting up PEAR and being able to retrieve packages from it is a two-stage process. First, there’s the PEAR Installer, then, there’s the PEAR Package Manager. The job of the Installer is purely to set up the Package Manager. The Package Manager is the tool you use to fetch the PHP libraries (PEAR packages) you’re interested in.

Let’s begin with the PEAR Installer. Essentially, it’s just a PHP script that connects to the PEAR Website and downloads a whole bunch of other stuff (in particular, the Package Manager). To execute the installer, you need to be able to run PHP from the command line. So, let’s start there…

Command Line PHP

If you’re running Windows, open up a DOS shell (Windows NT / 2000 / XP: Start > Run > cmd.exe, Windows 95 / 98: Start > Run > command.exe — see Kev’s Command Prompt Cheat Sheet if you’re in any doubt).

If you’re running Linux on your own PC, I’ll assume you know how to start a shell. If you have a LAMP host (Linux / Apache / MySQL / PHP), when you start an ssh or telnet session to the server (assuming your host allows this), you should be taken to the command prompt (typically the BASH shell for Linux). Apologies to Mac users (there’s a significant Mac / PHP user group, you know) but Santa failed to leave one in my stocking last December. Maybe next year.

Whatever your OS, from the command prompt, type:

php -v

In response, you should see some version information displayed about PHP, such as:

PHP 4.3.4 (cli) (built: Nov 26 2003 10:46:59)  
Copyright (c) 1997-2003 The PHP Group  
Zend Engine v1.3.0, Copyright (c) 1998-2003 Zend Technologies

If you can’t see this, you first need to locate the PHP executable and add it to your systems path variable.

On Windows based systems, this will be below your PHP installation directory, in the “cli” subdirectory, for example:

c:php-4.3.2-Win32cliphp.exe

On Linux based systems, PHP will typically be found at:

/usr/local/bin/php

Note that the php binary doesn’t have the “.exe” extension on Linux. If in doubt, you can locate it on Linux with the following:

$ whereis php

Failing that, try the following (to search below the /usr directory):

$ find /usr -name php

Now you know where the php executable can be found, you need to update your path variable to make it available.

On Windows, head to Start > Control Panel > System > Advanced > Environment Variables. Scroll down the list of “system variables” until you find the path variable, select it and click edit. Now, at the end the “Variable Value”, append the path to your php executable e.g. “;c:php-4.3.2-Win32cli” (note the semi colon, which separates one path from the next). The executable is now in your path. If you start a new command prompt (any existing ones will still be using the old path variable), you should be able to type “php -v” and get the expected response.

If you use a LAMP host, they should have set it up for you, but if not, you need to edit (or create) the file “.profile” in your account’s home directory, adding the following line to the end of the file:

export PATH=$PATH:/usr/local/bin

Logout and, next time you connect to the shell, you should be able to execute the PHP binary directly (assuming your host has provided you with adequate permissions).

For more general tips and tricks for using PHP from the command line, see Replacing Perl Scripts with PHP Scripts, and the PHP Manual on Using PHP from the Command Line.

Running the PEAR Installer

Now you’ve got the PHP executable in your system path, it’s time to fetch and run the PEAR Installer. These days, the Installer is bundled with the PHP distribution, so it’s possible that you may already have it on your system. The Installer script is also available from http://pear.php.net/go-pear, and I’ll be using this so you know how to install PEAR from scratch.

Windows users, head to http://pear.php.net/go-pear with your browser and simply “Save Page As…”. Store it somewhere on your system, for example:

c:tempgo-pear.php

Now, type:

cd c:temp  
php go-pear.php

The Installer now starts.

Linux users get an easier life, needing only to type:

$ wget http://pear.php.net/go-pear -O go-pear.php  
$ php go-pear.php

Alternatively, if you have the Lynx text mode browser installed, just type:

$ lynx -source http://pear.php.net/go-pear | php

…which will download and execute the Installer.

Install Options

With the Installer running, you need to answer a few questions about how you’d like the PEAR Package Manager set up. Most of the questions should be straightforward (such as whether you’re using proxy server — the installer talks to the PEAR Website over HTTP).

When it comes to defining the file layout of PEAR, a little thought needs to be undertaken. If you’re installing on your own Linux system, it’s generally best to accept the default settings (login as root, first). When installing on Windows or on your LAMP host, it’s a good idea to change them. These are my preferences, which differ a little from the default settings the Installer provides:

  • Option 1 (alias $prefix): Installation Prefix – This a base location under which you can choose to put everything. A good choice might simply be c:pear on Windows systems. On LAMP, you’re probably better off with something like /home/yourname/pear, where “yourname” is the username that you login with (so, you install below your home directory).
  • Option 2: Binaries Location – When it says “binaries”, it actually means executable PHP scripts, shell scripts and so on. The command line version of the PEAR Package Manager goes here (which is what you’re interested in!). This directory will need go to into your systems path variable (using the same procedure as that you used to add the php binary to your path). Generally, a good choice might be $prefixbin for Windows ($prefix/bin for a LAMP account).
  • Option 3 (alias $php_dir): PHP Code Directory – This is the directory under which all the PEAR packages will be placed. It will need to be added to your PHP include_path (more on that in a moment). You might choose $prefixlib for Windows ($prefix/lib — LAMP).
  • Option 4: Documentation Base Directory – This is where documentation and examples, provided with PEAR packages, will be placed. You’ll probably be referring to this directory to see how a package works. On your own development system, you might choose to change this directory to one that’s below your Web root directory (e.g. c:apachehtdocspear) so you can quickly view examples with your browser. Be careful, though! Make sure you’re not exposing the directory to the world! A safer choice could be $prefixdocs for Windows or $prefix/docs for a Linux hosting account.
  • Option 5: Data Base Directory – Some PEAR packages use data stored in, say, XML form, which will be used in some manner by the PHP scripts the package provides (for example, PEAR::Science_Chemistry place a description of water in Chemical Markup Language in the data dir, although purely for testing). A good choice is probably $prefixdata for Windows (or $prefix/data for your LAMP host account).
  • Option 6: Test Directory – Place any unit test scripts provided with the package, normally for execution under PEAR::PHPUnit, here. Again, something like $prefixtests for Windows ($prefix/test — LAMP).

That’s the hard part done. Continue following the prompts and the Installer will download and set up the PEAR Package Manager, along with some extra, commonly used packages, should you choose to accept them (recommended).

Once this is complete, the Installer will attempt to modify your php.ini file, if possible, to add the PEAR library directory (Option 2 above) to your PHP include_path. On your own system, with the correct permission, it will probably get these modifications right. It’s a good idea to double check what it does, though, so open up your php.ini (usually in c:Windows; it varies on Linux) and see that the modifications are correct. Of course, the shared account that your host provides probably won’t let you modify php.ini — workaround coming up!

As I mentioned earlier, PEAR packages are included in your PHP code using the same relative path. So, having the correct include_path is very important (manually modifying PEAR packages is not fun!).

Using the directories I’ve suggested above, your include_path might look like one of the following:

include_path = ".;c:pearlib" ;

…on Windows. Note the semi colon.

include_path = ".:/usr/local/lib/php" ;

…on your own Linux system.

On a shared LAMP host where you have no access to modify php.ini, the best approach is to place a .htaccess file in your Web document root directory (this assumes your host has Apache configured to allow the use of .htaccess files), containing:

php_value "include_path" ".:/home/yourname/pear/lib"

That should apply recursively to subdirectories. If you get internal server errors, it’s time to harass your host — they need to configure Apache for your virtual host to have:

AllowOverride Options

(“Options” or “All” should do it.)

If you get desperate, you could also modify your include path in some global script that is already included throughout your application. For example:

<?php  
ini_set("include_path", ".:/home/yourname/pear/lib");

Note that you fetch your existing include path with ini_get(), meaning that you might use the following to preserve the existing include path:

<?php  
$current_path = ini_get("include_path");  
 
// Append a new include path to the existing path  
ini_set("include_path", "$current_path:/home/yourname/pear/lib");

More Environment Changes

Finally, you need to make further modifications to your environment.

Windows users should find a file call PEAR_ENV.reg, placed in the PEAR “binaries” directory by the installer (Option 2 above). This contains instructions that will allow you to edit your registry and create some environment variables that point to the various directories you specified above, so the PEAR Package Manager (and any package needing it) knows how PEAR is set up.

Those on a LAMP host should type:

$ ls -l ~/.pearrc

You should see a file called .pearrc, which PEAR has placed in your home directory. This will be used by the Package Manager to find the directories you specified when running the installer. The content is a serialized PHP array but if you have a look, you should be able to double check that the settings are correct.

The final step is to add the PEAR “binaries” directory to your systems path variable, so you can execute them from anywhere in your directory structure.

Following the steps that you used to add the php binary to your path above, Windows users should append the following (depending on where you installed PEAR):

;c:pearbin

Those with LAMP accounts, must edit .profile again, adding:

export PATH=/home/yourname/pear/bin:$PATH

Notice that the $PATH variable goes after the PEAR binaries directory. This is just a precaution, in case your host has its own version of PEAR installed; your version of any PEAR command line scripts should be executed first when you type pear.

That’s it! Now you can go on to experiment with the PEAR Package Manager (things get a lot easier from here, I promise).

Other Options

This isn’t the only way to set up the PEAR Package Manager. In particular, LAMP account hosts may already have PEAR installed (if you type pear from the command line before doing any of the above, you may see the Package Manager help page). You have the option of “piggy backing” on your host’s install, as explained here. Personally, I prefer not to do this as I’m a control freak (at least, I am when it comes to hosting!), but it may make life easier for you to trust your host to know what they’re doing with PEAR.

Also, although I’ll only be looking at the command line interface here, the PEAR Package Manager has two other “front ends”: a Web interface and a PHP-GTK GUI. I’ve never touched the GTK version, but the Web interface can be useful, especially if you’re stuck with a host that gives you no access to the command line (*boo*, *hiss*). There are some notes about setting up the Web front end at PHP Kitchen, which should be easy to adapt to a shared hosting account. Make sure you protect the Web interface with a username/password combination (a .htaccess file should do this for you)!

The Package Manager

OK, you’ve got this far. From now on, its gets a lot easier. The PEAR Package Manager should now be set up and ready to roll. To start with, from the command line, enter:

$ pear

Up should pop the basic usage of the PEAR Package Manager — a list of possible subcommands you can use with it. You can change pretty much all the settings you specified when you installed PEAR. Enter the following:

$ pear config-show

Here you’ll see the current configuration, with everything from the directories you specified when you installed it, to proxy server configuration and more. Generally, you shouldn’t need to worry about these, but it’s worth being aware how to control them. If you type:

$ pear config-help <optioname>

…you’ll receive a short description of what that config option means. You can change your options using:

$ pear set <optioname>

Not impressed yet? All that work for what? Well, how about typing this…

$ pear install XML_Parser   
$ pear install XML_Util  
$ pear install XML_Serializer

The first line may have resulted in your being told it’s already installed, depending on whether you accepted the recommended packages at install time. If so, just continue to the next line. What happens? There should have been some action, such as:

downloading XML_Serializer-0.9.1.tgz ...   
...done: 12,675 bytes  
install ok: XML_Serializer 0.9.1

What happened here? The PEAR Package Manager contacted the PEAR Website, found the latest version of XML_Serializer, downloaded it and installed it in your PEAR package library. You can immediately begin using the packages from your PHP scripts.

Impressed yet? The Package Manager is written in PHP, by the way. There’s more to this language than meets the eye…

The PEAR Package Manager provides a number of mechanisms for installing PEAR packages. The first, which was used above, was XML-RPC. It “talks” to the PEAR Web server and finds out stuff like which release it should download.

It is also able to fetch and install directly using HTTP, downloading a package in much the same way as browser does. For example, if you wanted a specific version of HTML_QuickForm, such as 3.1.1, you can get the link to the file from the package homepage — in this case, http://pear.php.net/get/HTML_QuickForm-3.1.1.tgz. You can then directly install it with:

$ pear install http://pear.php.net/get/HTML_QuickForm-3.1.1.tgz

You can also install files, which you’ve manually downloaded, from your local file system like so:

$ pear install /home/harryf/downloads/HTML_QuickForm-3.1.1.tgz

This also means that a package doesn’t have to be on the PEAR Website (or part of PEAR at all) in order for you to use it. Other projects, such as the ISMO Framework, publish releases ready for the Package Manager (the .tgz files) and can be installed directly, using the same approach. If you had a library you wanted to make easier for people to install, you could do the same.

In attempting to install HTML_QuickForm, you may have encountered a problem: an error message saying it depends on HTML_Common. Some packages require other packages to be available. If you look at the HTML_QuickForm homepage, at the bottom, you’ll notice it has a dependency on HTML_Common. That means HTML_Common will need to be installed first.

So, how does the PEAR package manager know what to do with a package? If you download some version of HTML_QuickForm, for example, with your browser and unzip it, you’ll find a file in there called package.xml. This contains all the information about where the package’s code should be placed, relative to your PEAR library directory. If you’re ever really dead in the water and can’t install the Package Manager, you could manually unzip a package and place it correctly in your include path, based on the information in package.xml (see a full description here). That’s a last resort, though — why make extra work for yourself?

Another useful command to know about is this one:

$ pear upgrade <package_name>

If you’ve already installed a package, that’s how you upgrade to the newest version. Make sure you check the release notes first, in case the new version breaks your code.

One small “gotcha” when it comes to installing packages, is the “preferred_state” configuration setting. Currently, this can be set to “stable”, “beta”, “alpha”, “devel” or “snapshot”. Now, imagine you have the “preferred_state” set to “stable” (the default), and you typed:

pear install HTML_QuickForm

This would cause the Package Manager to install the newest stable version of the package. This means that, if there’s a newer version of the package available, but the developers flagged it as, say, “beta”, it will be ignored in preference of an older, stable release. It may mean, for packages that have never had a stable release, that the Package Manager will not let you install them unless you lower the preferred state.

Anyway, that’s enough to get you started. As you can see, life is already a lot easier, thanks to PEAR.

Instant RSS

OK — time to put my money where my mouth is. No doubt, you’ve already read Kev’s article on PHP and XML: Parsing RSS 1.0. It explains the detail of building your own SAX handler for parsing RSS 1.0 and shows you how to fetch it from the SitePoint feed at https://www.sitepoint.com/rss.php.

Of course, it’s a lot of work to write all that code for handling XML. Also, if you’re trying to access the feed from behind a proxy server, you’ll need some kind of HTTP client that’s capable of understanding the headers the proxy server generates. PHP’s fopen() function won’t help you with that.

Thanks to PEAR, you can cut down the work involved in parsing an RSS feed significantly. Assuming you installed XML_Serializer up there, you also need PEAR::HTTP_Request. I’ll leave it to you to install it and work out any issues with dependencies.

Once you have the required packages installed, use this code:

<?php   
// Include PEAR::HTTP_Request  
require_once 'HTTP/Request.php';  
 
// Include PEAR::XML_Unserializer  
require_once 'XML/Unserializer.php';  
 
// Create the HTTP_Request object, specifying the URL  
$Request = & new HTTP_Request('https://www.sitepoint.com/rss.php');  
 
// Set proxy server as necessary  
// $Request->setProxy('proxy.myisp.com', '8080', 'harryf', 'secret');  
 
// Send the request for the feed to the remote server  
$ErrorCheck = $Request->sendRequest();  
 
// Check for errors  
if ( PEAR::isError($ErrorCheck) ) {  
   die ( "Connection problem: ".$ErrorCheck->toString() );  
}  
 
// Check we got an HTTP 200 status code (if not there's a problem)  
if ( $Request->getResponseCode() != '200' ) {  
   die ( "Request failed: ".$Request->getResponseCode() );  
}  
 
// Get the body of the response - the XML document  
$xml = $Request->getResponseBody();  
 
// Create an instance of XML_Unserializer  
$UnSerializer = &new XML_Unserializer();  
 
// Unserialize the feed and dump the raw array  
if ( $UnSerializer->unserialize($xml) ) {  
   $feed = $UnSerializer->getUnserializedData();  
   echo "<pre>";  
   print_r ( $feed );  
   echo "</pre>";  
} else {  
   die ( "Error unserializing feed" );  
}  
?>

From a glance at the above example it’s clear that there’s much less code to deal with, yet, we enjoy more detailed error handling, thanks to PEAR::HTTP_Request having some “understanding” of the HTTP protocol. Also, you immediately get access to the data in the RSS feed (no need to think about XML). To finish off, it’s just a matter of looping through the $feed["item"] array and displaying each row in HTML. I won’t discuss the details of PEAR::HTTP_Request or XML_Serializer this time. The example is designed just to give you an idea of how PEAR can make your life easier.

Whether any given PEAR package will save you time depends on whether you know how to use it, of course, and with documentation often amiss that’s often an issue. I strongly advise you research packages before planning them into a project (and that typically means looking at the source code).

Along those lines, you may be wondering why I didn’t use PEAR::XML_RSS instead of XML_Serializer. After a glance at the source of XML_RSS, I noticed that it expects to be given file handle from which it can fetch the feed. That would have caused issues with HTTP_Request, which returns the response as a string. XML_RSS should suit many requirements, but in this instance, I needed something a little different.

Wrap Up

That should have given you enough of a taste of PEAR to get you started!

Personally, I think it’s a great project and I’m finding myself taking advantage of PEAR packages more and more, whenever there’s a good fit. Sure, not everything is perfect and there are occasions where you’ll need to use hacks and workarounds to shape a package to what you need.

PEAR already has a lot to offer and is, by far, the largest combined PHP coding effort around. And as more and more PHP developers get behind PEAR, the better things will get.

Frequently Asked Questions about PEAR in PHP

What is the main purpose of PEAR in PHP?

PEAR, which stands for PHP Extension and Application Repository, is a framework and distribution system for reusable PHP components. It provides a structured library of open-source code for PHP users, a system for code distribution and package maintenance, and a standard style for code written in PHP. The main purpose of PEAR is to promote the reusability of code and a higher standard of programming in PHP.

How do I install PEAR on my system?

To install PEAR on your system, you need to download the PEAR installer script from the PEAR website. Once downloaded, you can run the script in your command line interface. The script will guide you through the installation process. After the installation is complete, you can verify the installation by typing ‘pear’ in your command line. If the installation was successful, you should see a list of PEAR commands.

How can I use PEAR packages in my PHP code?

Once you have installed a PEAR package, you can use it in your PHP code by including it with the ‘require_once’ statement. For example, if you have installed the Mail package, you can include it in your code like this: require_once ‘Mail.php’. After including the package, you can use its functions and classes in your code.

What are some popular PEAR packages?

There are many useful PEAR packages available for different purposes. Some popular ones include Mail for sending emails, DB for database abstraction, HTML_QuickForm for generating HTML forms, and HTTP_Request for making HTTP requests.

How do I update PEAR packages?

You can update PEAR packages using the ‘pear upgrade’ command in your command line interface. For example, to upgrade the Mail package, you would type ‘pear upgrade Mail’. If you want to upgrade all your installed packages, you can use the ‘pear upgrade-all’ command.

How can I contribute to PEAR?

If you want to contribute to PEAR, you can submit your own packages or patches to existing packages. You can also help by testing packages and reporting bugs. To get started, you can check out the PEAR developer documentation on the PEAR website.

What is the difference between PEAR and PECL?

PEAR and PECL are both repositories for PHP code, but they serve different purposes. PEAR is for PHP code that is written in PHP, while PECL is for code that is written in C and is used to extend PHP. PECL extensions are often more efficient than PEAR packages, but they require a C compiler to install.

How can I uninstall PEAR packages?

You can uninstall PEAR packages using the ‘pear uninstall’ command in your command line interface. For example, to uninstall the Mail package, you would type ‘pear uninstall Mail’.

Can I use PEAR with any version of PHP?

PEAR is compatible with PHP 4 and above. However, some packages may require a specific version of PHP. You can check the requirements for each package on the PEAR website.

Is PEAR secure?

PEAR itself is secure, but the security of individual packages depends on the package authors. It’s always a good idea to check the security of a package before using it. If you find a security issue in a PEAR package, you can report it to the PEAR security team.

Harry FuecksHarry Fuecks
View Author

Harry Fuecks is the Engineering Project Lead at Tamedia and formerly the Head of Engineering at Squirro. He is a data-driven facilitator, leader, coach and specializes in line management, hiring software engineers, analytics, mobile, and marketing. Harry also enjoys writing and you can read his articles on SitePoint and Medium.

Read Next
Get the freshest news and resources for developers, designers and digital creators in your inbox each week