LEARNING PHP WAS NEVER THIS MUCH FUN Come learn PHP in Paradise with us (and spend less than many other conferences) Ilia Alshanetsky - Accelerating PHP Applications , Marcus Boerger - Implementing PHP 5 OOP Extensions , John Coggeshall - Programming Smarty , Wez Furlong - PDO: PHP Data Objects , Daniel Kushner - Introduction to OOP in PHP 5 , Derick Rethans - Playing Safe: PHP and Encryption , George Schlossnagle - Web Services in PHP 5 , Dan Scott - DB2 Universal Database , Chris Shiflett - PHP Security: Coding for Safety , Lukas Smith - How About Some PEAR For You? , Jason Sweat - Test-driven Development with PHP , Andrei Zmievski PHP-GTK2 The Magazine For PHP Professionals php| Tropics Moon Palace Resort, Cancun, Mexico. May 11-15 2005 At php|tropics, take the exam and Get Zend Certified .and we'll pay your fees! For more information and to sign up: http://www.phparch.com/tropics Early-bird discount in effect for a limited time! II NN DD EE XX 6 EDITORIAL Out with the Old 7 What’s New! 48 Test Pattern Spring Cleaning by Marcus Baker 54 Product Review Visustin 3.0: The Flowcharter of the People ? by Peter B. MacIntyre 68 Security Corner BBCode 71 exit(0); Old School, New School, NO SCHOOL by Marco Tabini 10 Secure SOAP Transactions in Command Line Applications by Ron Korving 20 Database Abstraction in PHP by Lukas Smith 29 Advanced Sessions and Authentication in PHP 5 by Ed Lecky-Thompson 40 Building a MySQL Database Abstraction Class by Tom Whitbread 58 An XML approach to Templating using PHPTAL Part II by José Pablo Ezequiel Fernández Silva TABLE OF CONTENTS php|architect TM Departments Features Have you had your PHP today?Have you had your PHP today? The Magazine For PHP Professionals http://www.phparch.com NEW COMBO NOW AVAILABLE: PDF + PRINT NNEEWW LLoowweerr PPrriiccee!! EEDDIITTOORRIIAALL E diting php|architect is, at the same time, a blessing and a curse. On the plus side, I get to read some really exciting material every month. On the minus side… I have to read all that material every month before the deadline for the next issue! Being an editor is very challenging—something I would have never guessed when I got into this line of work. I dare anybody to do it for six months and read a book the way they used to before. Gone is the lust for knowledge—to be replaced for a compulsive, incurable need to find typos and fix someone else’s grammar. Of course, someone else is the key here—it’s never your own mistakes you catch (regardless of whether you actively made them part of your own writing or didn’t catch them in another author’s work). There are, of course, many reasons why being the editor of this magazine no longer makes sense for me. First, our activities have grown so much from a single PDF publication to a group that encompasses PHP education on so many levels— print, books, training and conferences—that I constantly feel guilty that I’m not dedicating as much time as I should to making sure that the contents of php|a are always the best of the best (even though editing the magazine keeps me up many nights every month). Second, and most important, we must ensure that our supply of fresh ideas is, well, fresh. Change is everything—and it’s been time for some new thought pat- terns to be formed in the php|a brain for a while now. Armed with these problems, we have been working hard at finding a new Editor- in-Chief for php|architect. It’s not been easy, but I hope that you’ll join me in wel- coming Sean Coates to the gang. Sean is an active member of the PHP team (he works on the documentation—and I can’t think of a better way to be exposed to as much PHP technology as possible) and, like the rest of us, uses PHP in his every- day life. But don’t take my word for it—he will be introducing himself shortly. For my part, I bid you all farewell. Of course, you can’t get rid of me quite that eas- ily—I’m still hanging on to my exit(0), and I will as always lurk on our forums try- ing my very best to confuse as many people as possible for every single post. Until next month… well, it’s up to Sean now! In with the New One random afternoon, on IRC, I noticed Marco complaining about having to go edit an article, when he’d rather be doing something else. I naively retorted with “I actually like editing!” and, over the next few days, we worked out the details, evaluated my skills, and speculated on how much work was involved in editing an issue of php|architect. Now, only a month later, here I am. Allow me to introduce myself. As Marco indicated, I’ve been actively involved in the PHP community for approximately two years, now (and not-so-actively involved, before that, for another year). My attention and keystrokes are primarily spent writing and editing the PHP manual, but I’m also involved in several other projects, including documentation meta-projects and the maintenance of a popu- lar PEAR package. I’ve been writing PHP, professionally, for over 5 years for various companies, involved in many sectors, from marketing to credit card processing. It is with great pleasure (and already some late nights) that I take the reins of what I believe to be the best recurring resource that is currently available for pro- fessional PHP developers. I’m also happy that Marco can offload some of his work to me, freeing him up to do the things he mentioned above. I believe that the owner of a business should be involved in his creation, but not necessarily intimate- ly so. There’s a certain value in having the ability to take a step back, and view the fruits of your labor from a distance. With this pleasure, though, comes great responsibility. I hope to be accessible to you, our readers, in as many ways as possible. Please don’t hesitate to contact me with any complaints, criticism, snide remarks, ideas, or encouragement you may have. I’m usually very responsive by email ( sseeaann@@pphhppaarrcchh ccoomm ), or you might find it more convenient to drop your thoughts in our online discussion forums ( hhttttpp::////pphhppaarrcchh ccoomm//ddiissccuussss// ). I look forward to hearing from you. Until next month, happy reading! (Yes, I stole his line.) April 2005 ● PHP Architect ● www.phparch.com 6 php|architect Volume IV - Issue 4 April, 2005 Publisher Marco Tabini Editor-in-Chief Sean Coates Editorial Team Arbi Arzoumani Peter MacIntyre Eddie Peloke Graphics & Layout Arbi Arzoumani Managing Editor Emanuela Corso News Editor Leslie Hill news@phparch.com Authors Marcus Baker, Peter B. MacIntyre, Chris Shiflett, Ron Korving, José Pablo Ezequiel Fernández Silva, Lukas Smith, Ed Lecky-Thompson, Tom Whitbread php|architect (ISSN 1709-7169) is published twelve times a year by Marco Tabini & Associates, Inc., P.O. Box 54526, 1771 Avenue Road, Toronto, ON M5M 4N5, Canada. Although all possible care has been placed in assuring the accuracy of the contents of this magazine, including all associated source code, list- ings and figures, the publisher assumes no responsibilities with regards of use of the information contained herein or in all associated material. Contact Information: General mailbox: info@phparch.com Editorial: editors@phparch.com Subscriptions: subs@phparch.com Sales & advertising: sales@phparch.com Technical support: support@phparch.com Copyright © 2003-2005 Marco Tabini & Associates, Inc. — All Rights Reserved OOuutt wwiitthh tthhee OOlldd EE DD II TT OO RR II AA LL RR AA NN TT SS TM NNEEWW SSTTUUFFFF April 2005 ● PHP Architect ● www.phparch.com 7 What’s New! php|architect prepares for php| tropics 2005 Ever wonder what it's like to learn PHP in paradise? Well, this year we've decided to give you a chance to find out! We're proud to announce php|tropics 2005, a new conference that will take place between May 11-15 at the Moon Palace Resort in Cancun, Mexico. The Moon Palace is an all- inclusive (yes, we said all inclusive!) resort with over 100 acres of ground and 3,000 ft. of private beach, as well as excellent state-of-the-art meeting facilities. As always, we've planned an in-depth set of tracks for you, combined with a generous amount of downtime for your enjoyment (and your family's, if you can take them along with you). We even have a very special early-bird fee in effect for a limited time only. For more information, go to http://www.phparch.com/tropics . NN EE WW SS TT UU FF FF PHP Input Filter 1.2.0 Need help filtering data and pre- venting attacks? Check out PHP Input Filter. According to the pro- ject's homepage, PHP Input Filter: "is a free php class that allows developers to easily filter input coming from the user (HTML forms, cookies etc) for a num- ber of reasons. The focus of this tool is on customization. v1.2.0 features much more comprehensive anti-XSS pro- tection, as well as the option of auto-stripping bad tags sep- arate from any specified by the developer." To see a demo or to download, visit www.cyberai.com/inputfil- ter/ . CONFERENCES Zend/PHP Conference and Expo 2005 Zend.com announces: Zend Technologies and KB Conferences proudly announce the Zend/PHP Conference & Expo 2005 taking place at the Hyatt Regency San Francisco Airport on October 18-21, 2005. The theme of the con- ference will be "Power Your Business With PHP" and will feature sessions in the following four tracks: The Business Case for PHP; Developing, Deploying and Managing Large-Scale PHP Applications; Integrating PHP with the Enterprise (including Web Services and XML); and PHP Resources: Tools, Libraries and Techniques. "We invite interested speakers to submit session proposals between now and July 15, 2005. Visit the conference website for more information about the conference or if you are interested in sub- mitting a session proposal." Get all the latest conference information from Zend.com. International PHP Conference 2005 Spring Edition Don't want to wait until October for the Zend/PHP Conference? Zend.com brings news of the International PHP Conference coming in May: "The International PHP Conference 2005 Spring Edition will take place from May 2, 2005 to May 4, 2005. The Conference features a PowerWorkshop day on May 2 with PHP/MySQL Best Practices, XML/WebServices with PHP 5, Rapid Application Development and a PHP Starter Workshop for Beginners. The main Conference days will include sessions on PHP Internals, XML, Databases, Migration to PHP 5 and others. Early bird discounts are available until April 1, 2005." For more information, visit phpconference.com. Fast Template 1.3 Grafxsoftware.com announces the latest release of their PHP templating system, Fast Template. What's new in this version? • Added DELETE_CACHE function, to delete files what is older then expire time. • Added file extension to cache for example now a cache file name will be 62327a34b389dca70c7c15e9d81e57bd.ft (notice the extension .ft) This was necessary because of DELETE_CACHE function • Added include block which include another template by statement (like SSI do) <!--#include file="include2.html"--> It is useful if you have several different templates for different parts of page and you don't need to write any php code to gather all "blocks" of the page. Also is very helpful from designer point of view, he will see in a visual editor the result. Get more information from http://www.grafxsoftware.com/product.php?id=26. NNEEWW SSTTUUFFFF April 2005 ● PHP Architect ● www.phparch.com 8 Check out some of the hottest new releases from PEAR. Net_Monitor 0.2.2 A unified interface for checking the availability of services on external servers and sending meaningful alerts through a variety of media if a service becomes unavailable. LiveUser_Admin 0.2.1 LiveUser_Admin is meant to be used with the LiveUser package. It is composed of all the classes necessary to administer data used by LiveUser. You'll be able to aadddd//eeddiitt//ddeelleettee//ggeett things like: • Rights • Users • Groups • Areas • Applications • Subgroups • ImpliedRights And all other entities within LiveUser. LiveUser 0.15.1 LiveUser is a set of classes for dealing with user authentication and permission management. Basically, there are three main elements that make up this package: • The LiveUser class • The Auth containers • The Perm containers The LiveUser class takes care of the login process and can be configured to use a certain permission container and one or more differ- ent auth containers. That means, you can have your users' data scattered among many data containers and have the LiveUser class try each defined container until the user is found. For example, you can have all website users who can apply for a new account online on the webserver's local database. Also, you want to enable all your company's employees to login to the site without the need to create new accounts for all of them. To achieve that, a second container can be defined to be used by the LiveUser class. You can also define a permission container of your choice that will manage the rights for each user. Depending on the container, you can implement any kind of permission schemes for your application while having one consistent API. Using different permission and auth containers, it's easily possible to integrate newly written applications with older ones that have their own ways of storing permissions and user data. Just make a new container type and you're ready to go! Currently available are containers using: PPEEAARR::::DDBB,, PPEEAARR::::MMDDBB,, PPEEAARR::::MMDDBB22,, PPEEAARR::::XXMMLL__TTrreeee and PPEEAARR::::AAuutthh . File 1.2.0 Provides easy access to read/write to files along with some common routines to deal with paths. Also provides interface for handling CCSSVV files. XML_Wddx 1.0.1 XXMMLL__WWddddxx does 2 things: a) functions as a drop in replacement for the XXMMLL__WWddddxx extension (if it's not built in) b) produces an editable WWDDDDXX file (with indenting etc.) and uses CCDDAATTAA , rather than char tags This package contains 2 static methods: XXMMLL__WWddddxx::sseerriiaalliizzee(($$vvaalluuee)) and XXMMLL__WWddddxx::ddeesseerriiaalliizzee(($$vvaalluuee)) . It should be 90% compatible with wddx_deserialize(), and the deserializer will use wddx_deserialize if it is built in. No support for recordsets is available at present in the PHP version of the deserializer. PHP 5 ionCube Encoder The good people at ioncube have announced the release of the new ionCube Encoder for PHP 5. "We are happy to announce the release of the new ionCube Encoder for PHP 5! The new Encoder fully supports all PHP 5 language constructs and can deliver a substantial increase in performance over unencoded PHP 5. The PHP 4 Encoder is provided for free with the PHP 5 Encoder. We have added Package Foundry support to the Windows version of the new Encoder, enabling a one-stop solution for those wishing to create, package, and deploy PHP applications. To demonstrate this support the Encoder download bundle now includes a Package Foundry evaluation. Existing PHP 4 Encoder customers are eligible for a discount when purchasing the new PHP 5 Encoder." For more details please visit www.ioncube.com. NNEEWW SSTTUUFFFF April 2005 ● PHP Architect ● www.phparch.com 9 Looking for a new PHP Extension? Check out some of the lastest offerings from PECL. pecl_http 0.7.0 pecl_http provides: • Building absolute URIs • RFC compliant HTTP redirects • RFC compliant HTTP date handling • Parsing of HTTP headers and responses • Caching by "Last-Modified" and/or ETag (with 'on the fly' option for ETag generation from buffered output) • Sending data/files/streams with (multiple) ranges support • Negotiating user preferred language/charset • Convenient request functions to HEAD/GET/POST if libcurl is available • HTTP auth hooks (Basic) • HTTPi, HTTPi_Response and HTTPi_Request classes (HTTPi_Request only with libcurl) maxdb 7.5.00.24 MaxDB PHP is an extension which provides access to the MySQL MaxDB databases. It is compatible with MySQL's mysqli extension. big_int 1.0.1 Functions from this package are useful for number theory applications. For example, in two-keys cryptography. See //tteessttss//RRSSAA pphhpp in the package for example of implementation of RSA-like cryptoalgorithm. The package has many bitset functions, which allow to work with arbitrary length bitsets. This package is much faster than bundled into PHP BCMath and consists almost all functions, which implemented in PHP GMP extension, but it needn't any external libraries. crack 0.2 This package provides an interface to the cracklib (libcrack) libraries that come standard on most unix-like distributions. This allows you to check passwords against dictionaries of words to ensure some minimal level of password security. From the cracklib README CrackLib makes literally hundreds of tests to determine whether you've chosen a bad password. • It tries to generate words from your username and gecos entry to tries to match them against what you've chosen. • It checks for simplistic patterns. • It then tries to reverse-engineer your password into a dictionary word, and searches for it in your dictionary. • after all that, it's PROBABLY a safe(-ish) password. 8-) The crack extension requires cracklib (libcrack) 2.7, some kind of word dictionary, and the proper header files (crack.h and packer.h) to build. For cracklib RPMs for Red Hat systems and a binary distribution for Windows systems, visit http://www.dragonstrider.com/cracklib. php-Booba 0.8.1 The php-Booba team announces the release of php-Booba 0.8.1. "php-Booba is a simple framework for developing Web applications. It contains classes for validating incoming data from forms, a powerful ticket-based request handling system, and a very fast template system." For more information, or to download, visit http://sourceforge.net/projects/php-booba The Zend PHP Certification Practice Test Book is now available! We're happy to announce that, after many months of hard work, the Zend PHP Certification Practice Test Book, written by John Coggeshall and Marco Tabini, is now available for sale from our website and most book sellers worldwide! The book provides 200 questions designed as a learning and practice tool for the Zend PHP Certification exam. Each question has been written and edited by four members of the Zend Education Board--the very same group who prepared the exam. The questions, which cover every topic in the exam, come with a detailed answer that explains not only the correct choice, but also the question's intention, pitfalls and the best strategy for tackling similar topics during the exam. For more information, visit hhttttpp::////wwwwww pphhppaarrcchh ccoomm//cceerrtt//mmoocckk__tteessttiinngg pphhpp S OAP (Simple Object Access Protocol) is a protocol that enables you to run functions on a remote sys- tem (Remote Procedure Calls). It is derived from XML-RPC, which has been available in PHP since ver- sion 4.1, and as we will see later, SOAP messages are formatted in XML. Because it is such an open protocol, SOAP is programming language and operating system independent. This enables you to use PHP to commu- nicate with any application as long as it can communi- cate using SOAP. The PHP SOAP extension was introduced in PHP 5 and is particularly useful when combined with PHP 5’s object oriented possibilities, because SOAP handler functions can all be implemented in a single class, and because the extension itself is completely implemented as classes. One of the nice things about having a SOAP exten- sion in PHP is the ability to use this protocol to commu- nicate with custom-made daemon applications that are running on remote servers. The wonderful thing about having a daemon running on the command line inter- face (CLI), instead of a web interface, is that you can run it with root permissions, enabling it to do virtually everything a web script is not allowed to do. Generally, SOAP relies on the HTTP protocol, which is a good thing, since it’s such a commonly spoken pro- tocol. HTTP is, however, insecure by default. Of course, you can use the secure HTTPS protocol for SOAP trans- actions, but if you want to create a secure command- line daemon in PHP, you’ll have to embed an HTTPS web server in it. Luckily, the SOAP extension allows you to modify requests before they are sent, and responses before they are received. This allows you to apply the cryptographic algorithms and key-distribution mecha- nisms of your choice! REQUIREMENTS PHP 5.x OS Any Other Software N/A Code Directory soap April 2005 ● PHP Architect ● www.phparch.com FFEEAATTUURREE 10 Secure SOAP Transactions in Command Line Applications by Ron Korving Remote procedure calls using PHP have become increas- ingly popular in the past few years. Since the introduction of PHP 5, a SOAP extension has been bundled with the core PHP distribution. SOAP does not, in itself, provide a security mechanism, nor is the PHP-extension very suitable for command line applications. In this article, I will explain how you can achieve security for your SOAP transactions, and create your own SOAP-driven daemons on your servers. FF EE AA TT UU RR EE RESOURCES URL hhttttpp::////wwwwww pphhpp nneett//mmaannuuaall//eenn//rreeff ssooaapp pphhpp URL hhttttpp::////pphhpp nneett//mmaannuuaall//eenn//rreeff mmyyssqqll pphhpp URL hhttttpp::////eenn wwiikkiippeeddiiaa oorrgg//wwiikkii//BBlloocckk__cciipphheerr__ mmooddeess__ooff__ooppeerraattiioonn ii . create a SOAP client and server, web- as well as command-line-based. You’ve seen how to alter transaction data (in-line), apply encryption, handle errors, and. run a SOAP server run from the command line and the cool possibilities that are created when doing so. A Simple SOAP Client and Server Let’s write a small