Last month we looked at basic user authentication with PHP. The methods shown were useful for simple applications that require only minimal security. More complex applications, however, tend to require a more flexible and robust authentication system as well as session handling, permissions, and so on. Building such a system on your own would probably require a lot of time, during which you'd be reinventing wheels (and bugs). This month we'll look at PHPLib and some of the features you could take advantage of.
Last month we looked at basic user authentication with PHP. The methods shown were useful for simple applications that require only minimal security. More complex applications, however, tend to require a more flexible and robust authentication system as well as session handling, permissions, and so on. Building such a system on your own would probably require a lot of time, during which you’d be reinventing wheels (and bugs). This month we’ll look at PHPLib and some of the features you could take advantage of.
PHPLib (http://phplib.sourceforge.net) is a library of classes for PHP that you can use in building medium and large-scale Web applications. “Classes?” you may be wondering. Yes, PHP provides support for classes and other object- oriented programming constructs. This means you can build generic software components that you’ll use across a large variety of applications. This often comes as news to folks who’ve been using PHP from the early days and upgraded without really taking note of its new features.
PHPLib provides the classes for the following:
- database access (MySQL, PostgreSQL, Oracle, etc.)
- session management
- permission checks
- user accounts
- shopping carts
- database queries
As you can see, PHPLib is feature-packed. While it may sound like the “kitchen sink” of PHP bloat-ware libraries, PHPLib is designed such that you can pick and choose the components you want to use in your applications.
Because PHPLib is a rather complex library, there are a variety of ways it can be installed. The one that you select will depend on the type of distribution you are using (Red Hat, Debian, Slackware), whether you have root access, and how the Apache Web server is configured.
The best approach is to either read the documentation available on the PHPLib Web site or to download the latest tarball and unpack it. You’ll find detailed installation instructions in the documentation.txt or documentation-1. html file in the doc subdirectory.
It’s probably best to create a directory called phplib at the same level as your document root. If that’s located at /usr/local/apache/htdocs, then you should create /usr/local/apache/phplib.
Into this directory, you should copy the php subdirectory (which contains mostly PHP include files) and the local. inc file. You should also decide which database PHP is going to use and locate the appropriate script create_ database.database. We will assume that MySQL is being used, so the script create_database.mysql will be located for later use.
Finally, you should copy the contents of the pages subdirectory to a directory under your server’s document root, such as /usr/local/apache/htdocs/ pages. These are sample pages to help test PHPLib.
Now you will need to tell PHP about the existence of PHPLib. First, you should modify the PHP file php.ini and add the PHPLib directory that was created (/usr/local/apache/phplib in our case) to the include_path di-
rective. You should also add /usr/local/apache/phplib/prepend.php3 to the auto_prepend_file statement. The added lines might look like this:
include_path = /usr/local/
auto_prepend_file = /usr/
The first change places the PHPLib directory in PHP’s include path. This allows you to simply use a PHPLib module in a require(“file.inc”) statement without needing to specify the path to the file. The other change tells PHP to always load prepend.php3 on each request it handles. This frees you from having to specifically request PHPLib on every page in your application. Of course, it also carries a slight performance hit. If you have many PHP applications that don’t use PHPLib, you might want to consider using require(“prepend.php3″) only on pages which actually need it.
The next file that must be modified is the local.inc file that was copied into /usr/local/apache/phplib. There are a few parameters that you must customize for some of PHPLib’s features to work properly.
PHPLib makes use of a relational database (MySQL by default) for storing authentication and session information. In the DB_Example section of local.inc, you’ll need to specify some MySQL database information. Assuming that your MySQL server is on the same machine as Apache, you could use a configuration such as this:
class DB_Example extends
var $Host = “localhost”;
var $Database = “phplib”;
var $User = “phplib_user”;
var $Password = “phplib_pass”;
|Figure Two: The first visit to PHPLib’s index page.|
(You’ll probably want to select a more creative password, of course).
Once that’s done, you’ll need to create the phplib database and user via the session shown in Figure One.
Now you can create the tables and some PHPLib accounts using the create_database.mysql script we located earlier:
$ mysql -u phplib_user
-p phplib <
|Figure Three: PHPLib’s default login page.|
With all of that done, it’s time to see exactly why we went through all this effort. Point your browser at http://localhost/pages/index.php3; what you see should look like Figure Two. If you reload that page a few times, you’ll notice the “Per Session Data: 1″ counter increases each time.
Kicking the Tires
If that all worked, click the “Load a more complex example” link; you should see a login page which looks like Figure Three. Enter the username “kris” and password “test“. The page you’ll see contains a lot of information about your current session and login. Note that this account “kris” is stored within the PHPLib database. It is neither a Unix account nor a MySQL account.
Figure One: Creating the PHPLib Database in MySQL
mysql -u root -p
Enter password: ******
Welcome to the MySQL monitor. Commands end with ; or \g.
Your MySQL connection id is 13 to server version: 3.23.43-debug-log
Type ‘help;’ or ‘\h’ for help. Type ‘\c’ to clear the buffer.
mysql> CREATE DATABASE phplib;
Query OK, 1 row affected (0.00 sec)
mysql> GRANT ALL PRIVILEGES ON phplib.* TO phplib_user@localhost
IDENTIFIED BY ‘phplib_pass’;
Query OK, 1 row affected (0.00 sec)
Sessions and Authentication
Much of PHPLib’s power and flexibility comes from the fact that it has excellent support for sessions. PHPLib’s interface also makes it clear whether you are working with session, user, or authentication data.
In most PHPLib applications, like the index.php3 page we visited, a session is begun automatically if PHPLib doesn’t believe you already have an active session. The session data is stored in the active_sessions table in the phplib database. This gives you persistent sessions, meaning that even if you restart Apache, your session will still work if you reload the page.
Once a session has been established, you can store arbitrary information (session variables) in the user’s session data, and PHPLib takes care of automatically updating the database. So far, we’ve just seen simple numeric counters, but you could store the answers to an online quiz, credit card information, or just about anything else you want.
When you clicked on the link for the “more complex example” and authenticated yourself, the resulting page listed a variety of information about your session and user data. For example, you probably saw something like this:
Your session id is c5275d73
Your user id is c14cbf141
This should be the same as
You have the permissions admin
PHPLib assigned your session ID on your first visit to index.php3. Once you authenticated, it used the username and password that you entered to look up your user ID and user data in MySQL (using the auth_user or auth_user_md5 table). It just so happens that the “kris” account is created as part of the PHPLib installation and it has administrative privileges for this application.
There’s clearly a lot more going on behind the scenes, but it’s not particularly interesting to get into all the details — at least not until you know how to access session and user data in your own application.
Accessing the Data
Listing One provides the code to a sample page (test.php) which makes use of authentication and user data. It starts out by calling page_ open(), which you must have at the start of every page which uses PHPLib authentication. Note the corresponding page_close() on line 36.
2 page_open(array(“sess” => “Example_Session”, “auth” => “Example_Auth”,
3 “user” => “Example_User”));
7 <head><title>PHPLib Authentication and User Data</title></head>
9 <h1>PHPLib Authentication and User Data</h1>
11 <p>Welcome, <? echo $auth->auth["uname"] ?></p>
18 if (!isset($browser))
20 $browser = $HTTP_USER_AGENT;
21 echo “<b>You are using $browser</b>”;
23 elseif ($browser != $HTTP_USER_AGENT)
25 echo “You switched from <b>$browser</b> to <b>$HTTP_USER_AGENT</b>”;
26 $browser = $HTTP_USER_AGENT;
30 echo “Same browser as before: <b>$browser</b>”;
The page_open() call tells PHPLib that we would like access to session, authentication, and user objects (called $sess, $auth, and $user) in the page. Each of those objects are instances of the classes named on lines 2 and 3. They are subclasses of PHPLib’s base classes and are defined in local. inc. So if you want to change their behavior or further subclass them, see the relevant parts of the local.inc file.
The code goes on to issue a welcome message to the authenticated user (kris in this case) on line 6. It then registers a variable called $browser that will be associated with the user (kris). From there, it compares the value of $browser and $HTTP_USER_AGENT to see if the user has changed browsers between this visit and the previous visit. Of course, it also accounts for the fact that this could be the very first visit. In each case, it prints an appropriate message.
After loading the page a few times with Netscape 4.76, you’d see a message like:
Same browser as before:
Mozilla/4.76 [en] (X11; U;
Linux 2.4.14 i686; Nav)
If you then switched to Mozilla 0.9.5, you would see the following message on your next visit the page:
You switched browsers from
Mozilla/4.76 [en] (X11;
U; Linux 2.4.14 i686; Nav)
to Mozilla/5.0 (X11; U;
Linux i686; en-US; rv:
You could apply the same technique to various other bits of information, too. With PHPLib, being able to say “The last time you purchased using your Visa card…” or “I see that you are using a different proxy server…” is quite simple.
Wrapping It Up…
We’ve only scratched the surface of how PHPLib can simplify application development. Its various classes provide an easy to use and extensible interface for data storage and retrieval, authentication, and much more. Chapter Six of Web Application Development with PHP 4.0 contains some in-depth examples of using PHPLib, and it’s even available online (http://www.phpwizard.net/book).
Of course, the PHPLib documentation, is also quite helpful for understanding how its various classes act and interact.
Jeremy Zawodny uses open source tools in Yahoo! Finance by day and is writing a MySQL book for O’Reilly & Associates by night. Reach him at firstname.lastname@example.org.