www.phparch.com SEPTEMBER 2003 The Magazine For PHP Professionals VOLUME II - ISSUE 9 php | Cruise March 1 st - March 5 th 2004 See inside for details Get Ready For Plus: Tips & Tricks, Product Reviews and much more . Creating a Reusable Menu Creating a Reusable Menu System with XML and PHPSystem with XML and PHP Printing with PHPPrinting with PHP Using PHP's printer functions Using PHP's printer functions from Windowsfrom Windows Introduction to Introduction to Bug ManagementBug Management Understand the need, the solutions,Understand the need, the solutions, and the processesand the processes Installing Java for PHPInstalling Java for PHP Demystify the beastDemystify the beast Advanced DatabaseAdvanced Database Features ExposedFeatures Exposed Come to terms with usingCome to terms with using the best tool for the jobthe best tool for the job Secure PHPSecure PHP Taking the key outTaking the key out of the lockof the lock Signup now and save $100.00! Hurry, space is limited. Visit us at www.phparch.com/cruise for more details. php | Cruise March 1 st - March 5 th 2004 Andrei Zmievski - Andrei's Regex Clinic , James Cox - XML for the Masses , Wez Furlong - Extending PHP , Stuart Herbert - Safe and Advanced Error Handling in PHP5, Peter James - mod_rewrite: From Zero to Hero, George Schlossnagle - Profiling PHP, Ilia Alshanetsky - Programming Web Services, John Coggeshall - Mastering PDFLib, Jason Sweat - Data Caching Techniques <? ?> We’ve got you covered, from port to sockets. Port Canaveral • Coco Cay • Nassau Plus: Stream socket programming, debugging techniques, writing high-performance code, data mining, PHP 101, safe and advanced error handling in PHP5, programming smarty, and much, much more! FROM THE EXPERTS AT DEVELOPER’S LIBRARY . MORE TITLES FROM DEVELOPER’S LIBRARY Advanced PHP Programming by George Schlossnagle ISBN: 0-672-32561-6 $49.99 US • 500 pages PHP and MySQL Web Development, Second Edition by Luke Welling and Laura Thomson ISBN: 0-672-32525-X $49.99 US • 912 pages PHP Developer’s Handbook by John Coggeshall ISBN: 0-672-32511-X $49.99 US • 800 pages MySQL, Second Edition by Paul DuBois ISBN: 0-7357-1212-3 $49.99 US • 1248 pages Elevate Your PHP with Advanced PHP Programming While there are many books on learning PHP and developing small applications with it, there is a serious lack of information on scaling PHP for large-scale, business-critical systems. Schlossnagle’s Advanced PHP Programming fills that void, demonstrating that PHP is ready for enterprise Web applications by showing the reader how to develop PHP-based applications for maximum performance, stability, and extensibility. www.developers-library.com DEVELOPER’S LIBRARY Essential references for programming professionals php|architect readers, get 40% off books in the Developer’s Library Visit www.developers-library.com and add the books of your choosing to your shopping cart. Upon check-out, enter the coupon code PHPARCH03 to receive discount. Offer valid through 12/31/03. TABLE OF CONTENTS II NN DD EE XX 6 EDITORIAL From the front line 7 What’s New! 49 Product Review Lumenation and LightBulb 68 Book Review Core PHP Programming 3rd Edition 69 Tips & Tricks By John W. Holmes 73 Bits & Pieces Real. Interesting. Stuff. 76 exit(0); Buy vs. Build By Marco Tabini 9 Secure PHP Coding by David Jorm and Jody Melbourne 19 Introduction to Bug Management by Dejan Bosanac 27 Advanced Database Features Exposed by Davor Pleskina 35 Creating a Reusable Menu System with XML and PHP by Leon Vismer 45 Speaker on the High Seas by Marco Tabini 52 Printing with PHP by Alessandro Sfondrini 61 Installing Java for PHP by Dave Palmer php|architect Features Departments 4 September 2003 · PHP Architect · www.phparch.com *By signing this order form, you agree that we will charge your account in Canadian dollars for the “CAD” amounts indicated above. Because of fluctuations in the exchange rates, the actual amount charged in your currency on your credit card statement may vary slightly. †Limited time offer extended to September 30th, 2003. Choose a Subscription type: Canada/USA $ 81.59 $67.99 CAD ($59.99 $49.99 US*) International Surface $108.99 $94.99 CAD ($79.99 $69.99 US*) International Air $122.99 $108.99 CAD ($89.99 $79.99 US*) Your charge will appear under the name "Marco Tabini & Associates, Inc." Please allow up to 4 to 6 weeks for your subscription to be established and your first issue to be mailed to you. *US Pricing is approximate and for illustration purposes only. php|architect Subscription Dept. P.O. Box 3342 Markham, ON L3R 9Z4 Canada Name: Address: City: State/Province: ZIP/Postal Code: Country: Payment type: VISA Mastercard American Express Credit Card Number: Expiration Date: E-mail address: Phone Number: Buy now and save $10 off the price of any subscription† Visit: http://www.phparch.com/print for more information or to subscribe online. Signature: Date: To subscribe via snail mail - please detach this form, fill it out and mail to the address above or fax to +1-416-630-5057 php|architect The Magazine For PHP Professionals Existing subscribers can upgrade to the Print edition and save! Login to your account for more details. NEW! NEW! September 2003 · PHP Architect · www.phparch.com EE DD II TT OO RR II AA LL RR AA NN TT SS php|architect Volume II - Issue 9 September, 2003 Publisher Marco Tabini Editor-in-Chief Peter James petej@phparch.com Editor-at-Large Brian K. Jones brian@phparch.com Editorial Team Arbi Arzoumani Peter James Brian Jones Eddie Peloke Graphics & Layout Arbi Arzoumani, Hammed Malik, Marina Zlatogorov Managing Editor Emanuela Corso Director of Marketing J. Scott Johnson scott@phparch.com Account Executive Shelley Johnston shelley@phparch.com Authors Dejan Bosanac, David Jorm, Dave Palmer, Davor Pleskina, Allessandro Sfondrini, Leon Vismer php|architect (ISSN 1705-1142) is published twelve times a year by Marco Tabini & Associates, Inc., P.O. Box. 3342, Markham, ON L3R 6G6, Canada. Although all possible care has been placed in assuring the accu- racy of the contents of this magazine, including all associated source code, listings 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 © 2002-2003 Marco Tabini & Associates, Inc. — All Rights Reserved I n the relatively short time that I’ve been with php|architect (about six months now), I’ve seen a lot of our magazine content cross my (very messy) desk. In that same time period, I’ve been committed to gobbling up any and all PHP content gracing the pages of other publi- cations and developer sites. I now feel that I am qualified to state an opinion: We have great content. Our authors consistently dig deep into their top- ics, bringing you their practical experience, exam- ples, and well-written explanations. Their enthusi- asm for their articles shines through, and brings warmth and community to the pages of php|architect every month. We constantly demand the best from our authors, and they, in turn, demand the best from us. The php|architect editorial team prides itself on being transparent, and I believe that authors enjoy writing for us because of it (maybe this helps explain why there are only two new authors and four return authors this month). By transparent, I mean that we are honest and up front with them, as well as ourselves. We view our authors as collaborators and team members, never as service providers or vendors. We are easy to work with, and are eager to bend over backward to help if we can see that an honest effort is being made. Through all of this we never compromise our integrity or settle for second best. Really, though, how could we? We serve one of the greatest soft- ware communities in the world! This brings me to my next point. I am absolutely ecstatic to have been bestowed the honor of directing the editorial path of php|architect. Our authors, our readers, and our editorial team have all worked hard to build an excellent resource that brings you the best that the PHP world has to offer each and every month. The hardest part of my new role here at php|a will probably be trying to fill Brian’s shoes – he’s got really big feet.* Brian has worked extreme- ly hard to foster long-term relationships with our authors, and I will be working feverishly to continue to build and maintain that community, as well as various other initiatives on the front and back-end of the publication. But don’t worry, I’m still sleeping four hours a night. I sincerely hope you enjoy this month’s issue. People lost hair, sleep, and teeth over it. And, as always, if you see anything you particularly like or don’t like in our magazine this month, I strongly encourage you to send us your feedback at EDITORIAL editors@phparch.com. Even fan letters firmly stating that “You suck.” will be warmly accepted, as they help to break up the large amounts of spam that we all get from that address. * Actually, I’ve never physically seen Brian, or Brian’s shoes . I’m pretty sure I can smell them, though. September 2003 ● PHP Architect ● www.phparch.com 7 EDITORIAL When in Rome . Go to PHP Day 2003! T he first conference dedicated exclusively to the Italian PHP Community, called PHP Day 2003, will take place on October 24, 2003 in Rome at the Universita’ Tor Vergata. The program includes several speakers from the Italian technical community, and focuses on the theme of interface development, as well as a few tutorials to get the beginners up and running. Most of all, PHP Day revolves around the concept of providing the PHP com- munity with an opportunity to meet and exchange their experiences. If you live in Italy, this is a great opportunity to meet your fellow PHP enthusiasts. If you don’t live in Italy . this might be the perfect excuse for that long-postponed vacation! For more information on PHP Day, visit http://www .phpday.it or mail the organizers at staff@phpday .it . PHP 4.3.3 PHP.net announced the release of PHP 4.3.3. This release contains a large number of bug fixes and it is recommended that all users ugrade to this ver- sion. Changes include: • Synchronized bundled GD Library with GD 2.0.15 • Upgraded the bundled Expat Library to version 1.95.6 • Improved the engine to use POSIX/socket IO where feasible • and much more . Visit to php.net download or view the change log. Apache Cocoon 2.1 Apache Cocoon is a web development frame- work built around the concepts of separation of concerns (making sure people can interact and collaborate on a project, without stepping on each other toes) and component-based web development. Cocoon implements these concepts around the notion of ‘component pipelines’, each component on the pipeline specializing on a particular opera- tion. This makes it possible to use a Lego(tm)-like approach in building web solutions, hooking together components into pipelines without any required programming. Cocoon is “web glue for your web application development needs”. It is a glue that keeps con- cerns separate and allows parallel evolution of the two sides, improving development pace and reducing the chance of conflicts. Cocoon has a PHP Generator which is not includ- ed in the binary distribution but can be found at: cocoon.apache.org/2.1/ userdocs/generators/php-generator.html Get more information or download from the Cocoon Project Page: cocoon.apache.org/ What’s New! NEW STUFF php|a ZEND Studio 3.0.0 Beta Zend.com announced this month the release of the Zend Studio 3.0.0 Beta for Windows and Mac. The latest release includes: • Code Profiler – Determine which scripts are slowing down your project so you can focus your time on improving their performance • One-click debugging and profiling tool – Direct debugging and profiling of web pages directly from your browser • Code Analyzer – Pinpoint messy code, allowing you to write cleaner more correct code • Highlight syntax errors – Write clean PHP code while you are typing • Support for PHP 5.0 – Including syntax highlighting, code completion, file and proj- ect inspectors • Dramatic performance improvements • Code Completion improvements – Including improve speed, recognized con- stants, and new functions arguments view .and much more Get more information or download from Zend.com. PhpBB 2.0.6 The phpBB Group is pleased to announce the release of phpBB 2.0.6 the “phew, it’s way to hot to be furry” Edition. This release had been made to fix a number of potential security related issues and more annoying bugs. Work continues on 2.2.0 and another 2.0.x release is not planned except where critical issues arise. phpBB.com describes phpBB as: ” .a high powered, fully scalable, and highly customisable open-source bulletin board package. phpBB has a user-friendly inter- face, simple and straightforward administra- tion panel, and helpful FAQ. Based on the powerful PHP server language and your choice of MySQL, MS-SQL, PostgreSQL or Access/ODBC database servers, phpBB is the ideal free community solution for all web sites.” phpBB strongly advises all users to upgrade. Get more information for phpBB.com. Japha 1.3.3 The Japha site touts it as “An Expandable Implementation of Java in PHP”. From Japha: (japha.xzon.net/index.html) “Japha is an attempt to bring the main classes in the Java 1.4.1 (soon to be 1.4.2, time allow- ing) to PHP for use in everyday programs. We do this using the syntax that has been made common with the new releases of PHP 5. This allows us to easily implement interface, abstract classes, and more inheritance capa- bilities, not to mention excellent error han- dling and the ability to better conform with user-created data types.” Get more information or download the latest version from Japha.xzon.net LightBulb 4.79 LightBulb (formerly EzSDK) is a PHP SDK which includes a PHP source code generator, a library of PHP Classes, and an application environment con- sisting of premade supporting modules. The mod- ules handle user application and data access security, DB compatibility, a built-in GUI interface with an interactive desktop and more. Check out this month’s product review for more information. This release contains changes to the spell checking features. Spell checking of user data is now an inher- ent, interactive user option throughout the system. Developers are able to utilize the spell check features throughout every appli- cation developed without writing any source code to facilitate this. Get more information or view the demo at ezsdk.com September 2003 ● PHP Architect ● www.phparch.com 8 NNEEWW SSTTUUFFFF php|a W eb applications, by their very nature, have a broad exposure to remote attack- ers and a set of potential vulnerabilities as rich as the languages and protocols from which they are born. Web applications are han- dling an ever-growing list of business functions, and the code driving them must be paid due attention with regard not only to performance and stability, but also to security. This article is aimed at providing a concise list- ing and discussion of the most common vulnera- bilities that exist in PHP web applications. This vulnerability listing is used at the end of the arti- cle as the basis for developing coding and code audit/testing methodologies which can be applied to any PHP web application. Note that, for the sake of brevity, only the most common and severe vulnerabilities have been listed and that vulnerabilities outside the scope of PHP code – such as those which may exist in a web server or PHP itself – are not covered by this article. SQL Injection An SQL injection vulnerability can rear its ugly head when user-submitted variables are used to assemble SQL queries on the server side without sufficient input validation. The underlying SQL statement can be manipulated or additional SQL statements injected by an attacker. SQL Injection is one of the most common web application vul- nerabilities, but does not affect PHP code as much as other languages, mostly due to PHP’s automatic character escaping and built-in valida- tion functions. A sample vulnerability is shown in Listing 1. A sample attack on that vulnerability might look like the following: Note that the value being passed to artid is a urlencoded version of “0 or ArticleID <> 0”. Making a call to the link above would cause the following value to be assigned to $ssql and exe- http://www.server.com/listing1.php?artid= 0%20or%20ArticleID%20<>%200 NOTE: All examples use the HTTP GET method so that attacks can be easily illus- trated as URIs. Keep in mind that using POST is no defence; the variables are simply in the HTTP message body rather than the query string component of the URI. From a theoret- ical perspective, at least, POST variables are just as easy to manipulate as GET variables. September 2003 ● PHP Architect ● www.phparch.com 9 FEATURE Secure PHP Coding by David Jorm and Jody Melbourne PHP: 4.0+ OS: N/A Applications: N/A Code Directory: secure_php REQUIREMENTS cuted on the SQL server: Some database servers also allow multiple SQL statements to be concatenated using a semi- colon (;) as a separator. In that case, the follow- ing attack could be used: In this case, the urlencoded value being passed into artid is “0; DROP TABLE Articles”. You can imagine the problems that this might cause. The key to protecting code against SQL injec- tion attacks – also key for protecting against most web application vulnerabilities – is rigor- ous input validation. PHP can automatically escape some characters, such as apostrophes (‘), providing protection against attacks involv- ing those characters, but this is not sufficient immunity. All user-controlled variables used to construct SQL statements or other commands must be stripped of any content that may alter the effects of the query. For numeric inputs, either verify that the value is indeed numeric, or make it numeric using settype() . For non- numeric inputs, run the variable through addslashes() or addcslashes() before using it to construct a query. The vulnerable example above is patched in Listing 2. More information on patching against SQL injection is available at www.zend.com/manual/security.database.php. In testing for SQL injection, the blackbox tester studies application inputs and attempts to insert special characters (such as commas, apostrophes, semicolons, quotation marks, and equal signs) or SQL keywords (AND, OR, SELECT, INSERT, etc). With many of the popular backends, informa- tive error pages are displayed by default, which can often give clues to the underlying SQL query in use. For example, asking for instead of could return a telltale error like this one: It is evident from this response that the value for itemID is being used directly (without any val- idation) within an SQL query. PHP Code Injection When user-defined inputs form the file path parameters used to call include() , fopen() or other similar functions, there are several possi- bilities for exploitation. The first, PHP code injec- tion, is based on manipulating the input to include() to run your own PHP code. The sec- ond, path traversal, is based on manipulating the input to include() or fopen() to display files or create an open proxy. Note that both of these bugs rely on the same basic problem and overlap somewhat. PHP code injection is similar to SQL injection, but involves native PHP code being injected by the user rather than SQL. This is made possible when the code makes use of the include() func- tion. The include() function will accept a file name or URI (if the appropriate wrapper is installed) and include the contents of the resource as part of the PHP program. This is fre- quently used as a means of keeping libraries of code separate, and applications more modular, mySQL error with query SELECT myitem FROM shop_item WHERE itemid=123’;: You have an error in your SQL syntax near ‘’’ at line 1 http://example.com/items.php?itemID=123 http://example.com/items.php?itemID=123’ http://www.server.com/listing1.php?artid= 0;%20DROP%20TABLE%20Articles SELECT ArticleContents FROM Articles WHERE ArticleID = 0 OR ArticleID <> 0 September 2003 ● PHP Architect ● www.phparch.com 10 FFEEAATTUURREESS Secure PHP Coding 1 <?php 2 3 // sqlinject.php 4 $ssql=”SELECT ArticleContents FROM Articles WHERE ArticleID = “ . $_GET[‘artid’]; 5 $conn=mysql_connect(‘127.0.0.1’, ‘dbuser’, ‘dbpw’); 6 $res=mysql_query($ssql, $conn); 7 while ($resarr=mysql_fetch_row($res)) { 8 echo “<span id=\”article\”>” . $resarr[0] . “</span>\n\”; 9 } 10 mysql_close($conn); 11 12 ?> Listing 1 1 <?php 2 3 //sqlinjectpatched.php 4 if (!is_numeric($_GET[‘artid’])) 5 die; 6 $ssql=”SELECT ArticleContents FROM Articles WHERE ArticleID = “ . $_GET[‘artid’]; 7 $conn=mysql_connect(‘127.0.0.1’, ‘dbuser’, ‘dbpw’); 8 $res=mysql_query($ssql, $conn); 9 while ($resarr=mysql_fetch_row($res)) { 10 echo “<span id=\”article\”>” . $resarr[0] . “</span>\n”; 11 } 12 mysql_close($conn); 13 14 ?> Listing 2 [...]... cycle of bugs This information, however, is not enough for a successful bug tracking process In order to make your process efficient, the QA department 21 FEATURES Introduction to Bug Management needs to supply useful bug reports to the development team The more information developers have to work on, the sooner the bug will be traced and fixed When submitting a bug report, there are a few things to keep... submit bug report Owner Developer fixes the bug Project manager reviews the bug report and assigns it if necessary QA verifies that bug is fixed Bug gets closed The bug life cycle would look like this: quality assurance person finds the bug and submits the bug report Project manager reviews every bug report If he finds that the bug is valid, he assigns some attributes to the bug and assigns it to the... so that it returns only customers with no addresses: SELECT * FROM CUSTOMER, CUSTOMER_ADDRESS_COUNT WHERE CUSTOMER.CUSTOMER_ID = CUSTOMER_ADDRESS_COUNT.CUSTOMER_ID AND NO_OF_ADDRESSES = 0 29 FEATURES Advanced Database Features Exposed Listing 2 1 . PHP's printer functions from Windowsfrom Windows Introduction to Introduction to Bug ManagementBug Management Understand the need, the solutions,Understand. system. Anatomy of a bug Now is a good time to see what bug attributes we need in order to successfully track our bugs. Components Components help us to partition