Domain: php.net
Stories and comments across the archive that link to php.net.
Stories · 193
-
Which PHP5 Framework is Your Favorite?
matt_j_99 asks: "With all the talk about Ruby on Rails, I've been thinking about PHP frameworks. Ruby on Rails looks pretty cool, but frankly, I don't want to learn a new language. It seems that with all the slashdot discussion about RoR, somebody always makes the valid point that PHP is not a framework. But with PHP5's, Object Oriented features, a standard framework might emerge. Prado, Carthag, BlueShoes, and PHITE all seem like interesting frameworks. What PHP frameworks have you used in your applications? What were the pros and cons of each? Which framework do you think will have the best chance of long-term viability and maintenance?" -
Which PHP5 Framework is Your Favorite?
matt_j_99 asks: "With all the talk about Ruby on Rails, I've been thinking about PHP frameworks. Ruby on Rails looks pretty cool, but frankly, I don't want to learn a new language. It seems that with all the slashdot discussion about RoR, somebody always makes the valid point that PHP is not a framework. But with PHP5's, Object Oriented features, a standard framework might emerge. Prado, Carthag, BlueShoes, and PHITE all seem like interesting frameworks. What PHP frameworks have you used in your applications? What were the pros and cons of each? Which framework do you think will have the best chance of long-term viability and maintenance?" -
Spring Into PHP 5
Michael J. Ross writes "A professional programmer could at any time be tasked with developing a nontrivial application using a language or Web technology with which he or she is unfamiliar. A common response is to quickly scan code snippets in Internet newsgroups and online tutorials, copy and paste code that looks applicable to the task at hand, and then lose valuable time trying to make it all work and control what was created -- not unlike Dr. Frankenstein's experience. A smarter approach is to learn the language basics in sequence as rapidly as possible, not getting bogged down in excessive sample code. For developers seeking to learn PHP using the latter approach, Steven Holzner's Spring Into PHP 5, published by Addison-Wesley, would be an excellent choice." Read on for the rest of Ross's review. Spring Into PHP 5 author Steven Holzner pages 340 publisher Addison-Wesley rating 8 reviewer Michael J. Ross ISBN 0131498622 summary A comprehensive and no-nonsense primer on the basics of PHP.
This title is another entry in Addison-Wesley's promising "Spring Into" series, which, as suggested by the name, is aimed at developers who want to jump into a new technology and get up to speed as quickly as possible, but without missing any of the essentials. In the case of Holzner's PHP book, this goal is pursued by presenting the information in so-called "chunks," with each spanning just a few pages. Every chunk attempts to cover only one or a few related ideas, and is designed to build upon earlier chunks. The bulk of the explanation takes the form of code samples, which fortunately are short enough in length and clear enough in composition to be easily digestible. This is in stark contrast to far too many other programming books on the market, whose code samples can span multiple pages, making it difficult for the reader to discern all of the ideas that the author is trying to get across -- especially when the reader has to flip back and forth between pages. Even worse is how some authors (such as Deitel and Deitel) use lengthy code listings -- sometimes even complete applications -- to demonstrate many ideas at once, which can be quite confusing, especially for the newbie reading about a challenging language for the first time. As Holzner notes in his preface, his book is example-oriented, with dozens of tested code samples. But none are overwhelming.
Spring Into PHP 5 was published on 12 April 2005. It is organized into nine chapters, covering a range of topics: PHP essentials; operators and flow control; strings and arrays; functions; PHP in HTML pages; Web forms and input validation; object-oriented programming and file handling; PHP and databases; cookies, user sessions, FTP, e-mail, and hit counters. The book has two appendices. The first one, on PHP language elements, is remarkably complete, considering that it only fills 18 pages. Owners of the book will likely find themselves turning to this material quite frequently. The second appendix lists the most commonly used functions in PHP, particularly those dealing with arrays, strings, and files. These two appendices combined go a long way to making this book more than an approachable primer -- it could serve as a reference book for the language for any reader not required to dig into the more obscure intricacies of PHP. Readers with those needs will have to use more detailed sources, such as the online PHP Manual.
Each one of Holzner's chapters explains the core concepts, using the bite-sized chunks mentioned earlier. This approach is somewhat similar to the "recipes" found in many books published by O'Reilly Media, and it works well here for introducing a computer language. Holzner's writing style is clear yet never condescending, and concise yet never cryptic. The intended reader only really needs an understanding of simple HTML and how to edit text files, to make this book worthwhile and usable. The book is meaty with information, and yet not too lengthy. This is a refreshing change of pace from countless other computer language books that are bloated with redundant sample code and overly wide margins, apparently in an attempt to entice the consumer with maximum page count per dollar.
Some programming books try to move the novice along at too rapid a pace, which can get quite discouraging if and when the reader is unable to follow the discussion, and particularly if trying to follow the author in building a working example. But a far more common mistake among programming books, is to drag out the process with humongous code listings or redundant verbiage (such as following the senseless rule of telling the reader something three times -- a technique that makes far more sense for speechwriting). Holzner sets and maintains an excellent pace, partly by keeping the code snippets reasonably sized, and partly through his modular approach of presenting ideas in chunks.
The physical book itself is well made and attractive, with a readable font face and size, and intelligent use of bolding to highlight those lines of code upon which the reader should focus. My only complaint in terms of the presentation, is that the gray background used for the code samples could be lightened up a bit, to make the text itself stand out more, especially the bold text. All of the screenshots are in black-and-white, which works just fine, as there would be no value in using color in the majority of the sample Web pages.
The author does an excellent job of explaining and illustrating all of the most commonly used and needed elements of the language. But he provides little guidance as to when a particular technique or approach should be used over another. For instance, when explaining how the programmer can use PHP to connect to a MySQL database, the author presents two alternatives -- direct layer and Pear::DB -- but no recommendations as to the choice of one over the other. On the other hand, one might argue that to include recommendations of techniques, as well as language best practices, would require the book to be much longer than it is, which would detract from the book's goal of getting a programmer up to speed on PHP in an efficient manner. The serious programmer who wishes to take PHP to the next level, can be expected to read more advanced books, to learn from expert PHP developers posting in online newsgroups, and to learn from experience as the programmer creates his or her own applications.
Another potential point of criticism could be that the book does not adequately explain how to use PHP with the various available database systems, only covering MySQL (the industry's favorite for use with PHP). But the database chapter, number 8, provides just enough information for the beginner to get started and to try out the basics. For simple database needs, the material in that chapter might be sufficient. Yet for more extensive MySQL usage, including installation and administration, other resources will need to be consulted. This book is clearly not intended to be one of those PHP + MySQL combo books that have proven so popular during the past few years.
The publisher's Web site for the book does not appear to have any collection of errata. Here are some that I found: On page 6, in the NOTE, "scripts can be used" should read "scripts cannot be used." On page 20, "#/ message to the user" should read "# message to the user." On page 49, in Table 2-4, in the last line, the formatting is partly wrong. Examples 3-1 through 4-14 contain incorrect indentation. On page 158, the last line in the $_FILES['userfile'] values is missing $_FILES['userfile']['error']. In Examples 5-19 and 5-20, the <head> and <h1> tags are missing ": Take 1." On page 169, the formatting of Example 6-2 is inconsistent with the others.
Aside from the errata, there were some other weaknesses -- none of them serious: The chapter summaries are useless, like in most other technical books, as there's not enough details to be instructive, and more details would make them even more redundant and space-consuming. On page 176, in Figure 6-6's caption, "Navigating" should be "Redirected." On page 197, the discussion of HTTP authentication is too brief to enable the typical reader to implement it. For instance, there is no mention of where to set $_SERVER[ 'PHP_AUTH_USER' ] to make it work. Chapter 7, on object-oriented programming and file handling, should be split into two chapters. Combining them makes no sense, and the author does not even transition from the first topic to the second.
Like others in the "Spring Into" series, this title is reasonably priced, at only $29.99 list for over 300 pages of quality material. The publisher, Addison-Wesley, has a page on their Web site devoted to the book, which includes a book description, a table of contents, an index, source code from the book, and a link for downloading a sample chapter (in PDF format), namely, Chapter 3, which covers strings and arrays. The site also has a link to a bonus chapter (also in PDF) that explains how to draw graphics interactively on a Web server and then send them back to the browser. Oddly enough, the page's title is "Spring Into PHP 5 - $20.99," but there's no indication as to how to get the book for only $20.99. That could simply be a typo. But there is a link to purchase the book online for $26.99. For those looking to spring into Web server-side development in general, or PHP in particular, it would be money well spent.
Michael J. Ross is a freelance writer, computer consultant, and the editor of the free newsletter for PristinePlanet.com. You can purchase Spring Into PHP 5 from bn.com. Slashdot welcomes readers' book reviews -- to see your own review here, read the book review guidelines, then visit the submission page. -
Suggested Curriculum for 'Complex Websites' Class?
StudMuffin asks: "I teach graduate computer science courses at a Big 10 university to grad students, who have never programmed before and are studying Human-Computer Interaction or other Information Science specialties. These courses are usually their first dip into the programming pool, so we have tons to cover in three months. This fall, I have been asked to take over and redesign our 'Complex Website' course, which is getting a bit long in the tooth. This course has traditionally been about database backed websites with server-side scripting. My only requirements are that there be coverage of PHP and that we have basic instruction about persistence using a database (which must be MySQL). However, I believe that the nature of 'complex' websites has changed, with XHTML, CSS, Javascript, web services, and so on. Sites like Google Maps make the browser feel like a fat client and are making the web browser a true window onto enormous data sets, and take into consideration the MoRAS of small views on large worlds. What do Slashdot readers consider a reasonable curriculum would be for a redesigned course like this?" -
PHP & AJAX Presentation Online
the.admin.man writes "There's been quite a bit of buzz around using PHP as a backend to AJAX-based web applications (the same development methodology on which some Google applications), lately, particularly after the release of JPSpan, a framework that helps building XML-based interfaces between Javascript and PHP apps. Just yesterday, Joshua Eichorn gave a presentation to the Arizona PHP Group on developing AJAX applications for PHP--he's posted the slides online, and will give his presentation again through a free webcast hosted by php|architect." -
Drupal 4.6.0 Released
ajayg writes "Drupal is IMHO one of the best open sourced Content Management Systems out there. The Drupal community has just released version 4.6.0 of their PHP based CMS which finally provides support for PHP5. The release follows 6 months of development, and includes -- among other changes -- better search function as well as usability improvements for permissions, block configuration, statistics tracking, logs, forum configuration, content administration, etc." -
Apple's First 2005 Mac OS X Security Update Is Out
ollie_ob writes "Security Update 2005-001 has just hit Software Update for Mac OS X users, for those running 10.3.7 and 10.2.8 in both normal and server flavours of the OS. The update includes patches for: at commands, ColorSync, libxml2, Mail, PHP, Safari and SquirrelMail. Details are here. One of these fixes -- a modification to Apple Mail so it stops broadcasting your MAC address in plain text every time you send an email - will come as a welcome relief to those trying to keep their WEP-based wireless networks secure. Other highlights are PHP 4.3.10, and a Safari fix so that pop-up windows can't mislead users as to their apparent origin. The Mac OS X Server version of the patch also includes an update to SquirrelMail that stops browsers from executing scripted content in emails viewed(!). Interesting to note Apple's new naming scheme for the updates (last year, some updates came out dated days into the future - or past.) Also, there's a unified page for all future security updates." -
PHP Automated Administrivia?
wikinerd asks: "I am sure all of you know what PHP is and many of you may even use it on your websites, like me. Some of you may have read a this article from Linux.com article that gives some examples on how to use PHP to automate your server administration tasks (or to say it with one word: administrivia). I wonder whether there are any Slashdot users that have already used PHP in their administrivia, and what the results are. Is PHP appropriate for this task? If you have written useful PHP scripts, would you consider to publish their source code here? I am sure that posting your scripts can be beneficial to many new (and old) admins, so let's share our work!" -
Is Apache 2.0 Worth the Switch for PHP?
An anonymous reader writes "It seems like some of the members of the Apache Software Foundation are a little angry with the PHP Community because they don't recommend using Apache 2.0 with PHP. Since PHP is installed on half of all Apache servers this is a major issue for them. A number of high-profile PHP community members such as John Coggeshall and Chris Shiflett have blogged about this decision in light of a recent posting by Apache Software Foundation Member Rich Bowen which called PHP's anti-Apache2 stance FUD. Is there any real reason for the PHP community to start recommending Apache 2.0, especially when the 1.3.x series of Apache is rock solid and proven? Note Rich did later commend PHP for being a great product, so it's not all flames." -
PHP Vulnerabilities Announced
Simone Klassen writes "The Hardened-PHP Project has announced several serious and according to them, easy-to-exploit vulnerabilities within PHP. A flaw within the function unserialize() is rated as very critical for millions of PHP servers, because it is exposed to remote attackers through lots of very popular webapplications. The list includes forum software like phpBB2, WBB2, Invision Board and vBulletin. It is time to upgrade now." -
Linus, Monty, Rasmus: No Software Patents
Jan Wildeboer writes "The three most famous European authors of open-source software have issued an appeal against software patents on NoSoftwarePatents.com. Linus Torvalds (Linux), Michael "Monty" Widenius (MySQL) and Rasmus Lerdorf (PHP) urge the EU Council, which will convene later in the week, not to adopt a draft directive on software patents that they consider "deceptive, dangerous, and democratically illegitimate". They also call on the Internet community to express solidarity by placing NoSoftwarePatents.com links and banners on many Web sites." -
The PHP Anthology - Volume II, 'Applications'
sympleko (Matthew Leingang) writes "In Volume I of The PHP Anthology, Harry Fuecks showed some of the basic PHP functionality to solve a few simple problems, including how to object-orient your code, how to use PHP's hundreds of built-in functions, and how to use well-developed existing classes, be they from PEAR or other sites. In Volume II, he intends to 'blow your socks off by tackling some traditionally complex problems with the same principles--to great effect.' It's summertime and I'm sandals-only for the time being, so my socks remain safely in the top drawer. But the volume is nonetheless exciting." (Read on for the rest of Leingang's review, and check out last week's review of Volume I.)There are seven chapters in this volume, each dealing with real-world problems. Many problems are those you've seen solved on sites you admire and wondered "How did they do that?" Others are frameworks that allow your site to run smoothly, with nobody getting accidentally logged out or having to wait too long while your script gluttonously pulls the same data out of the database for the Nth time. At the end, Fuecks goes back to the beginning, to show how proper design and development can save you time when you start your next project.
Chapter 1: Access Control
Authentication is the process by which users identify themselves. This is difficult in HTTP, a stateless protocol in which the server handles one request at a time and instantly forgets you. Luckily HTTP allows cookies, which are bits of data the server sends to the client for to reveal upon revisiting. At first cookies were used only to annoy ("Hello, Steve! You have visited this page 3 times"), but a cookie can hold the ID of a session record in a database, which contains any state-information that you like.You can authenticate without sessions via HTTP server configuration, as long as you like the dull dialog box the browser pops up when users enter a restricted area. Oh, and you don't mind the fact that users won't be able to "log out" without quitting their browser, nor can you force a logout after a certain timeout value. Nor can you allow users to register themselves... these are all existing, solved problems and the author shows some of the best solutions. Common tasks like allowing users to change their passwords, recover their passwords if (I mean when) they forget them, and arranging users in groups to which you assign common permissions are also covered.
My favorite example from this chapter is the humans-only registration application. Remember when online voting for the Major League Baseball All-Star Game first started? Anyone who knew how to write a web client could have automated a task to vote as many times as the server could handle, and have his favorite players be the all-star team.* To bring it closer to home, what if somebody decides to bog down your site by automatically registering a huge number of times and filling up your database? You can keep these things from happening by making users look at images which contain text but are hard for computers to "read." PHP is in use at all stages of this game, from writing the registration form's HTML to generating the obscured image on-the-fly.
Chapter 2: XML
XML is a fact of life and, hype aside, is a great way to store and transmit machine-readable data. One of the most visible applications is the thousands of bloggers and news sites providing XML feeds of their headlines. You can write portal sites that grab these headlines, parse them all and present them on your site with links to the full text at the source.There are two ways to parse XML: with events, or by using the Document Object Model (DOM). The methodologies are similar to reading a plain-text file line-by-line or all at once. Using events you can implement a finite-state machine based on which tags and text come down the pike. Or you can slurp the whole document into memory and find any part of it with ease. The built-in library for the former is based on the popular Simple API for XML (or SAX; don't you like those nested acronyms?), while the latter often uses Xpath to find the particular document nodes you want.
The author shows how to parse RSS feeds with both SAX and the DOM, and how to render a feed with DOM. Further, you can use Extensible Stylesheet Language Transformations (known as XSLT) to transform XML -- whether it's to XHTML for regular browser reading, WML (Wireless Markup Language) for viewing on mobile phones, or even SQL to communicate with a database.
Another exciting XML application is in the area of web services, in which agents (often but not necessarily web servers) communicate with each other over an XML-based protocol built on top of PHP. The two most popular protocols are XML-RPC (the RPC stands for "Remote Procedure Calls") and SOAP (which used to stand for "Simple Object Access Protocol" but now is just a name). Often-changing information such as stock prices and weather are often offered through web services, but they can also be used as an object API between agents over the network. What's cool about using SOAP is you can publish to clients exactly what services you offer and how they can call them using the Web Services Description Language (WSDL).
Chapter 3: Alternative Content Types
If you've ever printed out a web page that was designed for browser viewing, you know the less-than-desired effect. The navigational elements, search boxes, and banners, while necessary for the web page, are useless once a static copy is printed. Furthermore, you need to extend your site to include users with less-featured browsers, such as mobile phones.Fortunately, PHP has been taught many languages. PDF is the standard for print-quality documents, and there are several libraries (free and non-free) which allow you to generate them. WML is the HTML of cell phone browsers, in which screen space is at a premium and bandwidth scarce. SVG is an XML application which allows vector-based images like PostScript does. The coolest example, however, uses XUL (the XML User interface Language, not to be confused with Zool) to make full GUI applications that you run through Mozilla. This isn't useful for the outside world where you can't force your users to use Mozilla (sigh), but works well for intranet applications that run on a variety of platforms.
The author also brings up in this chapter an HTML SAX parser he has written. You can process HTML pages chunk-by-chunk and extract the pieces you want. I hadn't known about such a class until I read the book and I'm very excited I know about it now. For sometimes it's necessary to parse a web page meant for humans to read (perhaps to pretend to be a user and automate your all-star voting), and most HTML pages won't validate as HTML, let alone XML.
A good point here is that a well-designed, tiered application will allow you to swap out different presentation classes with little code rewrite. Separating the tasks of extracting the data from the database and presenting to the user in variety of formats is a common task that when done right becomes subsequently easier.
Chapter 4: Stats and Tracking
Once your site is up and running, you'll be interested to know which parts are the most active, and how much traffic you're getting. Into a dynamic page you can obviously insert any logging mechanism, but a great place to put it is inside your site's logo. PHP can send binary data as easily as text. Why would you want to do this?- The logo is usually on every page (or it should be). You don't have to cut-and-paste code.
- You can serve the image, then use the flush command to send the output on and do extra processing. This way logging doesn't get in the way of page rendering.
There are lots of packages available to collect and analyze data. The author goes through phpOpenTracker which is quite rich in features. There are also ways to collect data on what links users follow to leave your site, and to keep requests from search engines from cluttering your log files.
Chapter 5: Caching
Another possible knock against PHP is that, while it's good to have dynamic pages, some pages are unnecessarily so. This is a waste of server resources to keep rendering the same page anew. There are different ways to conserve.On the client side, you can use HTTP 1.1 headers like Cache-control and Expires to tell browsers when it's okay to store cached copies locally
On the server side, as can be expected, you have a greater level of control. You can use output buffering to delay sending of output to the browser, then save a copy of the output locally. On subsequent requests, you can serve the file rather than generate the HTML all over again. This can be implemented on a chunk (or block) level, so that you can keep some parts ultra-time sensitive and others not so much. The package PEAR::Cache_Lite can help with this.
Chapter 6: Development Technique
The last two chapters were my favorites of the two-volume set. They are on a higher level of abstraction than the features of PHP's library of functions, or previous five chapters on real-world solutions. After you've reached a certain level of expertise in PHP coding, you being to wonder about the "right" way to do things. The author shows how to use Xdebug to find bottlenecks in your code, as well as a few quick optimization tips (for instance, design your flow control so that the first choice is the one most often taken).He then discusses the principles of N-tiered design. N is usually 5, but the data layer (usually a database or file system) and presentation layer (usually the browser) are most often handled outside of PHP, so you normally have three levels to worry about:
- Data Access: Getting data from the outside world into your application
- Application Logic: Doing whatever unique thing your application is supposed to do
- Presentation Logic: Forming a response in a format acceptable to your client
Keeping these layers separate and restricting them to communicating through well-defined interfaces allows you maximum flexibility. If you need to change databases (say you just got venture capital money and can afford Oracle now), you can do so only changing one layer. If you want to serve different flavors of HTML, or different markup languages altogether, or binary data, you can do so by only changing one layer. You can even strive for maximum distributability by enabling your layers to "live" on physically independent machines and communicate with XML-RPC or SOAP.
Documenting your code is essential. Anybody who's been programming for over a year has gone back to code he or she's written and thought, "Now what the heck was this supposed to do?" It's even more essential when you write something and wish to distribute it for the benefit of others. You can expect them to grok your code at an even lower rate since they didn't write it the first time.
Luckily, scripted languages like PHP are excellent at parsing text files, including PHP scripts themselves. Using well-defined documentation formats akin to JavaDoc, you can embed documentation in your code inside comments, and use tools like phpDocumentor to extract these documentation blocks and format them as nice, cross-reference HTML. In fact, writing doc blocks before your code is a good way to think ahead about how you want your classes and methods to work.
Unit Testing, one of the most digestible dogmas of Extreme Programming, is an awesome way to test your code for logic errors. You build up tiny test cases (using mock objects to isolate the class you're testing) and build as many as you like. Once you do this (PHPUnit and SimpleTest are two rich frameworks), you keep your tests and each time you add features, you run your test to make sure you haven't added bugs as well.
Chapter 7: Design Patterns
Design Patterns is one of the modern classics in information technology. After having done OOP for a while, you will inevitably get the feeling of deja vu that you've solved a problem before. Not so concretely as "I need a database abstraction layer," or "I need a templating system," but as in "I need a way to create objects without specifying exactly what class they belong to," or "I'm tired of writing so many if statements." Design patterns are common object architectures which can be used to solve common (though unique) problems.Many design patterns are more suited to state-equipped applications with GUIs, but there are plenty to assist the PHP coder. The Factory Method is a pattern through which an object can create other objects of varying classes. So instead of writing mysql_connect everywhere, then having to change every occurrence of that function, you can abstract all database interaction to a class, then instantiate a database connection through a class method of another class: $db = MyApp::getDatabaseConnection(). This is useful when the connection (not just the RDBMS, but the actual database) you want varies depending on whether you are developing, testing, or going live with your application. Factory methods are also a good way to avoid global configuration variables.
The Iterator Pattern and the Observer Pattern are two others mentioned in this chapter. Iterators are used often in paging through database results. Observers are used to let objects notify other objects of changes in their state. This chapter will make you want to go read the whole Gang-of-Four book if you haven't already.
My biggest beef with the book is that this wasn't presented earlier on, perhaps at the beginning of Volume II. As a climax, it leaves me flat, wondering how the rest of the volume could have been derived from this very cool concept. But most PHP books conclude with chapters on how to extended PHP on the C level, or giant case studies involving massive code dumps, and I'm often not satisfied with them. This is a nice philosophical note to go out on. And there's something to be said for the argument that books like these aren't written to be read cover-to-cover.
Appendices
The book closes with the same indices as in Volume I. Since I don't know the URL of my review of that volume, I'll just copy: You can read about which configuration directives you're probably most interested in (the complete list you can get on PHP's web site), some common security breaches, and how to install PEAR, PHP's version of CPAN. My favorite appendix is the "Hosting Provider Checklist," a great reference for evaluating whether kewlhosting.com is going to give you the freedom and support you need to make a great hosted web site.This volume was informative, well-written, and inspirational in that it made me want to go out and add cool and useful features to my web sites. Check it out if you can.
*Not really (not that I tried or anything), but they've always been a little bit smarter about it. You get my point, though. This did happen on an ESPN.com Page 2 mascot popularity contest, but they noticed through request headers that millions of votes were coming from the same place, and invalidated all those votes.
In real life, Matthew Leingang is Preceptor in Mathematics at Harvard University. He promises to review any book sent to him for free, and sometimes actually does it. Both volumes of The PHP Anthology are available from SitePoint. Slashdot welcomes readers' book reviews; to see your own review here, carefully read the book review guidelines, then visit the submission page.
-
The PHP Anthology - Volume II, 'Applications'
sympleko (Matthew Leingang) writes "In Volume I of The PHP Anthology, Harry Fuecks showed some of the basic PHP functionality to solve a few simple problems, including how to object-orient your code, how to use PHP's hundreds of built-in functions, and how to use well-developed existing classes, be they from PEAR or other sites. In Volume II, he intends to 'blow your socks off by tackling some traditionally complex problems with the same principles--to great effect.' It's summertime and I'm sandals-only for the time being, so my socks remain safely in the top drawer. But the volume is nonetheless exciting." (Read on for the rest of Leingang's review, and check out last week's review of Volume I.)There are seven chapters in this volume, each dealing with real-world problems. Many problems are those you've seen solved on sites you admire and wondered "How did they do that?" Others are frameworks that allow your site to run smoothly, with nobody getting accidentally logged out or having to wait too long while your script gluttonously pulls the same data out of the database for the Nth time. At the end, Fuecks goes back to the beginning, to show how proper design and development can save you time when you start your next project.
Chapter 1: Access Control
Authentication is the process by which users identify themselves. This is difficult in HTTP, a stateless protocol in which the server handles one request at a time and instantly forgets you. Luckily HTTP allows cookies, which are bits of data the server sends to the client for to reveal upon revisiting. At first cookies were used only to annoy ("Hello, Steve! You have visited this page 3 times"), but a cookie can hold the ID of a session record in a database, which contains any state-information that you like.You can authenticate without sessions via HTTP server configuration, as long as you like the dull dialog box the browser pops up when users enter a restricted area. Oh, and you don't mind the fact that users won't be able to "log out" without quitting their browser, nor can you force a logout after a certain timeout value. Nor can you allow users to register themselves... these are all existing, solved problems and the author shows some of the best solutions. Common tasks like allowing users to change their passwords, recover their passwords if (I mean when) they forget them, and arranging users in groups to which you assign common permissions are also covered.
My favorite example from this chapter is the humans-only registration application. Remember when online voting for the Major League Baseball All-Star Game first started? Anyone who knew how to write a web client could have automated a task to vote as many times as the server could handle, and have his favorite players be the all-star team.* To bring it closer to home, what if somebody decides to bog down your site by automatically registering a huge number of times and filling up your database? You can keep these things from happening by making users look at images which contain text but are hard for computers to "read." PHP is in use at all stages of this game, from writing the registration form's HTML to generating the obscured image on-the-fly.
Chapter 2: XML
XML is a fact of life and, hype aside, is a great way to store and transmit machine-readable data. One of the most visible applications is the thousands of bloggers and news sites providing XML feeds of their headlines. You can write portal sites that grab these headlines, parse them all and present them on your site with links to the full text at the source.There are two ways to parse XML: with events, or by using the Document Object Model (DOM). The methodologies are similar to reading a plain-text file line-by-line or all at once. Using events you can implement a finite-state machine based on which tags and text come down the pike. Or you can slurp the whole document into memory and find any part of it with ease. The built-in library for the former is based on the popular Simple API for XML (or SAX; don't you like those nested acronyms?), while the latter often uses Xpath to find the particular document nodes you want.
The author shows how to parse RSS feeds with both SAX and the DOM, and how to render a feed with DOM. Further, you can use Extensible Stylesheet Language Transformations (known as XSLT) to transform XML -- whether it's to XHTML for regular browser reading, WML (Wireless Markup Language) for viewing on mobile phones, or even SQL to communicate with a database.
Another exciting XML application is in the area of web services, in which agents (often but not necessarily web servers) communicate with each other over an XML-based protocol built on top of PHP. The two most popular protocols are XML-RPC (the RPC stands for "Remote Procedure Calls") and SOAP (which used to stand for "Simple Object Access Protocol" but now is just a name). Often-changing information such as stock prices and weather are often offered through web services, but they can also be used as an object API between agents over the network. What's cool about using SOAP is you can publish to clients exactly what services you offer and how they can call them using the Web Services Description Language (WSDL).
Chapter 3: Alternative Content Types
If you've ever printed out a web page that was designed for browser viewing, you know the less-than-desired effect. The navigational elements, search boxes, and banners, while necessary for the web page, are useless once a static copy is printed. Furthermore, you need to extend your site to include users with less-featured browsers, such as mobile phones.Fortunately, PHP has been taught many languages. PDF is the standard for print-quality documents, and there are several libraries (free and non-free) which allow you to generate them. WML is the HTML of cell phone browsers, in which screen space is at a premium and bandwidth scarce. SVG is an XML application which allows vector-based images like PostScript does. The coolest example, however, uses XUL (the XML User interface Language, not to be confused with Zool) to make full GUI applications that you run through Mozilla. This isn't useful for the outside world where you can't force your users to use Mozilla (sigh), but works well for intranet applications that run on a variety of platforms.
The author also brings up in this chapter an HTML SAX parser he has written. You can process HTML pages chunk-by-chunk and extract the pieces you want. I hadn't known about such a class until I read the book and I'm very excited I know about it now. For sometimes it's necessary to parse a web page meant for humans to read (perhaps to pretend to be a user and automate your all-star voting), and most HTML pages won't validate as HTML, let alone XML.
A good point here is that a well-designed, tiered application will allow you to swap out different presentation classes with little code rewrite. Separating the tasks of extracting the data from the database and presenting to the user in variety of formats is a common task that when done right becomes subsequently easier.
Chapter 4: Stats and Tracking
Once your site is up and running, you'll be interested to know which parts are the most active, and how much traffic you're getting. Into a dynamic page you can obviously insert any logging mechanism, but a great place to put it is inside your site's logo. PHP can send binary data as easily as text. Why would you want to do this?- The logo is usually on every page (or it should be). You don't have to cut-and-paste code.
- You can serve the image, then use the flush command to send the output on and do extra processing. This way logging doesn't get in the way of page rendering.
There are lots of packages available to collect and analyze data. The author goes through phpOpenTracker which is quite rich in features. There are also ways to collect data on what links users follow to leave your site, and to keep requests from search engines from cluttering your log files.
Chapter 5: Caching
Another possible knock against PHP is that, while it's good to have dynamic pages, some pages are unnecessarily so. This is a waste of server resources to keep rendering the same page anew. There are different ways to conserve.On the client side, you can use HTTP 1.1 headers like Cache-control and Expires to tell browsers when it's okay to store cached copies locally
On the server side, as can be expected, you have a greater level of control. You can use output buffering to delay sending of output to the browser, then save a copy of the output locally. On subsequent requests, you can serve the file rather than generate the HTML all over again. This can be implemented on a chunk (or block) level, so that you can keep some parts ultra-time sensitive and others not so much. The package PEAR::Cache_Lite can help with this.
Chapter 6: Development Technique
The last two chapters were my favorites of the two-volume set. They are on a higher level of abstraction than the features of PHP's library of functions, or previous five chapters on real-world solutions. After you've reached a certain level of expertise in PHP coding, you being to wonder about the "right" way to do things. The author shows how to use Xdebug to find bottlenecks in your code, as well as a few quick optimization tips (for instance, design your flow control so that the first choice is the one most often taken).He then discusses the principles of N-tiered design. N is usually 5, but the data layer (usually a database or file system) and presentation layer (usually the browser) are most often handled outside of PHP, so you normally have three levels to worry about:
- Data Access: Getting data from the outside world into your application
- Application Logic: Doing whatever unique thing your application is supposed to do
- Presentation Logic: Forming a response in a format acceptable to your client
Keeping these layers separate and restricting them to communicating through well-defined interfaces allows you maximum flexibility. If you need to change databases (say you just got venture capital money and can afford Oracle now), you can do so only changing one layer. If you want to serve different flavors of HTML, or different markup languages altogether, or binary data, you can do so by only changing one layer. You can even strive for maximum distributability by enabling your layers to "live" on physically independent machines and communicate with XML-RPC or SOAP.
Documenting your code is essential. Anybody who's been programming for over a year has gone back to code he or she's written and thought, "Now what the heck was this supposed to do?" It's even more essential when you write something and wish to distribute it for the benefit of others. You can expect them to grok your code at an even lower rate since they didn't write it the first time.
Luckily, scripted languages like PHP are excellent at parsing text files, including PHP scripts themselves. Using well-defined documentation formats akin to JavaDoc, you can embed documentation in your code inside comments, and use tools like phpDocumentor to extract these documentation blocks and format them as nice, cross-reference HTML. In fact, writing doc blocks before your code is a good way to think ahead about how you want your classes and methods to work.
Unit Testing, one of the most digestible dogmas of Extreme Programming, is an awesome way to test your code for logic errors. You build up tiny test cases (using mock objects to isolate the class you're testing) and build as many as you like. Once you do this (PHPUnit and SimpleTest are two rich frameworks), you keep your tests and each time you add features, you run your test to make sure you haven't added bugs as well.
Chapter 7: Design Patterns
Design Patterns is one of the modern classics in information technology. After having done OOP for a while, you will inevitably get the feeling of deja vu that you've solved a problem before. Not so concretely as "I need a database abstraction layer," or "I need a templating system," but as in "I need a way to create objects without specifying exactly what class they belong to," or "I'm tired of writing so many if statements." Design patterns are common object architectures which can be used to solve common (though unique) problems.Many design patterns are more suited to state-equipped applications with GUIs, but there are plenty to assist the PHP coder. The Factory Method is a pattern through which an object can create other objects of varying classes. So instead of writing mysql_connect everywhere, then having to change every occurrence of that function, you can abstract all database interaction to a class, then instantiate a database connection through a class method of another class: $db = MyApp::getDatabaseConnection(). This is useful when the connection (not just the RDBMS, but the actual database) you want varies depending on whether you are developing, testing, or going live with your application. Factory methods are also a good way to avoid global configuration variables.
The Iterator Pattern and the Observer Pattern are two others mentioned in this chapter. Iterators are used often in paging through database results. Observers are used to let objects notify other objects of changes in their state. This chapter will make you want to go read the whole Gang-of-Four book if you haven't already.
My biggest beef with the book is that this wasn't presented earlier on, perhaps at the beginning of Volume II. As a climax, it leaves me flat, wondering how the rest of the volume could have been derived from this very cool concept. But most PHP books conclude with chapters on how to extended PHP on the C level, or giant case studies involving massive code dumps, and I'm often not satisfied with them. This is a nice philosophical note to go out on. And there's something to be said for the argument that books like these aren't written to be read cover-to-cover.
Appendices
The book closes with the same indices as in Volume I. Since I don't know the URL of my review of that volume, I'll just copy: You can read about which configuration directives you're probably most interested in (the complete list you can get on PHP's web site), some common security breaches, and how to install PEAR, PHP's version of CPAN. My favorite appendix is the "Hosting Provider Checklist," a great reference for evaluating whether kewlhosting.com is going to give you the freedom and support you need to make a great hosted web site.This volume was informative, well-written, and inspirational in that it made me want to go out and add cool and useful features to my web sites. Check it out if you can.
*Not really (not that I tried or anything), but they've always been a little bit smarter about it. You get my point, though. This did happen on an ESPN.com Page 2 mascot popularity contest, but they noticed through request headers that millions of votes were coming from the same place, and invalidated all those votes.
In real life, Matthew Leingang is Preceptor in Mathematics at Harvard University. He promises to review any book sent to him for free, and sometimes actually does it. Both volumes of The PHP Anthology are available from SitePoint. Slashdot welcomes readers' book reviews; to see your own review here, carefully read the book review guidelines, then visit the submission page.
-
The PHP Anthology - Volume II, 'Applications'
sympleko (Matthew Leingang) writes "In Volume I of The PHP Anthology, Harry Fuecks showed some of the basic PHP functionality to solve a few simple problems, including how to object-orient your code, how to use PHP's hundreds of built-in functions, and how to use well-developed existing classes, be they from PEAR or other sites. In Volume II, he intends to 'blow your socks off by tackling some traditionally complex problems with the same principles--to great effect.' It's summertime and I'm sandals-only for the time being, so my socks remain safely in the top drawer. But the volume is nonetheless exciting." (Read on for the rest of Leingang's review, and check out last week's review of Volume I.)There are seven chapters in this volume, each dealing with real-world problems. Many problems are those you've seen solved on sites you admire and wondered "How did they do that?" Others are frameworks that allow your site to run smoothly, with nobody getting accidentally logged out or having to wait too long while your script gluttonously pulls the same data out of the database for the Nth time. At the end, Fuecks goes back to the beginning, to show how proper design and development can save you time when you start your next project.
Chapter 1: Access Control
Authentication is the process by which users identify themselves. This is difficult in HTTP, a stateless protocol in which the server handles one request at a time and instantly forgets you. Luckily HTTP allows cookies, which are bits of data the server sends to the client for to reveal upon revisiting. At first cookies were used only to annoy ("Hello, Steve! You have visited this page 3 times"), but a cookie can hold the ID of a session record in a database, which contains any state-information that you like.You can authenticate without sessions via HTTP server configuration, as long as you like the dull dialog box the browser pops up when users enter a restricted area. Oh, and you don't mind the fact that users won't be able to "log out" without quitting their browser, nor can you force a logout after a certain timeout value. Nor can you allow users to register themselves... these are all existing, solved problems and the author shows some of the best solutions. Common tasks like allowing users to change their passwords, recover their passwords if (I mean when) they forget them, and arranging users in groups to which you assign common permissions are also covered.
My favorite example from this chapter is the humans-only registration application. Remember when online voting for the Major League Baseball All-Star Game first started? Anyone who knew how to write a web client could have automated a task to vote as many times as the server could handle, and have his favorite players be the all-star team.* To bring it closer to home, what if somebody decides to bog down your site by automatically registering a huge number of times and filling up your database? You can keep these things from happening by making users look at images which contain text but are hard for computers to "read." PHP is in use at all stages of this game, from writing the registration form's HTML to generating the obscured image on-the-fly.
Chapter 2: XML
XML is a fact of life and, hype aside, is a great way to store and transmit machine-readable data. One of the most visible applications is the thousands of bloggers and news sites providing XML feeds of their headlines. You can write portal sites that grab these headlines, parse them all and present them on your site with links to the full text at the source.There are two ways to parse XML: with events, or by using the Document Object Model (DOM). The methodologies are similar to reading a plain-text file line-by-line or all at once. Using events you can implement a finite-state machine based on which tags and text come down the pike. Or you can slurp the whole document into memory and find any part of it with ease. The built-in library for the former is based on the popular Simple API for XML (or SAX; don't you like those nested acronyms?), while the latter often uses Xpath to find the particular document nodes you want.
The author shows how to parse RSS feeds with both SAX and the DOM, and how to render a feed with DOM. Further, you can use Extensible Stylesheet Language Transformations (known as XSLT) to transform XML -- whether it's to XHTML for regular browser reading, WML (Wireless Markup Language) for viewing on mobile phones, or even SQL to communicate with a database.
Another exciting XML application is in the area of web services, in which agents (often but not necessarily web servers) communicate with each other over an XML-based protocol built on top of PHP. The two most popular protocols are XML-RPC (the RPC stands for "Remote Procedure Calls") and SOAP (which used to stand for "Simple Object Access Protocol" but now is just a name). Often-changing information such as stock prices and weather are often offered through web services, but they can also be used as an object API between agents over the network. What's cool about using SOAP is you can publish to clients exactly what services you offer and how they can call them using the Web Services Description Language (WSDL).
Chapter 3: Alternative Content Types
If you've ever printed out a web page that was designed for browser viewing, you know the less-than-desired effect. The navigational elements, search boxes, and banners, while necessary for the web page, are useless once a static copy is printed. Furthermore, you need to extend your site to include users with less-featured browsers, such as mobile phones.Fortunately, PHP has been taught many languages. PDF is the standard for print-quality documents, and there are several libraries (free and non-free) which allow you to generate them. WML is the HTML of cell phone browsers, in which screen space is at a premium and bandwidth scarce. SVG is an XML application which allows vector-based images like PostScript does. The coolest example, however, uses XUL (the XML User interface Language, not to be confused with Zool) to make full GUI applications that you run through Mozilla. This isn't useful for the outside world where you can't force your users to use Mozilla (sigh), but works well for intranet applications that run on a variety of platforms.
The author also brings up in this chapter an HTML SAX parser he has written. You can process HTML pages chunk-by-chunk and extract the pieces you want. I hadn't known about such a class until I read the book and I'm very excited I know about it now. For sometimes it's necessary to parse a web page meant for humans to read (perhaps to pretend to be a user and automate your all-star voting), and most HTML pages won't validate as HTML, let alone XML.
A good point here is that a well-designed, tiered application will allow you to swap out different presentation classes with little code rewrite. Separating the tasks of extracting the data from the database and presenting to the user in variety of formats is a common task that when done right becomes subsequently easier.
Chapter 4: Stats and Tracking
Once your site is up and running, you'll be interested to know which parts are the most active, and how much traffic you're getting. Into a dynamic page you can obviously insert any logging mechanism, but a great place to put it is inside your site's logo. PHP can send binary data as easily as text. Why would you want to do this?- The logo is usually on every page (or it should be). You don't have to cut-and-paste code.
- You can serve the image, then use the flush command to send the output on and do extra processing. This way logging doesn't get in the way of page rendering.
There are lots of packages available to collect and analyze data. The author goes through phpOpenTracker which is quite rich in features. There are also ways to collect data on what links users follow to leave your site, and to keep requests from search engines from cluttering your log files.
Chapter 5: Caching
Another possible knock against PHP is that, while it's good to have dynamic pages, some pages are unnecessarily so. This is a waste of server resources to keep rendering the same page anew. There are different ways to conserve.On the client side, you can use HTTP 1.1 headers like Cache-control and Expires to tell browsers when it's okay to store cached copies locally
On the server side, as can be expected, you have a greater level of control. You can use output buffering to delay sending of output to the browser, then save a copy of the output locally. On subsequent requests, you can serve the file rather than generate the HTML all over again. This can be implemented on a chunk (or block) level, so that you can keep some parts ultra-time sensitive and others not so much. The package PEAR::Cache_Lite can help with this.
Chapter 6: Development Technique
The last two chapters were my favorites of the two-volume set. They are on a higher level of abstraction than the features of PHP's library of functions, or previous five chapters on real-world solutions. After you've reached a certain level of expertise in PHP coding, you being to wonder about the "right" way to do things. The author shows how to use Xdebug to find bottlenecks in your code, as well as a few quick optimization tips (for instance, design your flow control so that the first choice is the one most often taken).He then discusses the principles of N-tiered design. N is usually 5, but the data layer (usually a database or file system) and presentation layer (usually the browser) are most often handled outside of PHP, so you normally have three levels to worry about:
- Data Access: Getting data from the outside world into your application
- Application Logic: Doing whatever unique thing your application is supposed to do
- Presentation Logic: Forming a response in a format acceptable to your client
Keeping these layers separate and restricting them to communicating through well-defined interfaces allows you maximum flexibility. If you need to change databases (say you just got venture capital money and can afford Oracle now), you can do so only changing one layer. If you want to serve different flavors of HTML, or different markup languages altogether, or binary data, you can do so by only changing one layer. You can even strive for maximum distributability by enabling your layers to "live" on physically independent machines and communicate with XML-RPC or SOAP.
Documenting your code is essential. Anybody who's been programming for over a year has gone back to code he or she's written and thought, "Now what the heck was this supposed to do?" It's even more essential when you write something and wish to distribute it for the benefit of others. You can expect them to grok your code at an even lower rate since they didn't write it the first time.
Luckily, scripted languages like PHP are excellent at parsing text files, including PHP scripts themselves. Using well-defined documentation formats akin to JavaDoc, you can embed documentation in your code inside comments, and use tools like phpDocumentor to extract these documentation blocks and format them as nice, cross-reference HTML. In fact, writing doc blocks before your code is a good way to think ahead about how you want your classes and methods to work.
Unit Testing, one of the most digestible dogmas of Extreme Programming, is an awesome way to test your code for logic errors. You build up tiny test cases (using mock objects to isolate the class you're testing) and build as many as you like. Once you do this (PHPUnit and SimpleTest are two rich frameworks), you keep your tests and each time you add features, you run your test to make sure you haven't added bugs as well.
Chapter 7: Design Patterns
Design Patterns is one of the modern classics in information technology. After having done OOP for a while, you will inevitably get the feeling of deja vu that you've solved a problem before. Not so concretely as "I need a database abstraction layer," or "I need a templating system," but as in "I need a way to create objects without specifying exactly what class they belong to," or "I'm tired of writing so many if statements." Design patterns are common object architectures which can be used to solve common (though unique) problems.Many design patterns are more suited to state-equipped applications with GUIs, but there are plenty to assist the PHP coder. The Factory Method is a pattern through which an object can create other objects of varying classes. So instead of writing mysql_connect everywhere, then having to change every occurrence of that function, you can abstract all database interaction to a class, then instantiate a database connection through a class method of another class: $db = MyApp::getDatabaseConnection(). This is useful when the connection (not just the RDBMS, but the actual database) you want varies depending on whether you are developing, testing, or going live with your application. Factory methods are also a good way to avoid global configuration variables.
The Iterator Pattern and the Observer Pattern are two others mentioned in this chapter. Iterators are used often in paging through database results. Observers are used to let objects notify other objects of changes in their state. This chapter will make you want to go read the whole Gang-of-Four book if you haven't already.
My biggest beef with the book is that this wasn't presented earlier on, perhaps at the beginning of Volume II. As a climax, it leaves me flat, wondering how the rest of the volume could have been derived from this very cool concept. But most PHP books conclude with chapters on how to extended PHP on the C level, or giant case studies involving massive code dumps, and I'm often not satisfied with them. This is a nice philosophical note to go out on. And there's something to be said for the argument that books like these aren't written to be read cover-to-cover.
Appendices
The book closes with the same indices as in Volume I. Since I don't know the URL of my review of that volume, I'll just copy: You can read about which configuration directives you're probably most interested in (the complete list you can get on PHP's web site), some common security breaches, and how to install PEAR, PHP's version of CPAN. My favorite appendix is the "Hosting Provider Checklist," a great reference for evaluating whether kewlhosting.com is going to give you the freedom and support you need to make a great hosted web site.This volume was informative, well-written, and inspirational in that it made me want to go out and add cool and useful features to my web sites. Check it out if you can.
*Not really (not that I tried or anything), but they've always been a little bit smarter about it. You get my point, though. This did happen on an ESPN.com Page 2 mascot popularity contest, but they noticed through request headers that millions of votes were coming from the same place, and invalidated all those votes.
In real life, Matthew Leingang is Preceptor in Mathematics at Harvard University. He promises to review any book sent to him for free, and sometimes actually does it. Both volumes of The PHP Anthology are available from SitePoint. Slashdot welcomes readers' book reviews; to see your own review here, carefully read the book review guidelines, then visit the submission page.
-
The PHP Anthology - Volume II, 'Applications'
sympleko (Matthew Leingang) writes "In Volume I of The PHP Anthology, Harry Fuecks showed some of the basic PHP functionality to solve a few simple problems, including how to object-orient your code, how to use PHP's hundreds of built-in functions, and how to use well-developed existing classes, be they from PEAR or other sites. In Volume II, he intends to 'blow your socks off by tackling some traditionally complex problems with the same principles--to great effect.' It's summertime and I'm sandals-only for the time being, so my socks remain safely in the top drawer. But the volume is nonetheless exciting." (Read on for the rest of Leingang's review, and check out last week's review of Volume I.)There are seven chapters in this volume, each dealing with real-world problems. Many problems are those you've seen solved on sites you admire and wondered "How did they do that?" Others are frameworks that allow your site to run smoothly, with nobody getting accidentally logged out or having to wait too long while your script gluttonously pulls the same data out of the database for the Nth time. At the end, Fuecks goes back to the beginning, to show how proper design and development can save you time when you start your next project.
Chapter 1: Access Control
Authentication is the process by which users identify themselves. This is difficult in HTTP, a stateless protocol in which the server handles one request at a time and instantly forgets you. Luckily HTTP allows cookies, which are bits of data the server sends to the client for to reveal upon revisiting. At first cookies were used only to annoy ("Hello, Steve! You have visited this page 3 times"), but a cookie can hold the ID of a session record in a database, which contains any state-information that you like.You can authenticate without sessions via HTTP server configuration, as long as you like the dull dialog box the browser pops up when users enter a restricted area. Oh, and you don't mind the fact that users won't be able to "log out" without quitting their browser, nor can you force a logout after a certain timeout value. Nor can you allow users to register themselves... these are all existing, solved problems and the author shows some of the best solutions. Common tasks like allowing users to change their passwords, recover their passwords if (I mean when) they forget them, and arranging users in groups to which you assign common permissions are also covered.
My favorite example from this chapter is the humans-only registration application. Remember when online voting for the Major League Baseball All-Star Game first started? Anyone who knew how to write a web client could have automated a task to vote as many times as the server could handle, and have his favorite players be the all-star team.* To bring it closer to home, what if somebody decides to bog down your site by automatically registering a huge number of times and filling up your database? You can keep these things from happening by making users look at images which contain text but are hard for computers to "read." PHP is in use at all stages of this game, from writing the registration form's HTML to generating the obscured image on-the-fly.
Chapter 2: XML
XML is a fact of life and, hype aside, is a great way to store and transmit machine-readable data. One of the most visible applications is the thousands of bloggers and news sites providing XML feeds of their headlines. You can write portal sites that grab these headlines, parse them all and present them on your site with links to the full text at the source.There are two ways to parse XML: with events, or by using the Document Object Model (DOM). The methodologies are similar to reading a plain-text file line-by-line or all at once. Using events you can implement a finite-state machine based on which tags and text come down the pike. Or you can slurp the whole document into memory and find any part of it with ease. The built-in library for the former is based on the popular Simple API for XML (or SAX; don't you like those nested acronyms?), while the latter often uses Xpath to find the particular document nodes you want.
The author shows how to parse RSS feeds with both SAX and the DOM, and how to render a feed with DOM. Further, you can use Extensible Stylesheet Language Transformations (known as XSLT) to transform XML -- whether it's to XHTML for regular browser reading, WML (Wireless Markup Language) for viewing on mobile phones, or even SQL to communicate with a database.
Another exciting XML application is in the area of web services, in which agents (often but not necessarily web servers) communicate with each other over an XML-based protocol built on top of PHP. The two most popular protocols are XML-RPC (the RPC stands for "Remote Procedure Calls") and SOAP (which used to stand for "Simple Object Access Protocol" but now is just a name). Often-changing information such as stock prices and weather are often offered through web services, but they can also be used as an object API between agents over the network. What's cool about using SOAP is you can publish to clients exactly what services you offer and how they can call them using the Web Services Description Language (WSDL).
Chapter 3: Alternative Content Types
If you've ever printed out a web page that was designed for browser viewing, you know the less-than-desired effect. The navigational elements, search boxes, and banners, while necessary for the web page, are useless once a static copy is printed. Furthermore, you need to extend your site to include users with less-featured browsers, such as mobile phones.Fortunately, PHP has been taught many languages. PDF is the standard for print-quality documents, and there are several libraries (free and non-free) which allow you to generate them. WML is the HTML of cell phone browsers, in which screen space is at a premium and bandwidth scarce. SVG is an XML application which allows vector-based images like PostScript does. The coolest example, however, uses XUL (the XML User interface Language, not to be confused with Zool) to make full GUI applications that you run through Mozilla. This isn't useful for the outside world where you can't force your users to use Mozilla (sigh), but works well for intranet applications that run on a variety of platforms.
The author also brings up in this chapter an HTML SAX parser he has written. You can process HTML pages chunk-by-chunk and extract the pieces you want. I hadn't known about such a class until I read the book and I'm very excited I know about it now. For sometimes it's necessary to parse a web page meant for humans to read (perhaps to pretend to be a user and automate your all-star voting), and most HTML pages won't validate as HTML, let alone XML.
A good point here is that a well-designed, tiered application will allow you to swap out different presentation classes with little code rewrite. Separating the tasks of extracting the data from the database and presenting to the user in variety of formats is a common task that when done right becomes subsequently easier.
Chapter 4: Stats and Tracking
Once your site is up and running, you'll be interested to know which parts are the most active, and how much traffic you're getting. Into a dynamic page you can obviously insert any logging mechanism, but a great place to put it is inside your site's logo. PHP can send binary data as easily as text. Why would you want to do this?- The logo is usually on every page (or it should be). You don't have to cut-and-paste code.
- You can serve the image, then use the flush command to send the output on and do extra processing. This way logging doesn't get in the way of page rendering.
There are lots of packages available to collect and analyze data. The author goes through phpOpenTracker which is quite rich in features. There are also ways to collect data on what links users follow to leave your site, and to keep requests from search engines from cluttering your log files.
Chapter 5: Caching
Another possible knock against PHP is that, while it's good to have dynamic pages, some pages are unnecessarily so. This is a waste of server resources to keep rendering the same page anew. There are different ways to conserve.On the client side, you can use HTTP 1.1 headers like Cache-control and Expires to tell browsers when it's okay to store cached copies locally
On the server side, as can be expected, you have a greater level of control. You can use output buffering to delay sending of output to the browser, then save a copy of the output locally. On subsequent requests, you can serve the file rather than generate the HTML all over again. This can be implemented on a chunk (or block) level, so that you can keep some parts ultra-time sensitive and others not so much. The package PEAR::Cache_Lite can help with this.
Chapter 6: Development Technique
The last two chapters were my favorites of the two-volume set. They are on a higher level of abstraction than the features of PHP's library of functions, or previous five chapters on real-world solutions. After you've reached a certain level of expertise in PHP coding, you being to wonder about the "right" way to do things. The author shows how to use Xdebug to find bottlenecks in your code, as well as a few quick optimization tips (for instance, design your flow control so that the first choice is the one most often taken).He then discusses the principles of N-tiered design. N is usually 5, but the data layer (usually a database or file system) and presentation layer (usually the browser) are most often handled outside of PHP, so you normally have three levels to worry about:
- Data Access: Getting data from the outside world into your application
- Application Logic: Doing whatever unique thing your application is supposed to do
- Presentation Logic: Forming a response in a format acceptable to your client
Keeping these layers separate and restricting them to communicating through well-defined interfaces allows you maximum flexibility. If you need to change databases (say you just got venture capital money and can afford Oracle now), you can do so only changing one layer. If you want to serve different flavors of HTML, or different markup languages altogether, or binary data, you can do so by only changing one layer. You can even strive for maximum distributability by enabling your layers to "live" on physically independent machines and communicate with XML-RPC or SOAP.
Documenting your code is essential. Anybody who's been programming for over a year has gone back to code he or she's written and thought, "Now what the heck was this supposed to do?" It's even more essential when you write something and wish to distribute it for the benefit of others. You can expect them to grok your code at an even lower rate since they didn't write it the first time.
Luckily, scripted languages like PHP are excellent at parsing text files, including PHP scripts themselves. Using well-defined documentation formats akin to JavaDoc, you can embed documentation in your code inside comments, and use tools like phpDocumentor to extract these documentation blocks and format them as nice, cross-reference HTML. In fact, writing doc blocks before your code is a good way to think ahead about how you want your classes and methods to work.
Unit Testing, one of the most digestible dogmas of Extreme Programming, is an awesome way to test your code for logic errors. You build up tiny test cases (using mock objects to isolate the class you're testing) and build as many as you like. Once you do this (PHPUnit and SimpleTest are two rich frameworks), you keep your tests and each time you add features, you run your test to make sure you haven't added bugs as well.
Chapter 7: Design Patterns
Design Patterns is one of the modern classics in information technology. After having done OOP for a while, you will inevitably get the feeling of deja vu that you've solved a problem before. Not so concretely as "I need a database abstraction layer," or "I need a templating system," but as in "I need a way to create objects without specifying exactly what class they belong to," or "I'm tired of writing so many if statements." Design patterns are common object architectures which can be used to solve common (though unique) problems.Many design patterns are more suited to state-equipped applications with GUIs, but there are plenty to assist the PHP coder. The Factory Method is a pattern through which an object can create other objects of varying classes. So instead of writing mysql_connect everywhere, then having to change every occurrence of that function, you can abstract all database interaction to a class, then instantiate a database connection through a class method of another class: $db = MyApp::getDatabaseConnection(). This is useful when the connection (not just the RDBMS, but the actual database) you want varies depending on whether you are developing, testing, or going live with your application. Factory methods are also a good way to avoid global configuration variables.
The Iterator Pattern and the Observer Pattern are two others mentioned in this chapter. Iterators are used often in paging through database results. Observers are used to let objects notify other objects of changes in their state. This chapter will make you want to go read the whole Gang-of-Four book if you haven't already.
My biggest beef with the book is that this wasn't presented earlier on, perhaps at the beginning of Volume II. As a climax, it leaves me flat, wondering how the rest of the volume could have been derived from this very cool concept. But most PHP books conclude with chapters on how to extended PHP on the C level, or giant case studies involving massive code dumps, and I'm often not satisfied with them. This is a nice philosophical note to go out on. And there's something to be said for the argument that books like these aren't written to be read cover-to-cover.
Appendices
The book closes with the same indices as in Volume I. Since I don't know the URL of my review of that volume, I'll just copy: You can read about which configuration directives you're probably most interested in (the complete list you can get on PHP's web site), some common security breaches, and how to install PEAR, PHP's version of CPAN. My favorite appendix is the "Hosting Provider Checklist," a great reference for evaluating whether kewlhosting.com is going to give you the freedom and support you need to make a great hosted web site.This volume was informative, well-written, and inspirational in that it made me want to go out and add cool and useful features to my web sites. Check it out if you can.
*Not really (not that I tried or anything), but they've always been a little bit smarter about it. You get my point, though. This did happen on an ESPN.com Page 2 mascot popularity contest, but they noticed through request headers that millions of votes were coming from the same place, and invalidated all those votes.
In real life, Matthew Leingang is Preceptor in Mathematics at Harvard University. He promises to review any book sent to him for free, and sometimes actually does it. Both volumes of The PHP Anthology are available from SitePoint. Slashdot welcomes readers' book reviews; to see your own review here, carefully read the book review guidelines, then visit the submission page.
-
PHP5: Could PHP Soon Be Owned by Sun?
Ian Felton writes "PHP 5's official release occurred on July 13th, with a complete overhaul of object-oriented programming features and improved MySQL functions. These are sure to be great additions to the package for PHP developers. However, many of the changes to PHP are hinting at something that PHP developers might not necessarily like down the road." Read on for the rest of Felton's thoughts on the downside to corporate involvment in PHP's future.At first glance, the obvious changes to PHP are a result of the success of the Java platform and the weaknesses of PHP revealed in comparison. With the release of PHP 5, it's apparent that the developers of PHP and the Zend Engine (essentially a single group) felt compelled to make PHP much more like Java with respect to object-oriented programming. Zend, the Israeli company backing the development of PHP, promises on their web site that "full integration with Java will be closer than ever before." Hmmm, full integration with Java, huh?
On November 4th, 2003, Zend announced a strategic partnership with Sun. This deal also included advisors from Borland, Macromedia, MySQL and others. The purported purpose of this deal was to make PHP part of Sun's web server and bring it to the corporate world of development that previously had been dominated by ASP and ColdFusion. Now with the release of PHP 5, it's far more apparent which path PHP is taking.
PHP's object model was re-written from the ground up and mimics the abstract properties of Java's object method. There are private and protected members and methods, abstract classes and interfaces, in practice, identical to Java's object model. The extent of the influence that Sun has on PHP today is clear. If you have experience with Java and PHP, reading the details of the object model reveals the absolute cloning of the Java object model within PHP 5. From throwing exceptions to static variables, PHP 5's object model mimics Java in concept all the way to the syntactical level.
This is great for enterprise developers using Sun products, but with the release of PHP 5, what does this mean for the half-million PHP developers worldwide who have depended on PHP for open-source development, or for the developers whose ideas and efforts have brought PHP up through the ranks from its inception in 1995? When PHP goodies were bundled with Sun's web server on November 4th, 2003, with a $775 price tag, PHP began down the path of corporate ownership. For years developers have eagerly contributed their ideas and efforts to be a part of the success of PHP. Now that all the hard work and volunteering has paid off and PHP is a worldwide success, it appears that PHP could soon be another corporate shill owned by Sun, MySQL, Borland and Macromedia, if not on paper, then by direct influence on the people at Zend. Of course it will remain open source so that those half-million developers can continue to contribute their time and genius to its success, but if those thousands of contributions lead to direct financial gain for companies whose coffers are already overflowing and are simultaneously using those contributions to manufacture software with price tags out of reach to anyone but corporations, is PHP still the language developers should be focusing on for use in the open-source community?
On the positive side, this edition of PHP does bring improved performance and a new suite of MySQL functions. Backward incompatibility is limited to a list of ten issues. Additionally, there are only minor configuration file changes that need to be made to the web server. Several directives have been introduced for configuring php.ini files, mainly dealing with hashes for encryption.
Some very useful functions have been added to PHP5. It's been nine years in the making, but PHP5 now includes two functions to uuencode and uudecode. Combining those functions with the new socket and stream functions, developers can create a lots of "kewl" applications. An application to automatically encode and decode files to and from news servers comes to mind as an example of how to incorporate these new functions. At that point of course, a developer could use any of PHP's existing functions to continue to manipulate the files, store the contents in databases, and so on.
An addition to error reporting aids developers in keeping their code up-to-date. The E_STRICT message tells developers when their code is using deprecated functions or is in danger of not being forward compatible. However, don't assume that E_STRICT will be output if using E_ALL, because it won't. E_STRICT must be explicitly declared to output its suggestions to PHP 5 code.
While the rewriting of PHP's object model to essentially that of the Java object model does raise flags about the direction of PHP, it is still a powerful addition to the PHP5 release. Java became successful for a reason: it's intelligently designed and facilitates code reuse. By borrowing the best features of Java's object model, PHP has leveraged itself with far more credibility as a programming language that can stand on its own two feet (even if Sun, Borland and Macromedia are holding it by its arms).
Some vital re-workings in the PHP object model lie in how objects are treated in low-level fashion. Instead of passing the actual object itself, PHP's object model passes by reference. Now when operating on objects, developers can pass around multiple handles to the actual object allowing for more powerful and efficient applications. Existing PHP objects do not need to be re-written to take advantage of this change in PHP 5.
In general, developers who have experience with Java will easily adapt to PHP 5's object model. On the downside, if PHP is a developer's primary language and he or she hasn't been introduced to the world of static variables, public and private methods and the host of aspects included with this new model, they may have a bit of a learning curve adopting the higher-level format of object-oriented programming in this release. Overall, though, this change will be a plus for creating large-scale, object-oriented applications with PHP.
Keeping pace with the developments in MySQL and PHP's tight relationship, PHP5 has added a new suite of MySQL functions relating to the new features added since MySQL 4.1. Denoted as Improved MySQL Extension, its purpose is to allow developers to take advantage of prepared statements and the other additions to MySQL 4.1 and above.
Something very interesting to note with the addition on the Improved MySQL Extension is the absence of bundled MySQL client libraries with PHP5. There are numerous reasons given for this, including the different licenses that PHP and MySQL are under (PHP is under a BSD/Apache type license and MySQL is under a GPL license). The PHP5 documentation also assures developers that "there will always be MySQL support in PHP of one kind or another," but doesn't go into details as to the future of MySQL support. This perhaps is further evidence that the long-lasting popularity of LAMP environments (Linux, Apache, MySQL, PHP) will soon be replaced by SLOP environments (Sun, Linux, Oracle, PHP). If Zend continues to shy away from MySQL and completely joins forces with Sun, MySQL may soon no longer be part of the picture, and cheap, fast development may no longer be possible for PHP developers in the same capacity as it is today.
Zend clearly has underplayed the extent of the shift that has taken place concerning the future of PHP. While this version of PHP does provide a much better object model and added features, is this the beginning of the end of PHP as the choice of web scripting language for the open-source community and developers not under the employ of corporations? Will the average developer still be using PHP five years from now, or will the usefulness of PHP be limited to companies who can afford to shell out thousands of dollars for all of the necessary software that may be required to make PHP a viable option for development (along with the purchase of products from Sun, Macromedia, Oracle, Borland and others)?
While today this is still speculation, the evidence and tone lends credence to the thought that with the success of PHP, built on the backs of developers worldwide, the near future of it may include an alienation of it from those who energized it at its genesis, propelling it to the corporate enterprise status that those in control of PHP are seeking today. No matter what actually happens, developers should be aware of the major developments with PHP beyond the surface level function additions and new object model. Companies and developers who are employing PHP 5 for large-scale applications today at a reasonably low price may be in for a surprise in the next few years, if operating PHP at full capacity involves the purchase of additional, expensive software.
-
PHP5: Could PHP Soon Be Owned by Sun?
Ian Felton writes "PHP 5's official release occurred on July 13th, with a complete overhaul of object-oriented programming features and improved MySQL functions. These are sure to be great additions to the package for PHP developers. However, many of the changes to PHP are hinting at something that PHP developers might not necessarily like down the road." Read on for the rest of Felton's thoughts on the downside to corporate involvment in PHP's future.At first glance, the obvious changes to PHP are a result of the success of the Java platform and the weaknesses of PHP revealed in comparison. With the release of PHP 5, it's apparent that the developers of PHP and the Zend Engine (essentially a single group) felt compelled to make PHP much more like Java with respect to object-oriented programming. Zend, the Israeli company backing the development of PHP, promises on their web site that "full integration with Java will be closer than ever before." Hmmm, full integration with Java, huh?
On November 4th, 2003, Zend announced a strategic partnership with Sun. This deal also included advisors from Borland, Macromedia, MySQL and others. The purported purpose of this deal was to make PHP part of Sun's web server and bring it to the corporate world of development that previously had been dominated by ASP and ColdFusion. Now with the release of PHP 5, it's far more apparent which path PHP is taking.
PHP's object model was re-written from the ground up and mimics the abstract properties of Java's object method. There are private and protected members and methods, abstract classes and interfaces, in practice, identical to Java's object model. The extent of the influence that Sun has on PHP today is clear. If you have experience with Java and PHP, reading the details of the object model reveals the absolute cloning of the Java object model within PHP 5. From throwing exceptions to static variables, PHP 5's object model mimics Java in concept all the way to the syntactical level.
This is great for enterprise developers using Sun products, but with the release of PHP 5, what does this mean for the half-million PHP developers worldwide who have depended on PHP for open-source development, or for the developers whose ideas and efforts have brought PHP up through the ranks from its inception in 1995? When PHP goodies were bundled with Sun's web server on November 4th, 2003, with a $775 price tag, PHP began down the path of corporate ownership. For years developers have eagerly contributed their ideas and efforts to be a part of the success of PHP. Now that all the hard work and volunteering has paid off and PHP is a worldwide success, it appears that PHP could soon be another corporate shill owned by Sun, MySQL, Borland and Macromedia, if not on paper, then by direct influence on the people at Zend. Of course it will remain open source so that those half-million developers can continue to contribute their time and genius to its success, but if those thousands of contributions lead to direct financial gain for companies whose coffers are already overflowing and are simultaneously using those contributions to manufacture software with price tags out of reach to anyone but corporations, is PHP still the language developers should be focusing on for use in the open-source community?
On the positive side, this edition of PHP does bring improved performance and a new suite of MySQL functions. Backward incompatibility is limited to a list of ten issues. Additionally, there are only minor configuration file changes that need to be made to the web server. Several directives have been introduced for configuring php.ini files, mainly dealing with hashes for encryption.
Some very useful functions have been added to PHP5. It's been nine years in the making, but PHP5 now includes two functions to uuencode and uudecode. Combining those functions with the new socket and stream functions, developers can create a lots of "kewl" applications. An application to automatically encode and decode files to and from news servers comes to mind as an example of how to incorporate these new functions. At that point of course, a developer could use any of PHP's existing functions to continue to manipulate the files, store the contents in databases, and so on.
An addition to error reporting aids developers in keeping their code up-to-date. The E_STRICT message tells developers when their code is using deprecated functions or is in danger of not being forward compatible. However, don't assume that E_STRICT will be output if using E_ALL, because it won't. E_STRICT must be explicitly declared to output its suggestions to PHP 5 code.
While the rewriting of PHP's object model to essentially that of the Java object model does raise flags about the direction of PHP, it is still a powerful addition to the PHP5 release. Java became successful for a reason: it's intelligently designed and facilitates code reuse. By borrowing the best features of Java's object model, PHP has leveraged itself with far more credibility as a programming language that can stand on its own two feet (even if Sun, Borland and Macromedia are holding it by its arms).
Some vital re-workings in the PHP object model lie in how objects are treated in low-level fashion. Instead of passing the actual object itself, PHP's object model passes by reference. Now when operating on objects, developers can pass around multiple handles to the actual object allowing for more powerful and efficient applications. Existing PHP objects do not need to be re-written to take advantage of this change in PHP 5.
In general, developers who have experience with Java will easily adapt to PHP 5's object model. On the downside, if PHP is a developer's primary language and he or she hasn't been introduced to the world of static variables, public and private methods and the host of aspects included with this new model, they may have a bit of a learning curve adopting the higher-level format of object-oriented programming in this release. Overall, though, this change will be a plus for creating large-scale, object-oriented applications with PHP.
Keeping pace with the developments in MySQL and PHP's tight relationship, PHP5 has added a new suite of MySQL functions relating to the new features added since MySQL 4.1. Denoted as Improved MySQL Extension, its purpose is to allow developers to take advantage of prepared statements and the other additions to MySQL 4.1 and above.
Something very interesting to note with the addition on the Improved MySQL Extension is the absence of bundled MySQL client libraries with PHP5. There are numerous reasons given for this, including the different licenses that PHP and MySQL are under (PHP is under a BSD/Apache type license and MySQL is under a GPL license). The PHP5 documentation also assures developers that "there will always be MySQL support in PHP of one kind or another," but doesn't go into details as to the future of MySQL support. This perhaps is further evidence that the long-lasting popularity of LAMP environments (Linux, Apache, MySQL, PHP) will soon be replaced by SLOP environments (Sun, Linux, Oracle, PHP). If Zend continues to shy away from MySQL and completely joins forces with Sun, MySQL may soon no longer be part of the picture, and cheap, fast development may no longer be possible for PHP developers in the same capacity as it is today.
Zend clearly has underplayed the extent of the shift that has taken place concerning the future of PHP. While this version of PHP does provide a much better object model and added features, is this the beginning of the end of PHP as the choice of web scripting language for the open-source community and developers not under the employ of corporations? Will the average developer still be using PHP five years from now, or will the usefulness of PHP be limited to companies who can afford to shell out thousands of dollars for all of the necessary software that may be required to make PHP a viable option for development (along with the purchase of products from Sun, Macromedia, Oracle, Borland and others)?
While today this is still speculation, the evidence and tone lends credence to the thought that with the success of PHP, built on the backs of developers worldwide, the near future of it may include an alienation of it from those who energized it at its genesis, propelling it to the corporate enterprise status that those in control of PHP are seeking today. No matter what actually happens, developers should be aware of the major developments with PHP beyond the surface level function additions and new object model. Companies and developers who are employing PHP 5 for large-scale applications today at a reasonably low price may be in for a surprise in the next few years, if operating PHP at full capacity involves the purchase of additional, expensive software.
-
PHP5: Could PHP Soon Be Owned by Sun?
Ian Felton writes "PHP 5's official release occurred on July 13th, with a complete overhaul of object-oriented programming features and improved MySQL functions. These are sure to be great additions to the package for PHP developers. However, many of the changes to PHP are hinting at something that PHP developers might not necessarily like down the road." Read on for the rest of Felton's thoughts on the downside to corporate involvment in PHP's future.At first glance, the obvious changes to PHP are a result of the success of the Java platform and the weaknesses of PHP revealed in comparison. With the release of PHP 5, it's apparent that the developers of PHP and the Zend Engine (essentially a single group) felt compelled to make PHP much more like Java with respect to object-oriented programming. Zend, the Israeli company backing the development of PHP, promises on their web site that "full integration with Java will be closer than ever before." Hmmm, full integration with Java, huh?
On November 4th, 2003, Zend announced a strategic partnership with Sun. This deal also included advisors from Borland, Macromedia, MySQL and others. The purported purpose of this deal was to make PHP part of Sun's web server and bring it to the corporate world of development that previously had been dominated by ASP and ColdFusion. Now with the release of PHP 5, it's far more apparent which path PHP is taking.
PHP's object model was re-written from the ground up and mimics the abstract properties of Java's object method. There are private and protected members and methods, abstract classes and interfaces, in practice, identical to Java's object model. The extent of the influence that Sun has on PHP today is clear. If you have experience with Java and PHP, reading the details of the object model reveals the absolute cloning of the Java object model within PHP 5. From throwing exceptions to static variables, PHP 5's object model mimics Java in concept all the way to the syntactical level.
This is great for enterprise developers using Sun products, but with the release of PHP 5, what does this mean for the half-million PHP developers worldwide who have depended on PHP for open-source development, or for the developers whose ideas and efforts have brought PHP up through the ranks from its inception in 1995? When PHP goodies were bundled with Sun's web server on November 4th, 2003, with a $775 price tag, PHP began down the path of corporate ownership. For years developers have eagerly contributed their ideas and efforts to be a part of the success of PHP. Now that all the hard work and volunteering has paid off and PHP is a worldwide success, it appears that PHP could soon be another corporate shill owned by Sun, MySQL, Borland and Macromedia, if not on paper, then by direct influence on the people at Zend. Of course it will remain open source so that those half-million developers can continue to contribute their time and genius to its success, but if those thousands of contributions lead to direct financial gain for companies whose coffers are already overflowing and are simultaneously using those contributions to manufacture software with price tags out of reach to anyone but corporations, is PHP still the language developers should be focusing on for use in the open-source community?
On the positive side, this edition of PHP does bring improved performance and a new suite of MySQL functions. Backward incompatibility is limited to a list of ten issues. Additionally, there are only minor configuration file changes that need to be made to the web server. Several directives have been introduced for configuring php.ini files, mainly dealing with hashes for encryption.
Some very useful functions have been added to PHP5. It's been nine years in the making, but PHP5 now includes two functions to uuencode and uudecode. Combining those functions with the new socket and stream functions, developers can create a lots of "kewl" applications. An application to automatically encode and decode files to and from news servers comes to mind as an example of how to incorporate these new functions. At that point of course, a developer could use any of PHP's existing functions to continue to manipulate the files, store the contents in databases, and so on.
An addition to error reporting aids developers in keeping their code up-to-date. The E_STRICT message tells developers when their code is using deprecated functions or is in danger of not being forward compatible. However, don't assume that E_STRICT will be output if using E_ALL, because it won't. E_STRICT must be explicitly declared to output its suggestions to PHP 5 code.
While the rewriting of PHP's object model to essentially that of the Java object model does raise flags about the direction of PHP, it is still a powerful addition to the PHP5 release. Java became successful for a reason: it's intelligently designed and facilitates code reuse. By borrowing the best features of Java's object model, PHP has leveraged itself with far more credibility as a programming language that can stand on its own two feet (even if Sun, Borland and Macromedia are holding it by its arms).
Some vital re-workings in the PHP object model lie in how objects are treated in low-level fashion. Instead of passing the actual object itself, PHP's object model passes by reference. Now when operating on objects, developers can pass around multiple handles to the actual object allowing for more powerful and efficient applications. Existing PHP objects do not need to be re-written to take advantage of this change in PHP 5.
In general, developers who have experience with Java will easily adapt to PHP 5's object model. On the downside, if PHP is a developer's primary language and he or she hasn't been introduced to the world of static variables, public and private methods and the host of aspects included with this new model, they may have a bit of a learning curve adopting the higher-level format of object-oriented programming in this release. Overall, though, this change will be a plus for creating large-scale, object-oriented applications with PHP.
Keeping pace with the developments in MySQL and PHP's tight relationship, PHP5 has added a new suite of MySQL functions relating to the new features added since MySQL 4.1. Denoted as Improved MySQL Extension, its purpose is to allow developers to take advantage of prepared statements and the other additions to MySQL 4.1 and above.
Something very interesting to note with the addition on the Improved MySQL Extension is the absence of bundled MySQL client libraries with PHP5. There are numerous reasons given for this, including the different licenses that PHP and MySQL are under (PHP is under a BSD/Apache type license and MySQL is under a GPL license). The PHP5 documentation also assures developers that "there will always be MySQL support in PHP of one kind or another," but doesn't go into details as to the future of MySQL support. This perhaps is further evidence that the long-lasting popularity of LAMP environments (Linux, Apache, MySQL, PHP) will soon be replaced by SLOP environments (Sun, Linux, Oracle, PHP). If Zend continues to shy away from MySQL and completely joins forces with Sun, MySQL may soon no longer be part of the picture, and cheap, fast development may no longer be possible for PHP developers in the same capacity as it is today.
Zend clearly has underplayed the extent of the shift that has taken place concerning the future of PHP. While this version of PHP does provide a much better object model and added features, is this the beginning of the end of PHP as the choice of web scripting language for the open-source community and developers not under the employ of corporations? Will the average developer still be using PHP five years from now, or will the usefulness of PHP be limited to companies who can afford to shell out thousands of dollars for all of the necessary software that may be required to make PHP a viable option for development (along with the purchase of products from Sun, Macromedia, Oracle, Borland and others)?
While today this is still speculation, the evidence and tone lends credence to the thought that with the success of PHP, built on the backs of developers worldwide, the near future of it may include an alienation of it from those who energized it at its genesis, propelling it to the corporate enterprise status that those in control of PHP are seeking today. No matter what actually happens, developers should be aware of the major developments with PHP beyond the surface level function additions and new object model. Companies and developers who are employing PHP 5 for large-scale applications today at a reasonably low price may be in for a surprise in the next few years, if operating PHP at full capacity involves the purchase of additional, expensive software.
-
PHP5: Could PHP Soon Be Owned by Sun?
Ian Felton writes "PHP 5's official release occurred on July 13th, with a complete overhaul of object-oriented programming features and improved MySQL functions. These are sure to be great additions to the package for PHP developers. However, many of the changes to PHP are hinting at something that PHP developers might not necessarily like down the road." Read on for the rest of Felton's thoughts on the downside to corporate involvment in PHP's future.At first glance, the obvious changes to PHP are a result of the success of the Java platform and the weaknesses of PHP revealed in comparison. With the release of PHP 5, it's apparent that the developers of PHP and the Zend Engine (essentially a single group) felt compelled to make PHP much more like Java with respect to object-oriented programming. Zend, the Israeli company backing the development of PHP, promises on their web site that "full integration with Java will be closer than ever before." Hmmm, full integration with Java, huh?
On November 4th, 2003, Zend announced a strategic partnership with Sun. This deal also included advisors from Borland, Macromedia, MySQL and others. The purported purpose of this deal was to make PHP part of Sun's web server and bring it to the corporate world of development that previously had been dominated by ASP and ColdFusion. Now with the release of PHP 5, it's far more apparent which path PHP is taking.
PHP's object model was re-written from the ground up and mimics the abstract properties of Java's object method. There are private and protected members and methods, abstract classes and interfaces, in practice, identical to Java's object model. The extent of the influence that Sun has on PHP today is clear. If you have experience with Java and PHP, reading the details of the object model reveals the absolute cloning of the Java object model within PHP 5. From throwing exceptions to static variables, PHP 5's object model mimics Java in concept all the way to the syntactical level.
This is great for enterprise developers using Sun products, but with the release of PHP 5, what does this mean for the half-million PHP developers worldwide who have depended on PHP for open-source development, or for the developers whose ideas and efforts have brought PHP up through the ranks from its inception in 1995? When PHP goodies were bundled with Sun's web server on November 4th, 2003, with a $775 price tag, PHP began down the path of corporate ownership. For years developers have eagerly contributed their ideas and efforts to be a part of the success of PHP. Now that all the hard work and volunteering has paid off and PHP is a worldwide success, it appears that PHP could soon be another corporate shill owned by Sun, MySQL, Borland and Macromedia, if not on paper, then by direct influence on the people at Zend. Of course it will remain open source so that those half-million developers can continue to contribute their time and genius to its success, but if those thousands of contributions lead to direct financial gain for companies whose coffers are already overflowing and are simultaneously using those contributions to manufacture software with price tags out of reach to anyone but corporations, is PHP still the language developers should be focusing on for use in the open-source community?
On the positive side, this edition of PHP does bring improved performance and a new suite of MySQL functions. Backward incompatibility is limited to a list of ten issues. Additionally, there are only minor configuration file changes that need to be made to the web server. Several directives have been introduced for configuring php.ini files, mainly dealing with hashes for encryption.
Some very useful functions have been added to PHP5. It's been nine years in the making, but PHP5 now includes two functions to uuencode and uudecode. Combining those functions with the new socket and stream functions, developers can create a lots of "kewl" applications. An application to automatically encode and decode files to and from news servers comes to mind as an example of how to incorporate these new functions. At that point of course, a developer could use any of PHP's existing functions to continue to manipulate the files, store the contents in databases, and so on.
An addition to error reporting aids developers in keeping their code up-to-date. The E_STRICT message tells developers when their code is using deprecated functions or is in danger of not being forward compatible. However, don't assume that E_STRICT will be output if using E_ALL, because it won't. E_STRICT must be explicitly declared to output its suggestions to PHP 5 code.
While the rewriting of PHP's object model to essentially that of the Java object model does raise flags about the direction of PHP, it is still a powerful addition to the PHP5 release. Java became successful for a reason: it's intelligently designed and facilitates code reuse. By borrowing the best features of Java's object model, PHP has leveraged itself with far more credibility as a programming language that can stand on its own two feet (even if Sun, Borland and Macromedia are holding it by its arms).
Some vital re-workings in the PHP object model lie in how objects are treated in low-level fashion. Instead of passing the actual object itself, PHP's object model passes by reference. Now when operating on objects, developers can pass around multiple handles to the actual object allowing for more powerful and efficient applications. Existing PHP objects do not need to be re-written to take advantage of this change in PHP 5.
In general, developers who have experience with Java will easily adapt to PHP 5's object model. On the downside, if PHP is a developer's primary language and he or she hasn't been introduced to the world of static variables, public and private methods and the host of aspects included with this new model, they may have a bit of a learning curve adopting the higher-level format of object-oriented programming in this release. Overall, though, this change will be a plus for creating large-scale, object-oriented applications with PHP.
Keeping pace with the developments in MySQL and PHP's tight relationship, PHP5 has added a new suite of MySQL functions relating to the new features added since MySQL 4.1. Denoted as Improved MySQL Extension, its purpose is to allow developers to take advantage of prepared statements and the other additions to MySQL 4.1 and above.
Something very interesting to note with the addition on the Improved MySQL Extension is the absence of bundled MySQL client libraries with PHP5. There are numerous reasons given for this, including the different licenses that PHP and MySQL are under (PHP is under a BSD/Apache type license and MySQL is under a GPL license). The PHP5 documentation also assures developers that "there will always be MySQL support in PHP of one kind or another," but doesn't go into details as to the future of MySQL support. This perhaps is further evidence that the long-lasting popularity of LAMP environments (Linux, Apache, MySQL, PHP) will soon be replaced by SLOP environments (Sun, Linux, Oracle, PHP). If Zend continues to shy away from MySQL and completely joins forces with Sun, MySQL may soon no longer be part of the picture, and cheap, fast development may no longer be possible for PHP developers in the same capacity as it is today.
Zend clearly has underplayed the extent of the shift that has taken place concerning the future of PHP. While this version of PHP does provide a much better object model and added features, is this the beginning of the end of PHP as the choice of web scripting language for the open-source community and developers not under the employ of corporations? Will the average developer still be using PHP five years from now, or will the usefulness of PHP be limited to companies who can afford to shell out thousands of dollars for all of the necessary software that may be required to make PHP a viable option for development (along with the purchase of products from Sun, Macromedia, Oracle, Borland and others)?
While today this is still speculation, the evidence and tone lends credence to the thought that with the success of PHP, built on the backs of developers worldwide, the near future of it may include an alienation of it from those who energized it at its genesis, propelling it to the corporate enterprise status that those in control of PHP are seeking today. No matter what actually happens, developers should be aware of the major developments with PHP beyond the surface level function additions and new object model. Companies and developers who are employing PHP 5 for large-scale applications today at a reasonably low price may be in for a surprise in the next few years, if operating PHP at full capacity involves the purchase of additional, expensive software.
-
PHP5: Could PHP Soon Be Owned by Sun?
Ian Felton writes "PHP 5's official release occurred on July 13th, with a complete overhaul of object-oriented programming features and improved MySQL functions. These are sure to be great additions to the package for PHP developers. However, many of the changes to PHP are hinting at something that PHP developers might not necessarily like down the road." Read on for the rest of Felton's thoughts on the downside to corporate involvment in PHP's future.At first glance, the obvious changes to PHP are a result of the success of the Java platform and the weaknesses of PHP revealed in comparison. With the release of PHP 5, it's apparent that the developers of PHP and the Zend Engine (essentially a single group) felt compelled to make PHP much more like Java with respect to object-oriented programming. Zend, the Israeli company backing the development of PHP, promises on their web site that "full integration with Java will be closer than ever before." Hmmm, full integration with Java, huh?
On November 4th, 2003, Zend announced a strategic partnership with Sun. This deal also included advisors from Borland, Macromedia, MySQL and others. The purported purpose of this deal was to make PHP part of Sun's web server and bring it to the corporate world of development that previously had been dominated by ASP and ColdFusion. Now with the release of PHP 5, it's far more apparent which path PHP is taking.
PHP's object model was re-written from the ground up and mimics the abstract properties of Java's object method. There are private and protected members and methods, abstract classes and interfaces, in practice, identical to Java's object model. The extent of the influence that Sun has on PHP today is clear. If you have experience with Java and PHP, reading the details of the object model reveals the absolute cloning of the Java object model within PHP 5. From throwing exceptions to static variables, PHP 5's object model mimics Java in concept all the way to the syntactical level.
This is great for enterprise developers using Sun products, but with the release of PHP 5, what does this mean for the half-million PHP developers worldwide who have depended on PHP for open-source development, or for the developers whose ideas and efforts have brought PHP up through the ranks from its inception in 1995? When PHP goodies were bundled with Sun's web server on November 4th, 2003, with a $775 price tag, PHP began down the path of corporate ownership. For years developers have eagerly contributed their ideas and efforts to be a part of the success of PHP. Now that all the hard work and volunteering has paid off and PHP is a worldwide success, it appears that PHP could soon be another corporate shill owned by Sun, MySQL, Borland and Macromedia, if not on paper, then by direct influence on the people at Zend. Of course it will remain open source so that those half-million developers can continue to contribute their time and genius to its success, but if those thousands of contributions lead to direct financial gain for companies whose coffers are already overflowing and are simultaneously using those contributions to manufacture software with price tags out of reach to anyone but corporations, is PHP still the language developers should be focusing on for use in the open-source community?
On the positive side, this edition of PHP does bring improved performance and a new suite of MySQL functions. Backward incompatibility is limited to a list of ten issues. Additionally, there are only minor configuration file changes that need to be made to the web server. Several directives have been introduced for configuring php.ini files, mainly dealing with hashes for encryption.
Some very useful functions have been added to PHP5. It's been nine years in the making, but PHP5 now includes two functions to uuencode and uudecode. Combining those functions with the new socket and stream functions, developers can create a lots of "kewl" applications. An application to automatically encode and decode files to and from news servers comes to mind as an example of how to incorporate these new functions. At that point of course, a developer could use any of PHP's existing functions to continue to manipulate the files, store the contents in databases, and so on.
An addition to error reporting aids developers in keeping their code up-to-date. The E_STRICT message tells developers when their code is using deprecated functions or is in danger of not being forward compatible. However, don't assume that E_STRICT will be output if using E_ALL, because it won't. E_STRICT must be explicitly declared to output its suggestions to PHP 5 code.
While the rewriting of PHP's object model to essentially that of the Java object model does raise flags about the direction of PHP, it is still a powerful addition to the PHP5 release. Java became successful for a reason: it's intelligently designed and facilitates code reuse. By borrowing the best features of Java's object model, PHP has leveraged itself with far more credibility as a programming language that can stand on its own two feet (even if Sun, Borland and Macromedia are holding it by its arms).
Some vital re-workings in the PHP object model lie in how objects are treated in low-level fashion. Instead of passing the actual object itself, PHP's object model passes by reference. Now when operating on objects, developers can pass around multiple handles to the actual object allowing for more powerful and efficient applications. Existing PHP objects do not need to be re-written to take advantage of this change in PHP 5.
In general, developers who have experience with Java will easily adapt to PHP 5's object model. On the downside, if PHP is a developer's primary language and he or she hasn't been introduced to the world of static variables, public and private methods and the host of aspects included with this new model, they may have a bit of a learning curve adopting the higher-level format of object-oriented programming in this release. Overall, though, this change will be a plus for creating large-scale, object-oriented applications with PHP.
Keeping pace with the developments in MySQL and PHP's tight relationship, PHP5 has added a new suite of MySQL functions relating to the new features added since MySQL 4.1. Denoted as Improved MySQL Extension, its purpose is to allow developers to take advantage of prepared statements and the other additions to MySQL 4.1 and above.
Something very interesting to note with the addition on the Improved MySQL Extension is the absence of bundled MySQL client libraries with PHP5. There are numerous reasons given for this, including the different licenses that PHP and MySQL are under (PHP is under a BSD/Apache type license and MySQL is under a GPL license). The PHP5 documentation also assures developers that "there will always be MySQL support in PHP of one kind or another," but doesn't go into details as to the future of MySQL support. This perhaps is further evidence that the long-lasting popularity of LAMP environments (Linux, Apache, MySQL, PHP) will soon be replaced by SLOP environments (Sun, Linux, Oracle, PHP). If Zend continues to shy away from MySQL and completely joins forces with Sun, MySQL may soon no longer be part of the picture, and cheap, fast development may no longer be possible for PHP developers in the same capacity as it is today.
Zend clearly has underplayed the extent of the shift that has taken place concerning the future of PHP. While this version of PHP does provide a much better object model and added features, is this the beginning of the end of PHP as the choice of web scripting language for the open-source community and developers not under the employ of corporations? Will the average developer still be using PHP five years from now, or will the usefulness of PHP be limited to companies who can afford to shell out thousands of dollars for all of the necessary software that may be required to make PHP a viable option for development (along with the purchase of products from Sun, Macromedia, Oracle, Borland and others)?
While today this is still speculation, the evidence and tone lends credence to the thought that with the success of PHP, built on the backs of developers worldwide, the near future of it may include an alienation of it from those who energized it at its genesis, propelling it to the corporate enterprise status that those in control of PHP are seeking today. No matter what actually happens, developers should be aware of the major developments with PHP beyond the surface level function additions and new object model. Companies and developers who are employing PHP 5 for large-scale applications today at a reasonably low price may be in for a surprise in the next few years, if operating PHP at full capacity involves the purchase of additional, expensive software.
-
PHP5: Could PHP Soon Be Owned by Sun?
Ian Felton writes "PHP 5's official release occurred on July 13th, with a complete overhaul of object-oriented programming features and improved MySQL functions. These are sure to be great additions to the package for PHP developers. However, many of the changes to PHP are hinting at something that PHP developers might not necessarily like down the road." Read on for the rest of Felton's thoughts on the downside to corporate involvment in PHP's future.At first glance, the obvious changes to PHP are a result of the success of the Java platform and the weaknesses of PHP revealed in comparison. With the release of PHP 5, it's apparent that the developers of PHP and the Zend Engine (essentially a single group) felt compelled to make PHP much more like Java with respect to object-oriented programming. Zend, the Israeli company backing the development of PHP, promises on their web site that "full integration with Java will be closer than ever before." Hmmm, full integration with Java, huh?
On November 4th, 2003, Zend announced a strategic partnership with Sun. This deal also included advisors from Borland, Macromedia, MySQL and others. The purported purpose of this deal was to make PHP part of Sun's web server and bring it to the corporate world of development that previously had been dominated by ASP and ColdFusion. Now with the release of PHP 5, it's far more apparent which path PHP is taking.
PHP's object model was re-written from the ground up and mimics the abstract properties of Java's object method. There are private and protected members and methods, abstract classes and interfaces, in practice, identical to Java's object model. The extent of the influence that Sun has on PHP today is clear. If you have experience with Java and PHP, reading the details of the object model reveals the absolute cloning of the Java object model within PHP 5. From throwing exceptions to static variables, PHP 5's object model mimics Java in concept all the way to the syntactical level.
This is great for enterprise developers using Sun products, but with the release of PHP 5, what does this mean for the half-million PHP developers worldwide who have depended on PHP for open-source development, or for the developers whose ideas and efforts have brought PHP up through the ranks from its inception in 1995? When PHP goodies were bundled with Sun's web server on November 4th, 2003, with a $775 price tag, PHP began down the path of corporate ownership. For years developers have eagerly contributed their ideas and efforts to be a part of the success of PHP. Now that all the hard work and volunteering has paid off and PHP is a worldwide success, it appears that PHP could soon be another corporate shill owned by Sun, MySQL, Borland and Macromedia, if not on paper, then by direct influence on the people at Zend. Of course it will remain open source so that those half-million developers can continue to contribute their time and genius to its success, but if those thousands of contributions lead to direct financial gain for companies whose coffers are already overflowing and are simultaneously using those contributions to manufacture software with price tags out of reach to anyone but corporations, is PHP still the language developers should be focusing on for use in the open-source community?
On the positive side, this edition of PHP does bring improved performance and a new suite of MySQL functions. Backward incompatibility is limited to a list of ten issues. Additionally, there are only minor configuration file changes that need to be made to the web server. Several directives have been introduced for configuring php.ini files, mainly dealing with hashes for encryption.
Some very useful functions have been added to PHP5. It's been nine years in the making, but PHP5 now includes two functions to uuencode and uudecode. Combining those functions with the new socket and stream functions, developers can create a lots of "kewl" applications. An application to automatically encode and decode files to and from news servers comes to mind as an example of how to incorporate these new functions. At that point of course, a developer could use any of PHP's existing functions to continue to manipulate the files, store the contents in databases, and so on.
An addition to error reporting aids developers in keeping their code up-to-date. The E_STRICT message tells developers when their code is using deprecated functions or is in danger of not being forward compatible. However, don't assume that E_STRICT will be output if using E_ALL, because it won't. E_STRICT must be explicitly declared to output its suggestions to PHP 5 code.
While the rewriting of PHP's object model to essentially that of the Java object model does raise flags about the direction of PHP, it is still a powerful addition to the PHP5 release. Java became successful for a reason: it's intelligently designed and facilitates code reuse. By borrowing the best features of Java's object model, PHP has leveraged itself with far more credibility as a programming language that can stand on its own two feet (even if Sun, Borland and Macromedia are holding it by its arms).
Some vital re-workings in the PHP object model lie in how objects are treated in low-level fashion. Instead of passing the actual object itself, PHP's object model passes by reference. Now when operating on objects, developers can pass around multiple handles to the actual object allowing for more powerful and efficient applications. Existing PHP objects do not need to be re-written to take advantage of this change in PHP 5.
In general, developers who have experience with Java will easily adapt to PHP 5's object model. On the downside, if PHP is a developer's primary language and he or she hasn't been introduced to the world of static variables, public and private methods and the host of aspects included with this new model, they may have a bit of a learning curve adopting the higher-level format of object-oriented programming in this release. Overall, though, this change will be a plus for creating large-scale, object-oriented applications with PHP.
Keeping pace with the developments in MySQL and PHP's tight relationship, PHP5 has added a new suite of MySQL functions relating to the new features added since MySQL 4.1. Denoted as Improved MySQL Extension, its purpose is to allow developers to take advantage of prepared statements and the other additions to MySQL 4.1 and above.
Something very interesting to note with the addition on the Improved MySQL Extension is the absence of bundled MySQL client libraries with PHP5. There are numerous reasons given for this, including the different licenses that PHP and MySQL are under (PHP is under a BSD/Apache type license and MySQL is under a GPL license). The PHP5 documentation also assures developers that "there will always be MySQL support in PHP of one kind or another," but doesn't go into details as to the future of MySQL support. This perhaps is further evidence that the long-lasting popularity of LAMP environments (Linux, Apache, MySQL, PHP) will soon be replaced by SLOP environments (Sun, Linux, Oracle, PHP). If Zend continues to shy away from MySQL and completely joins forces with Sun, MySQL may soon no longer be part of the picture, and cheap, fast development may no longer be possible for PHP developers in the same capacity as it is today.
Zend clearly has underplayed the extent of the shift that has taken place concerning the future of PHP. While this version of PHP does provide a much better object model and added features, is this the beginning of the end of PHP as the choice of web scripting language for the open-source community and developers not under the employ of corporations? Will the average developer still be using PHP five years from now, or will the usefulness of PHP be limited to companies who can afford to shell out thousands of dollars for all of the necessary software that may be required to make PHP a viable option for development (along with the purchase of products from Sun, Macromedia, Oracle, Borland and others)?
While today this is still speculation, the evidence and tone lends credence to the thought that with the success of PHP, built on the backs of developers worldwide, the near future of it may include an alienation of it from those who energized it at its genesis, propelling it to the corporate enterprise status that those in control of PHP are seeking today. No matter what actually happens, developers should be aware of the major developments with PHP beyond the surface level function additions and new object model. Companies and developers who are employing PHP 5 for large-scale applications today at a reasonably low price may be in for a surprise in the next few years, if operating PHP at full capacity involves the purchase of additional, expensive software.
-
The PHP Anthology - Volume I, 'Foundations'
sympleko (Matt Leingang) writes "What a beautiful world anthology is. It comes from the Greek for a gathering of flowers, and in literature means a collection of works. Harry Fuecks, a very frequent contributor to the SitePoint community PHP forums, has gathered a bouquet of PHP best practices in a new book. The book comes in two volumes. The audience for Volume I, "Foundations," is the advanced beginner who's done one or two things in PHP, but you wants to know how to do more. Volume II, "Applications," is a design volume, mainly, and is good for people who have lots of experience with PHP but want to be better programmers. It's nice that the two volumes are separate; if you already know the syntax and mechanics of PHP you can buy Volume II and maximize d!/d$.*" Read on for Leingang's review of Volume I, and watch for his followup on Volume II. The PHP Anthology: Volume I: Foundations author Harry Fuecks pages 376 publisher SitePoint rating 7 reviewer Matthew Leingang ISBN 0957921853 summary Good start; for the real story read Volume II as well.The book is very well-written, often using a question-and-answer heading style that makes searching the table of contents easy. In the preface, we already meet the first cool aspect of the book: lots of links to sites in the form of footnotes.** Yes, most books of this genre include links to web sites, but this way makes a couple of things clear: first, that there are lot of references, so you have many places to jump to for more information, and it's a sleeker text flow: embedding URLs in dead text makes line breaking hard and detracts from the flow of the language. As you read a page, you can note, "OK, that's an online resource," and keep reading without having to stumble over an incomprehensible URL.
Each volume has numerous code examples, and they're all on the book's web page to save you from transcribing. The web site is the best place also to buy the books; they're generally not available in stores.
Chapter 1: PHP Basics
These are the foundations of the book. Quick highlights:How does one exactly RTFM? The author directs the novice to the PHP web site and explains what each part of the online manual corresponds to. But also, the coolest aspect of the PHP web site is its search-by-url feature. It looks up a function or language reference page, finds a set of likely matches, or just googles the site for you. Try it: http://php.net/array, http://php.net/sprintf, http://php.net/error.
How to understand error messages. Remember your first "cannot add header information -- headers already sent" error. Huh? Learn the difference between parse errors (what you wrote is not valid code), semantic errors (you're asking PHP to do something illegal), environment errors (PHP is not equipped to do what you want), and logic errors (PHP is happy but you're not). The last is particularly insidious (no E_PEBKAC level of reporting), but unit testing (see Volume II) gives you hope to find and fix those.
How to include. What is the difference between include and require (answer: require forces a fatal error if it can't find the file you want, while include only warns)?
How to write portable and reusable code There are hundreds of configuration directives, and using them can make one of your applications simpler. But some are to be used only with careful consideration. The magic_quotes_gpc directive, for instance, sounded like a good idea at the time it was developed. It automatically escapes user input so backslashes remain backslashes and not escape characters. A common use of this directive allowed you to insert user-supplied data directly into a database without checking to make sure any embedded quotes wouldn't create unintended SQL statements. While this does guard against SQL injection attacks, you could still end up with garbage in the database. So you still have to check user data to make sure it complies to your standards. This is easier to do before escaping magic characters, so it's better to wait until just before storage; then add all the backslashes you need. Nowadays it's considered good form to not rely on this directive and just use addslashes when you need it.
For maximal code reuse, consider object orientation. But there's a whole chapter on that...
Chapter 2: Object Oriented PHP
"Be lazy," the author writes; "Write good code." One of the ways to organize your code is through object-oriented programming. Most readers know the basic concepts of OOP, and are probably tired of the few over-simplified examples. Beyond that this chapter wants to get you to think OO, to "no longer think about long lists of tasks that a single script should accomplish; instead, [to] see programming as the putting together of a set of tools to which your script will delegate work."I know my first PHP classes were just namespaced scripts. The attributes and methods weren't at all related. This chapter (as well as Chapter 7 of Volume II) helps you distinguish where your classes are and how they connect. One of the aids for this is the use of Unified Modeling Language (UML) class diagrams. These diagrams, which use boxes for classes and arrows for the relationships between them, are really cool programming and teaching tools that require no code!
Here I think the book's physical workflow got caught in a gap between major PHP releases. The cover says this book says "PHP5 ready," which is a bit of a misnomer because all the code examples and rules are all written for PHP4. Minor text mentioning how things are going to be different in PHP5 has been inserted. It's true that none of the OO code written here will break in PHP5, but there are major additions to PHP5 especially in the OO implementation (no more ampersands! actual private variables! Exceptions! Much, much more!). Still, the author makes the point that you the programmer may not be using PHP5 for a while (PHP 5.0.0 is only a few weeks old today), and that you shouldn't put off learning PHP until version 5 is agreed to be stable.
I've read the comments of PHP bashers, arguing that using it for OO programming is a waste of overhead. The author has heard that argument, too, and rebuts:
"What they forget to mention is the drastic increase in your performance that object oriented programming delivers. After all, fast programmers cost more than fast microprocessors!"
Hear, hear. RAM and disk space are commodities, while programmers are not (yet).
Chapter 3: PHP and MySQL
This goes beyond the simple HOWTO on connecting to a database. A suite of PHP classes is developed for database connections, querying, and result handling, not as much to use as for your "health"--i.e., to see a well-done class from start to finish. For your real applications, use a real, well-maintained and tested class such as those found in PEAR. This is another principle of good programming: Somebody has probably had the same problem you are having right now, and already solved it (also known as Ecclesiastes 1:9, "...there is nothing new under the sun.")If you've done lots of SQL queries, you get to thinking that there's got to be a better way to access a database. In fact, you can build a layer of abstraction over the database connection layer to create interface classes to individual tables. This is called a persistence layer. For an implementation, see PEAR::DB_DataObject.
Any web programmer fears insecurity, and I don't mean self-doubt. The author weaves discussions of security into each chapter. For instance, you must be careful to guard against allowing users to seriously alter the nature of your SQL queries. Trust no user-supplied data! Also, this chapter gives a PHP-based solution for creating MySQL dumps.
Once you've got the data in the database, making sure users can find it is another problem. You can use LIKE relations in your queries to search field strings. The author shows how to use FULLTEXT indexes (a MySQL 4 feature) to assist in searching the entire table or any set of fields you like, all at once.
Chapter 4: Files
Sometimes databases are overkill for data storage, or you need to extract data from text files. The author gives several examples of uses of interacting with a local or remote file system. He explains:- how to slurp whole files into memory or to process them chunk-by-chunk.
- how to use the PHP built-in functions to interface with the file system (so you can make a self-updating "Last updated: " item on your pages).
- how to use .ini-style files to store configuration data -- a common configuration style which is much faster than keeping it in a RDBMS or XML file.
- how to use FTP with PHP.
- how to compress and decompress with tar through PHP.
- how to send create a file and send it to your web user (custom files generated on-the-fly and ready for download!).
Again, the security threat is raised, and the author gives pointers on how to prevent from crackers getting you to execute their code by including one of their files rather than your own.
Chapter 5: Text Manipulation
When building dynamic web sites, being able to manipulate code is a must. You need to validate the data that users send to you, as well as guard against simple HTML error or malicious cross-site scripting (XSS) attacks. There are lots of built in functions (strip_tags to remove the HTML from a string), but using regular expressions you can validate and filter just about anything. You can reimplement a restricted set of markup tags a la BBCode, or set up a custom, easily-updated profanity filter.Chapter 6: Dates and Times
Another real-world problem is formatting dates and times in a human-readable (and perhaps localizeable) way, and on the machine level manipulating dates correctly. Luckily these are all solved problems and PHP connects you to the C functions which do it. Whether you store dates as MySQL timestamps (e.g., 2004-08-03 20:07:00) or UNIX timestamps (1091578114 seconds since the epoch) is up to you, although if you use the former you'll probably have to convert to the latter at some point. Putting it all together you can create dynamic calendars where clicking on a day brings you to your appointments for that day. Another good use of date functions is a implementation of cron written entirely in PHP for those not on a unix platform.Chapter 7: Images
Once you've mastered the art of producing HTML with PHP (developed even further in Chapter 9), you'll wonder what else can do. It turns out that PHP, using glue to the GD image library, can output images as well. You can generate thumbnails of your images to create galleries. You can watermark images with text to discourage stealing them. You can hide your images behind a PHP script that protects people other than you from linking directly to your images. And you can analyze data with enough charts and graphs to make Ross Perot ecstatic.Chapter 8: Email
Contacting your users off-site is a must if you want them to come back. Furthermore, it's a nice way to register users by sending them links to an address they provide. PHP can send email natively using the mail function, but as always there are nice classes which jazz up the features. You can send HTML attachments (known by some as "spam", but we're not here to judge), even including the images in the mail. You can even use PHP as a replacement for procmail by parsing incoming mail and triggering actions based on headers.Chapter 9: Web Page Elements
Eventually you get tired of writing HTML, and interweaving markup and presentation logic can give you a headache. Can't PHP be told to format the table the right way? Another solved problem! Displaying data in a table is a common task, and classes such as PEAR::HTML_Table can take a simple data structure and beautify it for you. Forms are another area in which PHP-generated code can save you time. You can also use PHP to produce "breadcrumbs" (there's one at the top of every slashdot page) and drop-down menus that show your users where in the hierarchy of information they are. Finally the author shows how to use apache's url_rewrite module to get those question marks, file extensions, and ampersands out of your URLS and sex them up. (You can also do this without url_rewrite, completely inside PHP, but using a custom error document and examining the path requested.)Chapter 10: Error Handling
So you're all excited about your next web app, and you dive into coding, and something goes wrong. What then? This chapter is about errors. You can use the error_reporting function to customize which exceptions actually produce error messages, or create your own error messages that handle errors your own way. You can choose to log them in a database, send an e-mail to a coding team, and most importantly, recover gracefully so that your users don't see an error message. Not only is it unprofessional, it may reveal information about your program, file system, or database structure that can harm you.Appendices
There are several good appendices, which tell you which configuration directives you're probably most interested in (the complete list you can get on PHP's web site), some common security breaches, and how to install PEAR, PHP's version of CPAN. My favorite appendix is the "Hosting Provider Checklist," a great reference for evaluating whether kewlhosting.com is going to give you the freedom and support you need to make a great hosted web site.All in all, I liked this volume. Having read probably a dozen PHP books I wouldn't say it offers new information. But even though you know the plot, it's possible to enjoy a well-told story. See Volume II for heavier-duty ideas.
* My made-up calculus notation for "bang for your buck"
**Like this: http://books.slashdot.org/
In real life, Matthew Leingang is Preceptor in Mathematics at Harvard University. He promises to review any book sent to him for free, and sometimes actually does it. Slashdot welcomes readers' book reviews. To see your own review here, carefully read the book review guidelines, then visit the submission page. -
The PHP Anthology - Volume I, 'Foundations'
sympleko (Matt Leingang) writes "What a beautiful world anthology is. It comes from the Greek for a gathering of flowers, and in literature means a collection of works. Harry Fuecks, a very frequent contributor to the SitePoint community PHP forums, has gathered a bouquet of PHP best practices in a new book. The book comes in two volumes. The audience for Volume I, "Foundations," is the advanced beginner who's done one or two things in PHP, but you wants to know how to do more. Volume II, "Applications," is a design volume, mainly, and is good for people who have lots of experience with PHP but want to be better programmers. It's nice that the two volumes are separate; if you already know the syntax and mechanics of PHP you can buy Volume II and maximize d!/d$.*" Read on for Leingang's review of Volume I, and watch for his followup on Volume II. The PHP Anthology: Volume I: Foundations author Harry Fuecks pages 376 publisher SitePoint rating 7 reviewer Matthew Leingang ISBN 0957921853 summary Good start; for the real story read Volume II as well.The book is very well-written, often using a question-and-answer heading style that makes searching the table of contents easy. In the preface, we already meet the first cool aspect of the book: lots of links to sites in the form of footnotes.** Yes, most books of this genre include links to web sites, but this way makes a couple of things clear: first, that there are lot of references, so you have many places to jump to for more information, and it's a sleeker text flow: embedding URLs in dead text makes line breaking hard and detracts from the flow of the language. As you read a page, you can note, "OK, that's an online resource," and keep reading without having to stumble over an incomprehensible URL.
Each volume has numerous code examples, and they're all on the book's web page to save you from transcribing. The web site is the best place also to buy the books; they're generally not available in stores.
Chapter 1: PHP Basics
These are the foundations of the book. Quick highlights:How does one exactly RTFM? The author directs the novice to the PHP web site and explains what each part of the online manual corresponds to. But also, the coolest aspect of the PHP web site is its search-by-url feature. It looks up a function or language reference page, finds a set of likely matches, or just googles the site for you. Try it: http://php.net/array, http://php.net/sprintf, http://php.net/error.
How to understand error messages. Remember your first "cannot add header information -- headers already sent" error. Huh? Learn the difference between parse errors (what you wrote is not valid code), semantic errors (you're asking PHP to do something illegal), environment errors (PHP is not equipped to do what you want), and logic errors (PHP is happy but you're not). The last is particularly insidious (no E_PEBKAC level of reporting), but unit testing (see Volume II) gives you hope to find and fix those.
How to include. What is the difference between include and require (answer: require forces a fatal error if it can't find the file you want, while include only warns)?
How to write portable and reusable code There are hundreds of configuration directives, and using them can make one of your applications simpler. But some are to be used only with careful consideration. The magic_quotes_gpc directive, for instance, sounded like a good idea at the time it was developed. It automatically escapes user input so backslashes remain backslashes and not escape characters. A common use of this directive allowed you to insert user-supplied data directly into a database without checking to make sure any embedded quotes wouldn't create unintended SQL statements. While this does guard against SQL injection attacks, you could still end up with garbage in the database. So you still have to check user data to make sure it complies to your standards. This is easier to do before escaping magic characters, so it's better to wait until just before storage; then add all the backslashes you need. Nowadays it's considered good form to not rely on this directive and just use addslashes when you need it.
For maximal code reuse, consider object orientation. But there's a whole chapter on that...
Chapter 2: Object Oriented PHP
"Be lazy," the author writes; "Write good code." One of the ways to organize your code is through object-oriented programming. Most readers know the basic concepts of OOP, and are probably tired of the few over-simplified examples. Beyond that this chapter wants to get you to think OO, to "no longer think about long lists of tasks that a single script should accomplish; instead, [to] see programming as the putting together of a set of tools to which your script will delegate work."I know my first PHP classes were just namespaced scripts. The attributes and methods weren't at all related. This chapter (as well as Chapter 7 of Volume II) helps you distinguish where your classes are and how they connect. One of the aids for this is the use of Unified Modeling Language (UML) class diagrams. These diagrams, which use boxes for classes and arrows for the relationships between them, are really cool programming and teaching tools that require no code!
Here I think the book's physical workflow got caught in a gap between major PHP releases. The cover says this book says "PHP5 ready," which is a bit of a misnomer because all the code examples and rules are all written for PHP4. Minor text mentioning how things are going to be different in PHP5 has been inserted. It's true that none of the OO code written here will break in PHP5, but there are major additions to PHP5 especially in the OO implementation (no more ampersands! actual private variables! Exceptions! Much, much more!). Still, the author makes the point that you the programmer may not be using PHP5 for a while (PHP 5.0.0 is only a few weeks old today), and that you shouldn't put off learning PHP until version 5 is agreed to be stable.
I've read the comments of PHP bashers, arguing that using it for OO programming is a waste of overhead. The author has heard that argument, too, and rebuts:
"What they forget to mention is the drastic increase in your performance that object oriented programming delivers. After all, fast programmers cost more than fast microprocessors!"
Hear, hear. RAM and disk space are commodities, while programmers are not (yet).
Chapter 3: PHP and MySQL
This goes beyond the simple HOWTO on connecting to a database. A suite of PHP classes is developed for database connections, querying, and result handling, not as much to use as for your "health"--i.e., to see a well-done class from start to finish. For your real applications, use a real, well-maintained and tested class such as those found in PEAR. This is another principle of good programming: Somebody has probably had the same problem you are having right now, and already solved it (also known as Ecclesiastes 1:9, "...there is nothing new under the sun.")If you've done lots of SQL queries, you get to thinking that there's got to be a better way to access a database. In fact, you can build a layer of abstraction over the database connection layer to create interface classes to individual tables. This is called a persistence layer. For an implementation, see PEAR::DB_DataObject.
Any web programmer fears insecurity, and I don't mean self-doubt. The author weaves discussions of security into each chapter. For instance, you must be careful to guard against allowing users to seriously alter the nature of your SQL queries. Trust no user-supplied data! Also, this chapter gives a PHP-based solution for creating MySQL dumps.
Once you've got the data in the database, making sure users can find it is another problem. You can use LIKE relations in your queries to search field strings. The author shows how to use FULLTEXT indexes (a MySQL 4 feature) to assist in searching the entire table or any set of fields you like, all at once.
Chapter 4: Files
Sometimes databases are overkill for data storage, or you need to extract data from text files. The author gives several examples of uses of interacting with a local or remote file system. He explains:- how to slurp whole files into memory or to process them chunk-by-chunk.
- how to use the PHP built-in functions to interface with the file system (so you can make a self-updating "Last updated: " item on your pages).
- how to use .ini-style files to store configuration data -- a common configuration style which is much faster than keeping it in a RDBMS or XML file.
- how to use FTP with PHP.
- how to compress and decompress with tar through PHP.
- how to send create a file and send it to your web user (custom files generated on-the-fly and ready for download!).
Again, the security threat is raised, and the author gives pointers on how to prevent from crackers getting you to execute their code by including one of their files rather than your own.
Chapter 5: Text Manipulation
When building dynamic web sites, being able to manipulate code is a must. You need to validate the data that users send to you, as well as guard against simple HTML error or malicious cross-site scripting (XSS) attacks. There are lots of built in functions (strip_tags to remove the HTML from a string), but using regular expressions you can validate and filter just about anything. You can reimplement a restricted set of markup tags a la BBCode, or set up a custom, easily-updated profanity filter.Chapter 6: Dates and Times
Another real-world problem is formatting dates and times in a human-readable (and perhaps localizeable) way, and on the machine level manipulating dates correctly. Luckily these are all solved problems and PHP connects you to the C functions which do it. Whether you store dates as MySQL timestamps (e.g., 2004-08-03 20:07:00) or UNIX timestamps (1091578114 seconds since the epoch) is up to you, although if you use the former you'll probably have to convert to the latter at some point. Putting it all together you can create dynamic calendars where clicking on a day brings you to your appointments for that day. Another good use of date functions is a implementation of cron written entirely in PHP for those not on a unix platform.Chapter 7: Images
Once you've mastered the art of producing HTML with PHP (developed even further in Chapter 9), you'll wonder what else can do. It turns out that PHP, using glue to the GD image library, can output images as well. You can generate thumbnails of your images to create galleries. You can watermark images with text to discourage stealing them. You can hide your images behind a PHP script that protects people other than you from linking directly to your images. And you can analyze data with enough charts and graphs to make Ross Perot ecstatic.Chapter 8: Email
Contacting your users off-site is a must if you want them to come back. Furthermore, it's a nice way to register users by sending them links to an address they provide. PHP can send email natively using the mail function, but as always there are nice classes which jazz up the features. You can send HTML attachments (known by some as "spam", but we're not here to judge), even including the images in the mail. You can even use PHP as a replacement for procmail by parsing incoming mail and triggering actions based on headers.Chapter 9: Web Page Elements
Eventually you get tired of writing HTML, and interweaving markup and presentation logic can give you a headache. Can't PHP be told to format the table the right way? Another solved problem! Displaying data in a table is a common task, and classes such as PEAR::HTML_Table can take a simple data structure and beautify it for you. Forms are another area in which PHP-generated code can save you time. You can also use PHP to produce "breadcrumbs" (there's one at the top of every slashdot page) and drop-down menus that show your users where in the hierarchy of information they are. Finally the author shows how to use apache's url_rewrite module to get those question marks, file extensions, and ampersands out of your URLS and sex them up. (You can also do this without url_rewrite, completely inside PHP, but using a custom error document and examining the path requested.)Chapter 10: Error Handling
So you're all excited about your next web app, and you dive into coding, and something goes wrong. What then? This chapter is about errors. You can use the error_reporting function to customize which exceptions actually produce error messages, or create your own error messages that handle errors your own way. You can choose to log them in a database, send an e-mail to a coding team, and most importantly, recover gracefully so that your users don't see an error message. Not only is it unprofessional, it may reveal information about your program, file system, or database structure that can harm you.Appendices
There are several good appendices, which tell you which configuration directives you're probably most interested in (the complete list you can get on PHP's web site), some common security breaches, and how to install PEAR, PHP's version of CPAN. My favorite appendix is the "Hosting Provider Checklist," a great reference for evaluating whether kewlhosting.com is going to give you the freedom and support you need to make a great hosted web site.All in all, I liked this volume. Having read probably a dozen PHP books I wouldn't say it offers new information. But even though you know the plot, it's possible to enjoy a well-told story. See Volume II for heavier-duty ideas.
* My made-up calculus notation for "bang for your buck"
**Like this: http://books.slashdot.org/
In real life, Matthew Leingang is Preceptor in Mathematics at Harvard University. He promises to review any book sent to him for free, and sometimes actually does it. Slashdot welcomes readers' book reviews. To see your own review here, carefully read the book review guidelines, then visit the submission page. -
The PHP Anthology - Volume I, 'Foundations'
sympleko (Matt Leingang) writes "What a beautiful world anthology is. It comes from the Greek for a gathering of flowers, and in literature means a collection of works. Harry Fuecks, a very frequent contributor to the SitePoint community PHP forums, has gathered a bouquet of PHP best practices in a new book. The book comes in two volumes. The audience for Volume I, "Foundations," is the advanced beginner who's done one or two things in PHP, but you wants to know how to do more. Volume II, "Applications," is a design volume, mainly, and is good for people who have lots of experience with PHP but want to be better programmers. It's nice that the two volumes are separate; if you already know the syntax and mechanics of PHP you can buy Volume II and maximize d!/d$.*" Read on for Leingang's review of Volume I, and watch for his followup on Volume II. The PHP Anthology: Volume I: Foundations author Harry Fuecks pages 376 publisher SitePoint rating 7 reviewer Matthew Leingang ISBN 0957921853 summary Good start; for the real story read Volume II as well.The book is very well-written, often using a question-and-answer heading style that makes searching the table of contents easy. In the preface, we already meet the first cool aspect of the book: lots of links to sites in the form of footnotes.** Yes, most books of this genre include links to web sites, but this way makes a couple of things clear: first, that there are lot of references, so you have many places to jump to for more information, and it's a sleeker text flow: embedding URLs in dead text makes line breaking hard and detracts from the flow of the language. As you read a page, you can note, "OK, that's an online resource," and keep reading without having to stumble over an incomprehensible URL.
Each volume has numerous code examples, and they're all on the book's web page to save you from transcribing. The web site is the best place also to buy the books; they're generally not available in stores.
Chapter 1: PHP Basics
These are the foundations of the book. Quick highlights:How does one exactly RTFM? The author directs the novice to the PHP web site and explains what each part of the online manual corresponds to. But also, the coolest aspect of the PHP web site is its search-by-url feature. It looks up a function or language reference page, finds a set of likely matches, or just googles the site for you. Try it: http://php.net/array, http://php.net/sprintf, http://php.net/error.
How to understand error messages. Remember your first "cannot add header information -- headers already sent" error. Huh? Learn the difference between parse errors (what you wrote is not valid code), semantic errors (you're asking PHP to do something illegal), environment errors (PHP is not equipped to do what you want), and logic errors (PHP is happy but you're not). The last is particularly insidious (no E_PEBKAC level of reporting), but unit testing (see Volume II) gives you hope to find and fix those.
How to include. What is the difference between include and require (answer: require forces a fatal error if it can't find the file you want, while include only warns)?
How to write portable and reusable code There are hundreds of configuration directives, and using them can make one of your applications simpler. But some are to be used only with careful consideration. The magic_quotes_gpc directive, for instance, sounded like a good idea at the time it was developed. It automatically escapes user input so backslashes remain backslashes and not escape characters. A common use of this directive allowed you to insert user-supplied data directly into a database without checking to make sure any embedded quotes wouldn't create unintended SQL statements. While this does guard against SQL injection attacks, you could still end up with garbage in the database. So you still have to check user data to make sure it complies to your standards. This is easier to do before escaping magic characters, so it's better to wait until just before storage; then add all the backslashes you need. Nowadays it's considered good form to not rely on this directive and just use addslashes when you need it.
For maximal code reuse, consider object orientation. But there's a whole chapter on that...
Chapter 2: Object Oriented PHP
"Be lazy," the author writes; "Write good code." One of the ways to organize your code is through object-oriented programming. Most readers know the basic concepts of OOP, and are probably tired of the few over-simplified examples. Beyond that this chapter wants to get you to think OO, to "no longer think about long lists of tasks that a single script should accomplish; instead, [to] see programming as the putting together of a set of tools to which your script will delegate work."I know my first PHP classes were just namespaced scripts. The attributes and methods weren't at all related. This chapter (as well as Chapter 7 of Volume II) helps you distinguish where your classes are and how they connect. One of the aids for this is the use of Unified Modeling Language (UML) class diagrams. These diagrams, which use boxes for classes and arrows for the relationships between them, are really cool programming and teaching tools that require no code!
Here I think the book's physical workflow got caught in a gap between major PHP releases. The cover says this book says "PHP5 ready," which is a bit of a misnomer because all the code examples and rules are all written for PHP4. Minor text mentioning how things are going to be different in PHP5 has been inserted. It's true that none of the OO code written here will break in PHP5, but there are major additions to PHP5 especially in the OO implementation (no more ampersands! actual private variables! Exceptions! Much, much more!). Still, the author makes the point that you the programmer may not be using PHP5 for a while (PHP 5.0.0 is only a few weeks old today), and that you shouldn't put off learning PHP until version 5 is agreed to be stable.
I've read the comments of PHP bashers, arguing that using it for OO programming is a waste of overhead. The author has heard that argument, too, and rebuts:
"What they forget to mention is the drastic increase in your performance that object oriented programming delivers. After all, fast programmers cost more than fast microprocessors!"
Hear, hear. RAM and disk space are commodities, while programmers are not (yet).
Chapter 3: PHP and MySQL
This goes beyond the simple HOWTO on connecting to a database. A suite of PHP classes is developed for database connections, querying, and result handling, not as much to use as for your "health"--i.e., to see a well-done class from start to finish. For your real applications, use a real, well-maintained and tested class such as those found in PEAR. This is another principle of good programming: Somebody has probably had the same problem you are having right now, and already solved it (also known as Ecclesiastes 1:9, "...there is nothing new under the sun.")If you've done lots of SQL queries, you get to thinking that there's got to be a better way to access a database. In fact, you can build a layer of abstraction over the database connection layer to create interface classes to individual tables. This is called a persistence layer. For an implementation, see PEAR::DB_DataObject.
Any web programmer fears insecurity, and I don't mean self-doubt. The author weaves discussions of security into each chapter. For instance, you must be careful to guard against allowing users to seriously alter the nature of your SQL queries. Trust no user-supplied data! Also, this chapter gives a PHP-based solution for creating MySQL dumps.
Once you've got the data in the database, making sure users can find it is another problem. You can use LIKE relations in your queries to search field strings. The author shows how to use FULLTEXT indexes (a MySQL 4 feature) to assist in searching the entire table or any set of fields you like, all at once.
Chapter 4: Files
Sometimes databases are overkill for data storage, or you need to extract data from text files. The author gives several examples of uses of interacting with a local or remote file system. He explains:- how to slurp whole files into memory or to process them chunk-by-chunk.
- how to use the PHP built-in functions to interface with the file system (so you can make a self-updating "Last updated: " item on your pages).
- how to use .ini-style files to store configuration data -- a common configuration style which is much faster than keeping it in a RDBMS or XML file.
- how to use FTP with PHP.
- how to compress and decompress with tar through PHP.
- how to send create a file and send it to your web user (custom files generated on-the-fly and ready for download!).
Again, the security threat is raised, and the author gives pointers on how to prevent from crackers getting you to execute their code by including one of their files rather than your own.
Chapter 5: Text Manipulation
When building dynamic web sites, being able to manipulate code is a must. You need to validate the data that users send to you, as well as guard against simple HTML error or malicious cross-site scripting (XSS) attacks. There are lots of built in functions (strip_tags to remove the HTML from a string), but using regular expressions you can validate and filter just about anything. You can reimplement a restricted set of markup tags a la BBCode, or set up a custom, easily-updated profanity filter.Chapter 6: Dates and Times
Another real-world problem is formatting dates and times in a human-readable (and perhaps localizeable) way, and on the machine level manipulating dates correctly. Luckily these are all solved problems and PHP connects you to the C functions which do it. Whether you store dates as MySQL timestamps (e.g., 2004-08-03 20:07:00) or UNIX timestamps (1091578114 seconds since the epoch) is up to you, although if you use the former you'll probably have to convert to the latter at some point. Putting it all together you can create dynamic calendars where clicking on a day brings you to your appointments for that day. Another good use of date functions is a implementation of cron written entirely in PHP for those not on a unix platform.Chapter 7: Images
Once you've mastered the art of producing HTML with PHP (developed even further in Chapter 9), you'll wonder what else can do. It turns out that PHP, using glue to the GD image library, can output images as well. You can generate thumbnails of your images to create galleries. You can watermark images with text to discourage stealing them. You can hide your images behind a PHP script that protects people other than you from linking directly to your images. And you can analyze data with enough charts and graphs to make Ross Perot ecstatic.Chapter 8: Email
Contacting your users off-site is a must if you want them to come back. Furthermore, it's a nice way to register users by sending them links to an address they provide. PHP can send email natively using the mail function, but as always there are nice classes which jazz up the features. You can send HTML attachments (known by some as "spam", but we're not here to judge), even including the images in the mail. You can even use PHP as a replacement for procmail by parsing incoming mail and triggering actions based on headers.Chapter 9: Web Page Elements
Eventually you get tired of writing HTML, and interweaving markup and presentation logic can give you a headache. Can't PHP be told to format the table the right way? Another solved problem! Displaying data in a table is a common task, and classes such as PEAR::HTML_Table can take a simple data structure and beautify it for you. Forms are another area in which PHP-generated code can save you time. You can also use PHP to produce "breadcrumbs" (there's one at the top of every slashdot page) and drop-down menus that show your users where in the hierarchy of information they are. Finally the author shows how to use apache's url_rewrite module to get those question marks, file extensions, and ampersands out of your URLS and sex them up. (You can also do this without url_rewrite, completely inside PHP, but using a custom error document and examining the path requested.)Chapter 10: Error Handling
So you're all excited about your next web app, and you dive into coding, and something goes wrong. What then? This chapter is about errors. You can use the error_reporting function to customize which exceptions actually produce error messages, or create your own error messages that handle errors your own way. You can choose to log them in a database, send an e-mail to a coding team, and most importantly, recover gracefully so that your users don't see an error message. Not only is it unprofessional, it may reveal information about your program, file system, or database structure that can harm you.Appendices
There are several good appendices, which tell you which configuration directives you're probably most interested in (the complete list you can get on PHP's web site), some common security breaches, and how to install PEAR, PHP's version of CPAN. My favorite appendix is the "Hosting Provider Checklist," a great reference for evaluating whether kewlhosting.com is going to give you the freedom and support you need to make a great hosted web site.All in all, I liked this volume. Having read probably a dozen PHP books I wouldn't say it offers new information. But even though you know the plot, it's possible to enjoy a well-told story. See Volume II for heavier-duty ideas.
* My made-up calculus notation for "bang for your buck"
**Like this: http://books.slashdot.org/
In real life, Matthew Leingang is Preceptor in Mathematics at Harvard University. He promises to review any book sent to him for free, and sometimes actually does it. Slashdot welcomes readers' book reviews. To see your own review here, carefully read the book review guidelines, then visit the submission page. -
The PHP Anthology - Volume I, 'Foundations'
sympleko (Matt Leingang) writes "What a beautiful world anthology is. It comes from the Greek for a gathering of flowers, and in literature means a collection of works. Harry Fuecks, a very frequent contributor to the SitePoint community PHP forums, has gathered a bouquet of PHP best practices in a new book. The book comes in two volumes. The audience for Volume I, "Foundations," is the advanced beginner who's done one or two things in PHP, but you wants to know how to do more. Volume II, "Applications," is a design volume, mainly, and is good for people who have lots of experience with PHP but want to be better programmers. It's nice that the two volumes are separate; if you already know the syntax and mechanics of PHP you can buy Volume II and maximize d!/d$.*" Read on for Leingang's review of Volume I, and watch for his followup on Volume II. The PHP Anthology: Volume I: Foundations author Harry Fuecks pages 376 publisher SitePoint rating 7 reviewer Matthew Leingang ISBN 0957921853 summary Good start; for the real story read Volume II as well.The book is very well-written, often using a question-and-answer heading style that makes searching the table of contents easy. In the preface, we already meet the first cool aspect of the book: lots of links to sites in the form of footnotes.** Yes, most books of this genre include links to web sites, but this way makes a couple of things clear: first, that there are lot of references, so you have many places to jump to for more information, and it's a sleeker text flow: embedding URLs in dead text makes line breaking hard and detracts from the flow of the language. As you read a page, you can note, "OK, that's an online resource," and keep reading without having to stumble over an incomprehensible URL.
Each volume has numerous code examples, and they're all on the book's web page to save you from transcribing. The web site is the best place also to buy the books; they're generally not available in stores.
Chapter 1: PHP Basics
These are the foundations of the book. Quick highlights:How does one exactly RTFM? The author directs the novice to the PHP web site and explains what each part of the online manual corresponds to. But also, the coolest aspect of the PHP web site is its search-by-url feature. It looks up a function or language reference page, finds a set of likely matches, or just googles the site for you. Try it: http://php.net/array, http://php.net/sprintf, http://php.net/error.
How to understand error messages. Remember your first "cannot add header information -- headers already sent" error. Huh? Learn the difference between parse errors (what you wrote is not valid code), semantic errors (you're asking PHP to do something illegal), environment errors (PHP is not equipped to do what you want), and logic errors (PHP is happy but you're not). The last is particularly insidious (no E_PEBKAC level of reporting), but unit testing (see Volume II) gives you hope to find and fix those.
How to include. What is the difference between include and require (answer: require forces a fatal error if it can't find the file you want, while include only warns)?
How to write portable and reusable code There are hundreds of configuration directives, and using them can make one of your applications simpler. But some are to be used only with careful consideration. The magic_quotes_gpc directive, for instance, sounded like a good idea at the time it was developed. It automatically escapes user input so backslashes remain backslashes and not escape characters. A common use of this directive allowed you to insert user-supplied data directly into a database without checking to make sure any embedded quotes wouldn't create unintended SQL statements. While this does guard against SQL injection attacks, you could still end up with garbage in the database. So you still have to check user data to make sure it complies to your standards. This is easier to do before escaping magic characters, so it's better to wait until just before storage; then add all the backslashes you need. Nowadays it's considered good form to not rely on this directive and just use addslashes when you need it.
For maximal code reuse, consider object orientation. But there's a whole chapter on that...
Chapter 2: Object Oriented PHP
"Be lazy," the author writes; "Write good code." One of the ways to organize your code is through object-oriented programming. Most readers know the basic concepts of OOP, and are probably tired of the few over-simplified examples. Beyond that this chapter wants to get you to think OO, to "no longer think about long lists of tasks that a single script should accomplish; instead, [to] see programming as the putting together of a set of tools to which your script will delegate work."I know my first PHP classes were just namespaced scripts. The attributes and methods weren't at all related. This chapter (as well as Chapter 7 of Volume II) helps you distinguish where your classes are and how they connect. One of the aids for this is the use of Unified Modeling Language (UML) class diagrams. These diagrams, which use boxes for classes and arrows for the relationships between them, are really cool programming and teaching tools that require no code!
Here I think the book's physical workflow got caught in a gap between major PHP releases. The cover says this book says "PHP5 ready," which is a bit of a misnomer because all the code examples and rules are all written for PHP4. Minor text mentioning how things are going to be different in PHP5 has been inserted. It's true that none of the OO code written here will break in PHP5, but there are major additions to PHP5 especially in the OO implementation (no more ampersands! actual private variables! Exceptions! Much, much more!). Still, the author makes the point that you the programmer may not be using PHP5 for a while (PHP 5.0.0 is only a few weeks old today), and that you shouldn't put off learning PHP until version 5 is agreed to be stable.
I've read the comments of PHP bashers, arguing that using it for OO programming is a waste of overhead. The author has heard that argument, too, and rebuts:
"What they forget to mention is the drastic increase in your performance that object oriented programming delivers. After all, fast programmers cost more than fast microprocessors!"
Hear, hear. RAM and disk space are commodities, while programmers are not (yet).
Chapter 3: PHP and MySQL
This goes beyond the simple HOWTO on connecting to a database. A suite of PHP classes is developed for database connections, querying, and result handling, not as much to use as for your "health"--i.e., to see a well-done class from start to finish. For your real applications, use a real, well-maintained and tested class such as those found in PEAR. This is another principle of good programming: Somebody has probably had the same problem you are having right now, and already solved it (also known as Ecclesiastes 1:9, "...there is nothing new under the sun.")If you've done lots of SQL queries, you get to thinking that there's got to be a better way to access a database. In fact, you can build a layer of abstraction over the database connection layer to create interface classes to individual tables. This is called a persistence layer. For an implementation, see PEAR::DB_DataObject.
Any web programmer fears insecurity, and I don't mean self-doubt. The author weaves discussions of security into each chapter. For instance, you must be careful to guard against allowing users to seriously alter the nature of your SQL queries. Trust no user-supplied data! Also, this chapter gives a PHP-based solution for creating MySQL dumps.
Once you've got the data in the database, making sure users can find it is another problem. You can use LIKE relations in your queries to search field strings. The author shows how to use FULLTEXT indexes (a MySQL 4 feature) to assist in searching the entire table or any set of fields you like, all at once.
Chapter 4: Files
Sometimes databases are overkill for data storage, or you need to extract data from text files. The author gives several examples of uses of interacting with a local or remote file system. He explains:- how to slurp whole files into memory or to process them chunk-by-chunk.
- how to use the PHP built-in functions to interface with the file system (so you can make a self-updating "Last updated: " item on your pages).
- how to use .ini-style files to store configuration data -- a common configuration style which is much faster than keeping it in a RDBMS or XML file.
- how to use FTP with PHP.
- how to compress and decompress with tar through PHP.
- how to send create a file and send it to your web user (custom files generated on-the-fly and ready for download!).
Again, the security threat is raised, and the author gives pointers on how to prevent from crackers getting you to execute their code by including one of their files rather than your own.
Chapter 5: Text Manipulation
When building dynamic web sites, being able to manipulate code is a must. You need to validate the data that users send to you, as well as guard against simple HTML error or malicious cross-site scripting (XSS) attacks. There are lots of built in functions (strip_tags to remove the HTML from a string), but using regular expressions you can validate and filter just about anything. You can reimplement a restricted set of markup tags a la BBCode, or set up a custom, easily-updated profanity filter.Chapter 6: Dates and Times
Another real-world problem is formatting dates and times in a human-readable (and perhaps localizeable) way, and on the machine level manipulating dates correctly. Luckily these are all solved problems and PHP connects you to the C functions which do it. Whether you store dates as MySQL timestamps (e.g., 2004-08-03 20:07:00) or UNIX timestamps (1091578114 seconds since the epoch) is up to you, although if you use the former you'll probably have to convert to the latter at some point. Putting it all together you can create dynamic calendars where clicking on a day brings you to your appointments for that day. Another good use of date functions is a implementation of cron written entirely in PHP for those not on a unix platform.Chapter 7: Images
Once you've mastered the art of producing HTML with PHP (developed even further in Chapter 9), you'll wonder what else can do. It turns out that PHP, using glue to the GD image library, can output images as well. You can generate thumbnails of your images to create galleries. You can watermark images with text to discourage stealing them. You can hide your images behind a PHP script that protects people other than you from linking directly to your images. And you can analyze data with enough charts and graphs to make Ross Perot ecstatic.Chapter 8: Email
Contacting your users off-site is a must if you want them to come back. Furthermore, it's a nice way to register users by sending them links to an address they provide. PHP can send email natively using the mail function, but as always there are nice classes which jazz up the features. You can send HTML attachments (known by some as "spam", but we're not here to judge), even including the images in the mail. You can even use PHP as a replacement for procmail by parsing incoming mail and triggering actions based on headers.Chapter 9: Web Page Elements
Eventually you get tired of writing HTML, and interweaving markup and presentation logic can give you a headache. Can't PHP be told to format the table the right way? Another solved problem! Displaying data in a table is a common task, and classes such as PEAR::HTML_Table can take a simple data structure and beautify it for you. Forms are another area in which PHP-generated code can save you time. You can also use PHP to produce "breadcrumbs" (there's one at the top of every slashdot page) and drop-down menus that show your users where in the hierarchy of information they are. Finally the author shows how to use apache's url_rewrite module to get those question marks, file extensions, and ampersands out of your URLS and sex them up. (You can also do this without url_rewrite, completely inside PHP, but using a custom error document and examining the path requested.)Chapter 10: Error Handling
So you're all excited about your next web app, and you dive into coding, and something goes wrong. What then? This chapter is about errors. You can use the error_reporting function to customize which exceptions actually produce error messages, or create your own error messages that handle errors your own way. You can choose to log them in a database, send an e-mail to a coding team, and most importantly, recover gracefully so that your users don't see an error message. Not only is it unprofessional, it may reveal information about your program, file system, or database structure that can harm you.Appendices
There are several good appendices, which tell you which configuration directives you're probably most interested in (the complete list you can get on PHP's web site), some common security breaches, and how to install PEAR, PHP's version of CPAN. My favorite appendix is the "Hosting Provider Checklist," a great reference for evaluating whether kewlhosting.com is going to give you the freedom and support you need to make a great hosted web site.All in all, I liked this volume. Having read probably a dozen PHP books I wouldn't say it offers new information. But even though you know the plot, it's possible to enjoy a well-told story. See Volume II for heavier-duty ideas.
* My made-up calculus notation for "bang for your buck"
**Like this: http://books.slashdot.org/
In real life, Matthew Leingang is Preceptor in Mathematics at Harvard University. He promises to review any book sent to him for free, and sometimes actually does it. Slashdot welcomes readers' book reviews. To see your own review here, carefully read the book review guidelines, then visit the submission page. -
The PHP Anthology - Volume I, 'Foundations'
sympleko (Matt Leingang) writes "What a beautiful world anthology is. It comes from the Greek for a gathering of flowers, and in literature means a collection of works. Harry Fuecks, a very frequent contributor to the SitePoint community PHP forums, has gathered a bouquet of PHP best practices in a new book. The book comes in two volumes. The audience for Volume I, "Foundations," is the advanced beginner who's done one or two things in PHP, but you wants to know how to do more. Volume II, "Applications," is a design volume, mainly, and is good for people who have lots of experience with PHP but want to be better programmers. It's nice that the two volumes are separate; if you already know the syntax and mechanics of PHP you can buy Volume II and maximize d!/d$.*" Read on for Leingang's review of Volume I, and watch for his followup on Volume II. The PHP Anthology: Volume I: Foundations author Harry Fuecks pages 376 publisher SitePoint rating 7 reviewer Matthew Leingang ISBN 0957921853 summary Good start; for the real story read Volume II as well.The book is very well-written, often using a question-and-answer heading style that makes searching the table of contents easy. In the preface, we already meet the first cool aspect of the book: lots of links to sites in the form of footnotes.** Yes, most books of this genre include links to web sites, but this way makes a couple of things clear: first, that there are lot of references, so you have many places to jump to for more information, and it's a sleeker text flow: embedding URLs in dead text makes line breaking hard and detracts from the flow of the language. As you read a page, you can note, "OK, that's an online resource," and keep reading without having to stumble over an incomprehensible URL.
Each volume has numerous code examples, and they're all on the book's web page to save you from transcribing. The web site is the best place also to buy the books; they're generally not available in stores.
Chapter 1: PHP Basics
These are the foundations of the book. Quick highlights:How does one exactly RTFM? The author directs the novice to the PHP web site and explains what each part of the online manual corresponds to. But also, the coolest aspect of the PHP web site is its search-by-url feature. It looks up a function or language reference page, finds a set of likely matches, or just googles the site for you. Try it: http://php.net/array, http://php.net/sprintf, http://php.net/error.
How to understand error messages. Remember your first "cannot add header information -- headers already sent" error. Huh? Learn the difference between parse errors (what you wrote is not valid code), semantic errors (you're asking PHP to do something illegal), environment errors (PHP is not equipped to do what you want), and logic errors (PHP is happy but you're not). The last is particularly insidious (no E_PEBKAC level of reporting), but unit testing (see Volume II) gives you hope to find and fix those.
How to include. What is the difference between include and require (answer: require forces a fatal error if it can't find the file you want, while include only warns)?
How to write portable and reusable code There are hundreds of configuration directives, and using them can make one of your applications simpler. But some are to be used only with careful consideration. The magic_quotes_gpc directive, for instance, sounded like a good idea at the time it was developed. It automatically escapes user input so backslashes remain backslashes and not escape characters. A common use of this directive allowed you to insert user-supplied data directly into a database without checking to make sure any embedded quotes wouldn't create unintended SQL statements. While this does guard against SQL injection attacks, you could still end up with garbage in the database. So you still have to check user data to make sure it complies to your standards. This is easier to do before escaping magic characters, so it's better to wait until just before storage; then add all the backslashes you need. Nowadays it's considered good form to not rely on this directive and just use addslashes when you need it.
For maximal code reuse, consider object orientation. But there's a whole chapter on that...
Chapter 2: Object Oriented PHP
"Be lazy," the author writes; "Write good code." One of the ways to organize your code is through object-oriented programming. Most readers know the basic concepts of OOP, and are probably tired of the few over-simplified examples. Beyond that this chapter wants to get you to think OO, to "no longer think about long lists of tasks that a single script should accomplish; instead, [to] see programming as the putting together of a set of tools to which your script will delegate work."I know my first PHP classes were just namespaced scripts. The attributes and methods weren't at all related. This chapter (as well as Chapter 7 of Volume II) helps you distinguish where your classes are and how they connect. One of the aids for this is the use of Unified Modeling Language (UML) class diagrams. These diagrams, which use boxes for classes and arrows for the relationships between them, are really cool programming and teaching tools that require no code!
Here I think the book's physical workflow got caught in a gap between major PHP releases. The cover says this book says "PHP5 ready," which is a bit of a misnomer because all the code examples and rules are all written for PHP4. Minor text mentioning how things are going to be different in PHP5 has been inserted. It's true that none of the OO code written here will break in PHP5, but there are major additions to PHP5 especially in the OO implementation (no more ampersands! actual private variables! Exceptions! Much, much more!). Still, the author makes the point that you the programmer may not be using PHP5 for a while (PHP 5.0.0 is only a few weeks old today), and that you shouldn't put off learning PHP until version 5 is agreed to be stable.
I've read the comments of PHP bashers, arguing that using it for OO programming is a waste of overhead. The author has heard that argument, too, and rebuts:
"What they forget to mention is the drastic increase in your performance that object oriented programming delivers. After all, fast programmers cost more than fast microprocessors!"
Hear, hear. RAM and disk space are commodities, while programmers are not (yet).
Chapter 3: PHP and MySQL
This goes beyond the simple HOWTO on connecting to a database. A suite of PHP classes is developed for database connections, querying, and result handling, not as much to use as for your "health"--i.e., to see a well-done class from start to finish. For your real applications, use a real, well-maintained and tested class such as those found in PEAR. This is another principle of good programming: Somebody has probably had the same problem you are having right now, and already solved it (also known as Ecclesiastes 1:9, "...there is nothing new under the sun.")If you've done lots of SQL queries, you get to thinking that there's got to be a better way to access a database. In fact, you can build a layer of abstraction over the database connection layer to create interface classes to individual tables. This is called a persistence layer. For an implementation, see PEAR::DB_DataObject.
Any web programmer fears insecurity, and I don't mean self-doubt. The author weaves discussions of security into each chapter. For instance, you must be careful to guard against allowing users to seriously alter the nature of your SQL queries. Trust no user-supplied data! Also, this chapter gives a PHP-based solution for creating MySQL dumps.
Once you've got the data in the database, making sure users can find it is another problem. You can use LIKE relations in your queries to search field strings. The author shows how to use FULLTEXT indexes (a MySQL 4 feature) to assist in searching the entire table or any set of fields you like, all at once.
Chapter 4: Files
Sometimes databases are overkill for data storage, or you need to extract data from text files. The author gives several examples of uses of interacting with a local or remote file system. He explains:- how to slurp whole files into memory or to process them chunk-by-chunk.
- how to use the PHP built-in functions to interface with the file system (so you can make a self-updating "Last updated: " item on your pages).
- how to use .ini-style files to store configuration data -- a common configuration style which is much faster than keeping it in a RDBMS or XML file.
- how to use FTP with PHP.
- how to compress and decompress with tar through PHP.
- how to send create a file and send it to your web user (custom files generated on-the-fly and ready for download!).
Again, the security threat is raised, and the author gives pointers on how to prevent from crackers getting you to execute their code by including one of their files rather than your own.
Chapter 5: Text Manipulation
When building dynamic web sites, being able to manipulate code is a must. You need to validate the data that users send to you, as well as guard against simple HTML error or malicious cross-site scripting (XSS) attacks. There are lots of built in functions (strip_tags to remove the HTML from a string), but using regular expressions you can validate and filter just about anything. You can reimplement a restricted set of markup tags a la BBCode, or set up a custom, easily-updated profanity filter.Chapter 6: Dates and Times
Another real-world problem is formatting dates and times in a human-readable (and perhaps localizeable) way, and on the machine level manipulating dates correctly. Luckily these are all solved problems and PHP connects you to the C functions which do it. Whether you store dates as MySQL timestamps (e.g., 2004-08-03 20:07:00) or UNIX timestamps (1091578114 seconds since the epoch) is up to you, although if you use the former you'll probably have to convert to the latter at some point. Putting it all together you can create dynamic calendars where clicking on a day brings you to your appointments for that day. Another good use of date functions is a implementation of cron written entirely in PHP for those not on a unix platform.Chapter 7: Images
Once you've mastered the art of producing HTML with PHP (developed even further in Chapter 9), you'll wonder what else can do. It turns out that PHP, using glue to the GD image library, can output images as well. You can generate thumbnails of your images to create galleries. You can watermark images with text to discourage stealing them. You can hide your images behind a PHP script that protects people other than you from linking directly to your images. And you can analyze data with enough charts and graphs to make Ross Perot ecstatic.Chapter 8: Email
Contacting your users off-site is a must if you want them to come back. Furthermore, it's a nice way to register users by sending them links to an address they provide. PHP can send email natively using the mail function, but as always there are nice classes which jazz up the features. You can send HTML attachments (known by some as "spam", but we're not here to judge), even including the images in the mail. You can even use PHP as a replacement for procmail by parsing incoming mail and triggering actions based on headers.Chapter 9: Web Page Elements
Eventually you get tired of writing HTML, and interweaving markup and presentation logic can give you a headache. Can't PHP be told to format the table the right way? Another solved problem! Displaying data in a table is a common task, and classes such as PEAR::HTML_Table can take a simple data structure and beautify it for you. Forms are another area in which PHP-generated code can save you time. You can also use PHP to produce "breadcrumbs" (there's one at the top of every slashdot page) and drop-down menus that show your users where in the hierarchy of information they are. Finally the author shows how to use apache's url_rewrite module to get those question marks, file extensions, and ampersands out of your URLS and sex them up. (You can also do this without url_rewrite, completely inside PHP, but using a custom error document and examining the path requested.)Chapter 10: Error Handling
So you're all excited about your next web app, and you dive into coding, and something goes wrong. What then? This chapter is about errors. You can use the error_reporting function to customize which exceptions actually produce error messages, or create your own error messages that handle errors your own way. You can choose to log them in a database, send an e-mail to a coding team, and most importantly, recover gracefully so that your users don't see an error message. Not only is it unprofessional, it may reveal information about your program, file system, or database structure that can harm you.Appendices
There are several good appendices, which tell you which configuration directives you're probably most interested in (the complete list you can get on PHP's web site), some common security breaches, and how to install PEAR, PHP's version of CPAN. My favorite appendix is the "Hosting Provider Checklist," a great reference for evaluating whether kewlhosting.com is going to give you the freedom and support you need to make a great hosted web site.All in all, I liked this volume. Having read probably a dozen PHP books I wouldn't say it offers new information. But even though you know the plot, it's possible to enjoy a well-told story. See Volume II for heavier-duty ideas.
* My made-up calculus notation for "bang for your buck"
**Like this: http://books.slashdot.org/
In real life, Matthew Leingang is Preceptor in Mathematics at Harvard University. He promises to review any book sent to him for free, and sometimes actually does it. Slashdot welcomes readers' book reviews. To see your own review here, carefully read the book review guidelines, then visit the submission page. -
The PHP Anthology - Volume I, 'Foundations'
sympleko (Matt Leingang) writes "What a beautiful world anthology is. It comes from the Greek for a gathering of flowers, and in literature means a collection of works. Harry Fuecks, a very frequent contributor to the SitePoint community PHP forums, has gathered a bouquet of PHP best practices in a new book. The book comes in two volumes. The audience for Volume I, "Foundations," is the advanced beginner who's done one or two things in PHP, but you wants to know how to do more. Volume II, "Applications," is a design volume, mainly, and is good for people who have lots of experience with PHP but want to be better programmers. It's nice that the two volumes are separate; if you already know the syntax and mechanics of PHP you can buy Volume II and maximize d!/d$.*" Read on for Leingang's review of Volume I, and watch for his followup on Volume II. The PHP Anthology: Volume I: Foundations author Harry Fuecks pages 376 publisher SitePoint rating 7 reviewer Matthew Leingang ISBN 0957921853 summary Good start; for the real story read Volume II as well.The book is very well-written, often using a question-and-answer heading style that makes searching the table of contents easy. In the preface, we already meet the first cool aspect of the book: lots of links to sites in the form of footnotes.** Yes, most books of this genre include links to web sites, but this way makes a couple of things clear: first, that there are lot of references, so you have many places to jump to for more information, and it's a sleeker text flow: embedding URLs in dead text makes line breaking hard and detracts from the flow of the language. As you read a page, you can note, "OK, that's an online resource," and keep reading without having to stumble over an incomprehensible URL.
Each volume has numerous code examples, and they're all on the book's web page to save you from transcribing. The web site is the best place also to buy the books; they're generally not available in stores.
Chapter 1: PHP Basics
These are the foundations of the book. Quick highlights:How does one exactly RTFM? The author directs the novice to the PHP web site and explains what each part of the online manual corresponds to. But also, the coolest aspect of the PHP web site is its search-by-url feature. It looks up a function or language reference page, finds a set of likely matches, or just googles the site for you. Try it: http://php.net/array, http://php.net/sprintf, http://php.net/error.
How to understand error messages. Remember your first "cannot add header information -- headers already sent" error. Huh? Learn the difference between parse errors (what you wrote is not valid code), semantic errors (you're asking PHP to do something illegal), environment errors (PHP is not equipped to do what you want), and logic errors (PHP is happy but you're not). The last is particularly insidious (no E_PEBKAC level of reporting), but unit testing (see Volume II) gives you hope to find and fix those.
How to include. What is the difference between include and require (answer: require forces a fatal error if it can't find the file you want, while include only warns)?
How to write portable and reusable code There are hundreds of configuration directives, and using them can make one of your applications simpler. But some are to be used only with careful consideration. The magic_quotes_gpc directive, for instance, sounded like a good idea at the time it was developed. It automatically escapes user input so backslashes remain backslashes and not escape characters. A common use of this directive allowed you to insert user-supplied data directly into a database without checking to make sure any embedded quotes wouldn't create unintended SQL statements. While this does guard against SQL injection attacks, you could still end up with garbage in the database. So you still have to check user data to make sure it complies to your standards. This is easier to do before escaping magic characters, so it's better to wait until just before storage; then add all the backslashes you need. Nowadays it's considered good form to not rely on this directive and just use addslashes when you need it.
For maximal code reuse, consider object orientation. But there's a whole chapter on that...
Chapter 2: Object Oriented PHP
"Be lazy," the author writes; "Write good code." One of the ways to organize your code is through object-oriented programming. Most readers know the basic concepts of OOP, and are probably tired of the few over-simplified examples. Beyond that this chapter wants to get you to think OO, to "no longer think about long lists of tasks that a single script should accomplish; instead, [to] see programming as the putting together of a set of tools to which your script will delegate work."I know my first PHP classes were just namespaced scripts. The attributes and methods weren't at all related. This chapter (as well as Chapter 7 of Volume II) helps you distinguish where your classes are and how they connect. One of the aids for this is the use of Unified Modeling Language (UML) class diagrams. These diagrams, which use boxes for classes and arrows for the relationships between them, are really cool programming and teaching tools that require no code!
Here I think the book's physical workflow got caught in a gap between major PHP releases. The cover says this book says "PHP5 ready," which is a bit of a misnomer because all the code examples and rules are all written for PHP4. Minor text mentioning how things are going to be different in PHP5 has been inserted. It's true that none of the OO code written here will break in PHP5, but there are major additions to PHP5 especially in the OO implementation (no more ampersands! actual private variables! Exceptions! Much, much more!). Still, the author makes the point that you the programmer may not be using PHP5 for a while (PHP 5.0.0 is only a few weeks old today), and that you shouldn't put off learning PHP until version 5 is agreed to be stable.
I've read the comments of PHP bashers, arguing that using it for OO programming is a waste of overhead. The author has heard that argument, too, and rebuts:
"What they forget to mention is the drastic increase in your performance that object oriented programming delivers. After all, fast programmers cost more than fast microprocessors!"
Hear, hear. RAM and disk space are commodities, while programmers are not (yet).
Chapter 3: PHP and MySQL
This goes beyond the simple HOWTO on connecting to a database. A suite of PHP classes is developed for database connections, querying, and result handling, not as much to use as for your "health"--i.e., to see a well-done class from start to finish. For your real applications, use a real, well-maintained and tested class such as those found in PEAR. This is another principle of good programming: Somebody has probably had the same problem you are having right now, and already solved it (also known as Ecclesiastes 1:9, "...there is nothing new under the sun.")If you've done lots of SQL queries, you get to thinking that there's got to be a better way to access a database. In fact, you can build a layer of abstraction over the database connection layer to create interface classes to individual tables. This is called a persistence layer. For an implementation, see PEAR::DB_DataObject.
Any web programmer fears insecurity, and I don't mean self-doubt. The author weaves discussions of security into each chapter. For instance, you must be careful to guard against allowing users to seriously alter the nature of your SQL queries. Trust no user-supplied data! Also, this chapter gives a PHP-based solution for creating MySQL dumps.
Once you've got the data in the database, making sure users can find it is another problem. You can use LIKE relations in your queries to search field strings. The author shows how to use FULLTEXT indexes (a MySQL 4 feature) to assist in searching the entire table or any set of fields you like, all at once.
Chapter 4: Files
Sometimes databases are overkill for data storage, or you need to extract data from text files. The author gives several examples of uses of interacting with a local or remote file system. He explains:- how to slurp whole files into memory or to process them chunk-by-chunk.
- how to use the PHP built-in functions to interface with the file system (so you can make a self-updating "Last updated: " item on your pages).
- how to use .ini-style files to store configuration data -- a common configuration style which is much faster than keeping it in a RDBMS or XML file.
- how to use FTP with PHP.
- how to compress and decompress with tar through PHP.
- how to send create a file and send it to your web user (custom files generated on-the-fly and ready for download!).
Again, the security threat is raised, and the author gives pointers on how to prevent from crackers getting you to execute their code by including one of their files rather than your own.
Chapter 5: Text Manipulation
When building dynamic web sites, being able to manipulate code is a must. You need to validate the data that users send to you, as well as guard against simple HTML error or malicious cross-site scripting (XSS) attacks. There are lots of built in functions (strip_tags to remove the HTML from a string), but using regular expressions you can validate and filter just about anything. You can reimplement a restricted set of markup tags a la BBCode, or set up a custom, easily-updated profanity filter.Chapter 6: Dates and Times
Another real-world problem is formatting dates and times in a human-readable (and perhaps localizeable) way, and on the machine level manipulating dates correctly. Luckily these are all solved problems and PHP connects you to the C functions which do it. Whether you store dates as MySQL timestamps (e.g., 2004-08-03 20:07:00) or UNIX timestamps (1091578114 seconds since the epoch) is up to you, although if you use the former you'll probably have to convert to the latter at some point. Putting it all together you can create dynamic calendars where clicking on a day brings you to your appointments for that day. Another good use of date functions is a implementation of cron written entirely in PHP for those not on a unix platform.Chapter 7: Images
Once you've mastered the art of producing HTML with PHP (developed even further in Chapter 9), you'll wonder what else can do. It turns out that PHP, using glue to the GD image library, can output images as well. You can generate thumbnails of your images to create galleries. You can watermark images with text to discourage stealing them. You can hide your images behind a PHP script that protects people other than you from linking directly to your images. And you can analyze data with enough charts and graphs to make Ross Perot ecstatic.Chapter 8: Email
Contacting your users off-site is a must if you want them to come back. Furthermore, it's a nice way to register users by sending them links to an address they provide. PHP can send email natively using the mail function, but as always there are nice classes which jazz up the features. You can send HTML attachments (known by some as "spam", but we're not here to judge), even including the images in the mail. You can even use PHP as a replacement for procmail by parsing incoming mail and triggering actions based on headers.Chapter 9: Web Page Elements
Eventually you get tired of writing HTML, and interweaving markup and presentation logic can give you a headache. Can't PHP be told to format the table the right way? Another solved problem! Displaying data in a table is a common task, and classes such as PEAR::HTML_Table can take a simple data structure and beautify it for you. Forms are another area in which PHP-generated code can save you time. You can also use PHP to produce "breadcrumbs" (there's one at the top of every slashdot page) and drop-down menus that show your users where in the hierarchy of information they are. Finally the author shows how to use apache's url_rewrite module to get those question marks, file extensions, and ampersands out of your URLS and sex them up. (You can also do this without url_rewrite, completely inside PHP, but using a custom error document and examining the path requested.)Chapter 10: Error Handling
So you're all excited about your next web app, and you dive into coding, and something goes wrong. What then? This chapter is about errors. You can use the error_reporting function to customize which exceptions actually produce error messages, or create your own error messages that handle errors your own way. You can choose to log them in a database, send an e-mail to a coding team, and most importantly, recover gracefully so that your users don't see an error message. Not only is it unprofessional, it may reveal information about your program, file system, or database structure that can harm you.Appendices
There are several good appendices, which tell you which configuration directives you're probably most interested in (the complete list you can get on PHP's web site), some common security breaches, and how to install PEAR, PHP's version of CPAN. My favorite appendix is the "Hosting Provider Checklist," a great reference for evaluating whether kewlhosting.com is going to give you the freedom and support you need to make a great hosted web site.All in all, I liked this volume. Having read probably a dozen PHP books I wouldn't say it offers new information. But even though you know the plot, it's possible to enjoy a well-told story. See Volume II for heavier-duty ideas.
* My made-up calculus notation for "bang for your buck"
**Like this: http://books.slashdot.org/
In real life, Matthew Leingang is Preceptor in Mathematics at Harvard University. He promises to review any book sent to him for free, and sometimes actually does it. Slashdot welcomes readers' book reviews. To see your own review here, carefully read the book review guidelines, then visit the submission page. -
The PHP Anthology - Volume I, 'Foundations'
sympleko (Matt Leingang) writes "What a beautiful world anthology is. It comes from the Greek for a gathering of flowers, and in literature means a collection of works. Harry Fuecks, a very frequent contributor to the SitePoint community PHP forums, has gathered a bouquet of PHP best practices in a new book. The book comes in two volumes. The audience for Volume I, "Foundations," is the advanced beginner who's done one or two things in PHP, but you wants to know how to do more. Volume II, "Applications," is a design volume, mainly, and is good for people who have lots of experience with PHP but want to be better programmers. It's nice that the two volumes are separate; if you already know the syntax and mechanics of PHP you can buy Volume II and maximize d!/d$.*" Read on for Leingang's review of Volume I, and watch for his followup on Volume II. The PHP Anthology: Volume I: Foundations author Harry Fuecks pages 376 publisher SitePoint rating 7 reviewer Matthew Leingang ISBN 0957921853 summary Good start; for the real story read Volume II as well.The book is very well-written, often using a question-and-answer heading style that makes searching the table of contents easy. In the preface, we already meet the first cool aspect of the book: lots of links to sites in the form of footnotes.** Yes, most books of this genre include links to web sites, but this way makes a couple of things clear: first, that there are lot of references, so you have many places to jump to for more information, and it's a sleeker text flow: embedding URLs in dead text makes line breaking hard and detracts from the flow of the language. As you read a page, you can note, "OK, that's an online resource," and keep reading without having to stumble over an incomprehensible URL.
Each volume has numerous code examples, and they're all on the book's web page to save you from transcribing. The web site is the best place also to buy the books; they're generally not available in stores.
Chapter 1: PHP Basics
These are the foundations of the book. Quick highlights:How does one exactly RTFM? The author directs the novice to the PHP web site and explains what each part of the online manual corresponds to. But also, the coolest aspect of the PHP web site is its search-by-url feature. It looks up a function or language reference page, finds a set of likely matches, or just googles the site for you. Try it: http://php.net/array, http://php.net/sprintf, http://php.net/error.
How to understand error messages. Remember your first "cannot add header information -- headers already sent" error. Huh? Learn the difference between parse errors (what you wrote is not valid code), semantic errors (you're asking PHP to do something illegal), environment errors (PHP is not equipped to do what you want), and logic errors (PHP is happy but you're not). The last is particularly insidious (no E_PEBKAC level of reporting), but unit testing (see Volume II) gives you hope to find and fix those.
How to include. What is the difference between include and require (answer: require forces a fatal error if it can't find the file you want, while include only warns)?
How to write portable and reusable code There are hundreds of configuration directives, and using them can make one of your applications simpler. But some are to be used only with careful consideration. The magic_quotes_gpc directive, for instance, sounded like a good idea at the time it was developed. It automatically escapes user input so backslashes remain backslashes and not escape characters. A common use of this directive allowed you to insert user-supplied data directly into a database without checking to make sure any embedded quotes wouldn't create unintended SQL statements. While this does guard against SQL injection attacks, you could still end up with garbage in the database. So you still have to check user data to make sure it complies to your standards. This is easier to do before escaping magic characters, so it's better to wait until just before storage; then add all the backslashes you need. Nowadays it's considered good form to not rely on this directive and just use addslashes when you need it.
For maximal code reuse, consider object orientation. But there's a whole chapter on that...
Chapter 2: Object Oriented PHP
"Be lazy," the author writes; "Write good code." One of the ways to organize your code is through object-oriented programming. Most readers know the basic concepts of OOP, and are probably tired of the few over-simplified examples. Beyond that this chapter wants to get you to think OO, to "no longer think about long lists of tasks that a single script should accomplish; instead, [to] see programming as the putting together of a set of tools to which your script will delegate work."I know my first PHP classes were just namespaced scripts. The attributes and methods weren't at all related. This chapter (as well as Chapter 7 of Volume II) helps you distinguish where your classes are and how they connect. One of the aids for this is the use of Unified Modeling Language (UML) class diagrams. These diagrams, which use boxes for classes and arrows for the relationships between them, are really cool programming and teaching tools that require no code!
Here I think the book's physical workflow got caught in a gap between major PHP releases. The cover says this book says "PHP5 ready," which is a bit of a misnomer because all the code examples and rules are all written for PHP4. Minor text mentioning how things are going to be different in PHP5 has been inserted. It's true that none of the OO code written here will break in PHP5, but there are major additions to PHP5 especially in the OO implementation (no more ampersands! actual private variables! Exceptions! Much, much more!). Still, the author makes the point that you the programmer may not be using PHP5 for a while (PHP 5.0.0 is only a few weeks old today), and that you shouldn't put off learning PHP until version 5 is agreed to be stable.
I've read the comments of PHP bashers, arguing that using it for OO programming is a waste of overhead. The author has heard that argument, too, and rebuts:
"What they forget to mention is the drastic increase in your performance that object oriented programming delivers. After all, fast programmers cost more than fast microprocessors!"
Hear, hear. RAM and disk space are commodities, while programmers are not (yet).
Chapter 3: PHP and MySQL
This goes beyond the simple HOWTO on connecting to a database. A suite of PHP classes is developed for database connections, querying, and result handling, not as much to use as for your "health"--i.e., to see a well-done class from start to finish. For your real applications, use a real, well-maintained and tested class such as those found in PEAR. This is another principle of good programming: Somebody has probably had the same problem you are having right now, and already solved it (also known as Ecclesiastes 1:9, "...there is nothing new under the sun.")If you've done lots of SQL queries, you get to thinking that there's got to be a better way to access a database. In fact, you can build a layer of abstraction over the database connection layer to create interface classes to individual tables. This is called a persistence layer. For an implementation, see PEAR::DB_DataObject.
Any web programmer fears insecurity, and I don't mean self-doubt. The author weaves discussions of security into each chapter. For instance, you must be careful to guard against allowing users to seriously alter the nature of your SQL queries. Trust no user-supplied data! Also, this chapter gives a PHP-based solution for creating MySQL dumps.
Once you've got the data in the database, making sure users can find it is another problem. You can use LIKE relations in your queries to search field strings. The author shows how to use FULLTEXT indexes (a MySQL 4 feature) to assist in searching the entire table or any set of fields you like, all at once.
Chapter 4: Files
Sometimes databases are overkill for data storage, or you need to extract data from text files. The author gives several examples of uses of interacting with a local or remote file system. He explains:- how to slurp whole files into memory or to process them chunk-by-chunk.
- how to use the PHP built-in functions to interface with the file system (so you can make a self-updating "Last updated: " item on your pages).
- how to use .ini-style files to store configuration data -- a common configuration style which is much faster than keeping it in a RDBMS or XML file.
- how to use FTP with PHP.
- how to compress and decompress with tar through PHP.
- how to send create a file and send it to your web user (custom files generated on-the-fly and ready for download!).
Again, the security threat is raised, and the author gives pointers on how to prevent from crackers getting you to execute their code by including one of their files rather than your own.
Chapter 5: Text Manipulation
When building dynamic web sites, being able to manipulate code is a must. You need to validate the data that users send to you, as well as guard against simple HTML error or malicious cross-site scripting (XSS) attacks. There are lots of built in functions (strip_tags to remove the HTML from a string), but using regular expressions you can validate and filter just about anything. You can reimplement a restricted set of markup tags a la BBCode, or set up a custom, easily-updated profanity filter.Chapter 6: Dates and Times
Another real-world problem is formatting dates and times in a human-readable (and perhaps localizeable) way, and on the machine level manipulating dates correctly. Luckily these are all solved problems and PHP connects you to the C functions which do it. Whether you store dates as MySQL timestamps (e.g., 2004-08-03 20:07:00) or UNIX timestamps (1091578114 seconds since the epoch) is up to you, although if you use the former you'll probably have to convert to the latter at some point. Putting it all together you can create dynamic calendars where clicking on a day brings you to your appointments for that day. Another good use of date functions is a implementation of cron written entirely in PHP for those not on a unix platform.Chapter 7: Images
Once you've mastered the art of producing HTML with PHP (developed even further in Chapter 9), you'll wonder what else can do. It turns out that PHP, using glue to the GD image library, can output images as well. You can generate thumbnails of your images to create galleries. You can watermark images with text to discourage stealing them. You can hide your images behind a PHP script that protects people other than you from linking directly to your images. And you can analyze data with enough charts and graphs to make Ross Perot ecstatic.Chapter 8: Email
Contacting your users off-site is a must if you want them to come back. Furthermore, it's a nice way to register users by sending them links to an address they provide. PHP can send email natively using the mail function, but as always there are nice classes which jazz up the features. You can send HTML attachments (known by some as "spam", but we're not here to judge), even including the images in the mail. You can even use PHP as a replacement for procmail by parsing incoming mail and triggering actions based on headers.Chapter 9: Web Page Elements
Eventually you get tired of writing HTML, and interweaving markup and presentation logic can give you a headache. Can't PHP be told to format the table the right way? Another solved problem! Displaying data in a table is a common task, and classes such as PEAR::HTML_Table can take a simple data structure and beautify it for you. Forms are another area in which PHP-generated code can save you time. You can also use PHP to produce "breadcrumbs" (there's one at the top of every slashdot page) and drop-down menus that show your users where in the hierarchy of information they are. Finally the author shows how to use apache's url_rewrite module to get those question marks, file extensions, and ampersands out of your URLS and sex them up. (You can also do this without url_rewrite, completely inside PHP, but using a custom error document and examining the path requested.)Chapter 10: Error Handling
So you're all excited about your next web app, and you dive into coding, and something goes wrong. What then? This chapter is about errors. You can use the error_reporting function to customize which exceptions actually produce error messages, or create your own error messages that handle errors your own way. You can choose to log them in a database, send an e-mail to a coding team, and most importantly, recover gracefully so that your users don't see an error message. Not only is it unprofessional, it may reveal information about your program, file system, or database structure that can harm you.Appendices
There are several good appendices, which tell you which configuration directives you're probably most interested in (the complete list you can get on PHP's web site), some common security breaches, and how to install PEAR, PHP's version of CPAN. My favorite appendix is the "Hosting Provider Checklist," a great reference for evaluating whether kewlhosting.com is going to give you the freedom and support you need to make a great hosted web site.All in all, I liked this volume. Having read probably a dozen PHP books I wouldn't say it offers new information. But even though you know the plot, it's possible to enjoy a well-told story. See Volume II for heavier-duty ideas.
* My made-up calculus notation for "bang for your buck"
**Like this: http://books.slashdot.org/
In real life, Matthew Leingang is Preceptor in Mathematics at Harvard University. He promises to review any book sent to him for free, and sometimes actually does it. Slashdot welcomes readers' book reviews. To see your own review here, carefully read the book review guidelines, then visit the submission page. -
The PHP Anthology - Volume I, 'Foundations'
sympleko (Matt Leingang) writes "What a beautiful world anthology is. It comes from the Greek for a gathering of flowers, and in literature means a collection of works. Harry Fuecks, a very frequent contributor to the SitePoint community PHP forums, has gathered a bouquet of PHP best practices in a new book. The book comes in two volumes. The audience for Volume I, "Foundations," is the advanced beginner who's done one or two things in PHP, but you wants to know how to do more. Volume II, "Applications," is a design volume, mainly, and is good for people who have lots of experience with PHP but want to be better programmers. It's nice that the two volumes are separate; if you already know the syntax and mechanics of PHP you can buy Volume II and maximize d!/d$.*" Read on for Leingang's review of Volume I, and watch for his followup on Volume II. The PHP Anthology: Volume I: Foundations author Harry Fuecks pages 376 publisher SitePoint rating 7 reviewer Matthew Leingang ISBN 0957921853 summary Good start; for the real story read Volume II as well.The book is very well-written, often using a question-and-answer heading style that makes searching the table of contents easy. In the preface, we already meet the first cool aspect of the book: lots of links to sites in the form of footnotes.** Yes, most books of this genre include links to web sites, but this way makes a couple of things clear: first, that there are lot of references, so you have many places to jump to for more information, and it's a sleeker text flow: embedding URLs in dead text makes line breaking hard and detracts from the flow of the language. As you read a page, you can note, "OK, that's an online resource," and keep reading without having to stumble over an incomprehensible URL.
Each volume has numerous code examples, and they're all on the book's web page to save you from transcribing. The web site is the best place also to buy the books; they're generally not available in stores.
Chapter 1: PHP Basics
These are the foundations of the book. Quick highlights:How does one exactly RTFM? The author directs the novice to the PHP web site and explains what each part of the online manual corresponds to. But also, the coolest aspect of the PHP web site is its search-by-url feature. It looks up a function or language reference page, finds a set of likely matches, or just googles the site for you. Try it: http://php.net/array, http://php.net/sprintf, http://php.net/error.
How to understand error messages. Remember your first "cannot add header information -- headers already sent" error. Huh? Learn the difference between parse errors (what you wrote is not valid code), semantic errors (you're asking PHP to do something illegal), environment errors (PHP is not equipped to do what you want), and logic errors (PHP is happy but you're not). The last is particularly insidious (no E_PEBKAC level of reporting), but unit testing (see Volume II) gives you hope to find and fix those.
How to include. What is the difference between include and require (answer: require forces a fatal error if it can't find the file you want, while include only warns)?
How to write portable and reusable code There are hundreds of configuration directives, and using them can make one of your applications simpler. But some are to be used only with careful consideration. The magic_quotes_gpc directive, for instance, sounded like a good idea at the time it was developed. It automatically escapes user input so backslashes remain backslashes and not escape characters. A common use of this directive allowed you to insert user-supplied data directly into a database without checking to make sure any embedded quotes wouldn't create unintended SQL statements. While this does guard against SQL injection attacks, you could still end up with garbage in the database. So you still have to check user data to make sure it complies to your standards. This is easier to do before escaping magic characters, so it's better to wait until just before storage; then add all the backslashes you need. Nowadays it's considered good form to not rely on this directive and just use addslashes when you need it.
For maximal code reuse, consider object orientation. But there's a whole chapter on that...
Chapter 2: Object Oriented PHP
"Be lazy," the author writes; "Write good code." One of the ways to organize your code is through object-oriented programming. Most readers know the basic concepts of OOP, and are probably tired of the few over-simplified examples. Beyond that this chapter wants to get you to think OO, to "no longer think about long lists of tasks that a single script should accomplish; instead, [to] see programming as the putting together of a set of tools to which your script will delegate work."I know my first PHP classes were just namespaced scripts. The attributes and methods weren't at all related. This chapter (as well as Chapter 7 of Volume II) helps you distinguish where your classes are and how they connect. One of the aids for this is the use of Unified Modeling Language (UML) class diagrams. These diagrams, which use boxes for classes and arrows for the relationships between them, are really cool programming and teaching tools that require no code!
Here I think the book's physical workflow got caught in a gap between major PHP releases. The cover says this book says "PHP5 ready," which is a bit of a misnomer because all the code examples and rules are all written for PHP4. Minor text mentioning how things are going to be different in PHP5 has been inserted. It's true that none of the OO code written here will break in PHP5, but there are major additions to PHP5 especially in the OO implementation (no more ampersands! actual private variables! Exceptions! Much, much more!). Still, the author makes the point that you the programmer may not be using PHP5 for a while (PHP 5.0.0 is only a few weeks old today), and that you shouldn't put off learning PHP until version 5 is agreed to be stable.
I've read the comments of PHP bashers, arguing that using it for OO programming is a waste of overhead. The author has heard that argument, too, and rebuts:
"What they forget to mention is the drastic increase in your performance that object oriented programming delivers. After all, fast programmers cost more than fast microprocessors!"
Hear, hear. RAM and disk space are commodities, while programmers are not (yet).
Chapter 3: PHP and MySQL
This goes beyond the simple HOWTO on connecting to a database. A suite of PHP classes is developed for database connections, querying, and result handling, not as much to use as for your "health"--i.e., to see a well-done class from start to finish. For your real applications, use a real, well-maintained and tested class such as those found in PEAR. This is another principle of good programming: Somebody has probably had the same problem you are having right now, and already solved it (also known as Ecclesiastes 1:9, "...there is nothing new under the sun.")If you've done lots of SQL queries, you get to thinking that there's got to be a better way to access a database. In fact, you can build a layer of abstraction over the database connection layer to create interface classes to individual tables. This is called a persistence layer. For an implementation, see PEAR::DB_DataObject.
Any web programmer fears insecurity, and I don't mean self-doubt. The author weaves discussions of security into each chapter. For instance, you must be careful to guard against allowing users to seriously alter the nature of your SQL queries. Trust no user-supplied data! Also, this chapter gives a PHP-based solution for creating MySQL dumps.
Once you've got the data in the database, making sure users can find it is another problem. You can use LIKE relations in your queries to search field strings. The author shows how to use FULLTEXT indexes (a MySQL 4 feature) to assist in searching the entire table or any set of fields you like, all at once.
Chapter 4: Files
Sometimes databases are overkill for data storage, or you need to extract data from text files. The author gives several examples of uses of interacting with a local or remote file system. He explains:- how to slurp whole files into memory or to process them chunk-by-chunk.
- how to use the PHP built-in functions to interface with the file system (so you can make a self-updating "Last updated: " item on your pages).
- how to use .ini-style files to store configuration data -- a common configuration style which is much faster than keeping it in a RDBMS or XML file.
- how to use FTP with PHP.
- how to compress and decompress with tar through PHP.
- how to send create a file and send it to your web user (custom files generated on-the-fly and ready for download!).
Again, the security threat is raised, and the author gives pointers on how to prevent from crackers getting you to execute their code by including one of their files rather than your own.
Chapter 5: Text Manipulation
When building dynamic web sites, being able to manipulate code is a must. You need to validate the data that users send to you, as well as guard against simple HTML error or malicious cross-site scripting (XSS) attacks. There are lots of built in functions (strip_tags to remove the HTML from a string), but using regular expressions you can validate and filter just about anything. You can reimplement a restricted set of markup tags a la BBCode, or set up a custom, easily-updated profanity filter.Chapter 6: Dates and Times
Another real-world problem is formatting dates and times in a human-readable (and perhaps localizeable) way, and on the machine level manipulating dates correctly. Luckily these are all solved problems and PHP connects you to the C functions which do it. Whether you store dates as MySQL timestamps (e.g., 2004-08-03 20:07:00) or UNIX timestamps (1091578114 seconds since the epoch) is up to you, although if you use the former you'll probably have to convert to the latter at some point. Putting it all together you can create dynamic calendars where clicking on a day brings you to your appointments for that day. Another good use of date functions is a implementation of cron written entirely in PHP for those not on a unix platform.Chapter 7: Images
Once you've mastered the art of producing HTML with PHP (developed even further in Chapter 9), you'll wonder what else can do. It turns out that PHP, using glue to the GD image library, can output images as well. You can generate thumbnails of your images to create galleries. You can watermark images with text to discourage stealing them. You can hide your images behind a PHP script that protects people other than you from linking directly to your images. And you can analyze data with enough charts and graphs to make Ross Perot ecstatic.Chapter 8: Email
Contacting your users off-site is a must if you want them to come back. Furthermore, it's a nice way to register users by sending them links to an address they provide. PHP can send email natively using the mail function, but as always there are nice classes which jazz up the features. You can send HTML attachments (known by some as "spam", but we're not here to judge), even including the images in the mail. You can even use PHP as a replacement for procmail by parsing incoming mail and triggering actions based on headers.Chapter 9: Web Page Elements
Eventually you get tired of writing HTML, and interweaving markup and presentation logic can give you a headache. Can't PHP be told to format the table the right way? Another solved problem! Displaying data in a table is a common task, and classes such as PEAR::HTML_Table can take a simple data structure and beautify it for you. Forms are another area in which PHP-generated code can save you time. You can also use PHP to produce "breadcrumbs" (there's one at the top of every slashdot page) and drop-down menus that show your users where in the hierarchy of information they are. Finally the author shows how to use apache's url_rewrite module to get those question marks, file extensions, and ampersands out of your URLS and sex them up. (You can also do this without url_rewrite, completely inside PHP, but using a custom error document and examining the path requested.)Chapter 10: Error Handling
So you're all excited about your next web app, and you dive into coding, and something goes wrong. What then? This chapter is about errors. You can use the error_reporting function to customize which exceptions actually produce error messages, or create your own error messages that handle errors your own way. You can choose to log them in a database, send an e-mail to a coding team, and most importantly, recover gracefully so that your users don't see an error message. Not only is it unprofessional, it may reveal information about your program, file system, or database structure that can harm you.Appendices
There are several good appendices, which tell you which configuration directives you're probably most interested in (the complete list you can get on PHP's web site), some common security breaches, and how to install PEAR, PHP's version of CPAN. My favorite appendix is the "Hosting Provider Checklist," a great reference for evaluating whether kewlhosting.com is going to give you the freedom and support you need to make a great hosted web site.All in all, I liked this volume. Having read probably a dozen PHP books I wouldn't say it offers new information. But even though you know the plot, it's possible to enjoy a well-told story. See Volume II for heavier-duty ideas.
* My made-up calculus notation for "bang for your buck"
**Like this: http://books.slashdot.org/
In real life, Matthew Leingang is Preceptor in Mathematics at Harvard University. He promises to review any book sent to him for free, and sometimes actually does it. Slashdot welcomes readers' book reviews. To see your own review here, carefully read the book review guidelines, then visit the submission page. -
The PHP Anthology - Volume I, 'Foundations'
sympleko (Matt Leingang) writes "What a beautiful world anthology is. It comes from the Greek for a gathering of flowers, and in literature means a collection of works. Harry Fuecks, a very frequent contributor to the SitePoint community PHP forums, has gathered a bouquet of PHP best practices in a new book. The book comes in two volumes. The audience for Volume I, "Foundations," is the advanced beginner who's done one or two things in PHP, but you wants to know how to do more. Volume II, "Applications," is a design volume, mainly, and is good for people who have lots of experience with PHP but want to be better programmers. It's nice that the two volumes are separate; if you already know the syntax and mechanics of PHP you can buy Volume II and maximize d!/d$.*" Read on for Leingang's review of Volume I, and watch for his followup on Volume II. The PHP Anthology: Volume I: Foundations author Harry Fuecks pages 376 publisher SitePoint rating 7 reviewer Matthew Leingang ISBN 0957921853 summary Good start; for the real story read Volume II as well.The book is very well-written, often using a question-and-answer heading style that makes searching the table of contents easy. In the preface, we already meet the first cool aspect of the book: lots of links to sites in the form of footnotes.** Yes, most books of this genre include links to web sites, but this way makes a couple of things clear: first, that there are lot of references, so you have many places to jump to for more information, and it's a sleeker text flow: embedding URLs in dead text makes line breaking hard and detracts from the flow of the language. As you read a page, you can note, "OK, that's an online resource," and keep reading without having to stumble over an incomprehensible URL.
Each volume has numerous code examples, and they're all on the book's web page to save you from transcribing. The web site is the best place also to buy the books; they're generally not available in stores.
Chapter 1: PHP Basics
These are the foundations of the book. Quick highlights:How does one exactly RTFM? The author directs the novice to the PHP web site and explains what each part of the online manual corresponds to. But also, the coolest aspect of the PHP web site is its search-by-url feature. It looks up a function or language reference page, finds a set of likely matches, or just googles the site for you. Try it: http://php.net/array, http://php.net/sprintf, http://php.net/error.
How to understand error messages. Remember your first "cannot add header information -- headers already sent" error. Huh? Learn the difference between parse errors (what you wrote is not valid code), semantic errors (you're asking PHP to do something illegal), environment errors (PHP is not equipped to do what you want), and logic errors (PHP is happy but you're not). The last is particularly insidious (no E_PEBKAC level of reporting), but unit testing (see Volume II) gives you hope to find and fix those.
How to include. What is the difference between include and require (answer: require forces a fatal error if it can't find the file you want, while include only warns)?
How to write portable and reusable code There are hundreds of configuration directives, and using them can make one of your applications simpler. But some are to be used only with careful consideration. The magic_quotes_gpc directive, for instance, sounded like a good idea at the time it was developed. It automatically escapes user input so backslashes remain backslashes and not escape characters. A common use of this directive allowed you to insert user-supplied data directly into a database without checking to make sure any embedded quotes wouldn't create unintended SQL statements. While this does guard against SQL injection attacks, you could still end up with garbage in the database. So you still have to check user data to make sure it complies to your standards. This is easier to do before escaping magic characters, so it's better to wait until just before storage; then add all the backslashes you need. Nowadays it's considered good form to not rely on this directive and just use addslashes when you need it.
For maximal code reuse, consider object orientation. But there's a whole chapter on that...
Chapter 2: Object Oriented PHP
"Be lazy," the author writes; "Write good code." One of the ways to organize your code is through object-oriented programming. Most readers know the basic concepts of OOP, and are probably tired of the few over-simplified examples. Beyond that this chapter wants to get you to think OO, to "no longer think about long lists of tasks that a single script should accomplish; instead, [to] see programming as the putting together of a set of tools to which your script will delegate work."I know my first PHP classes were just namespaced scripts. The attributes and methods weren't at all related. This chapter (as well as Chapter 7 of Volume II) helps you distinguish where your classes are and how they connect. One of the aids for this is the use of Unified Modeling Language (UML) class diagrams. These diagrams, which use boxes for classes and arrows for the relationships between them, are really cool programming and teaching tools that require no code!
Here I think the book's physical workflow got caught in a gap between major PHP releases. The cover says this book says "PHP5 ready," which is a bit of a misnomer because all the code examples and rules are all written for PHP4. Minor text mentioning how things are going to be different in PHP5 has been inserted. It's true that none of the OO code written here will break in PHP5, but there are major additions to PHP5 especially in the OO implementation (no more ampersands! actual private variables! Exceptions! Much, much more!). Still, the author makes the point that you the programmer may not be using PHP5 for a while (PHP 5.0.0 is only a few weeks old today), and that you shouldn't put off learning PHP until version 5 is agreed to be stable.
I've read the comments of PHP bashers, arguing that using it for OO programming is a waste of overhead. The author has heard that argument, too, and rebuts:
"What they forget to mention is the drastic increase in your performance that object oriented programming delivers. After all, fast programmers cost more than fast microprocessors!"
Hear, hear. RAM and disk space are commodities, while programmers are not (yet).
Chapter 3: PHP and MySQL
This goes beyond the simple HOWTO on connecting to a database. A suite of PHP classes is developed for database connections, querying, and result handling, not as much to use as for your "health"--i.e., to see a well-done class from start to finish. For your real applications, use a real, well-maintained and tested class such as those found in PEAR. This is another principle of good programming: Somebody has probably had the same problem you are having right now, and already solved it (also known as Ecclesiastes 1:9, "...there is nothing new under the sun.")If you've done lots of SQL queries, you get to thinking that there's got to be a better way to access a database. In fact, you can build a layer of abstraction over the database connection layer to create interface classes to individual tables. This is called a persistence layer. For an implementation, see PEAR::DB_DataObject.
Any web programmer fears insecurity, and I don't mean self-doubt. The author weaves discussions of security into each chapter. For instance, you must be careful to guard against allowing users to seriously alter the nature of your SQL queries. Trust no user-supplied data! Also, this chapter gives a PHP-based solution for creating MySQL dumps.
Once you've got the data in the database, making sure users can find it is another problem. You can use LIKE relations in your queries to search field strings. The author shows how to use FULLTEXT indexes (a MySQL 4 feature) to assist in searching the entire table or any set of fields you like, all at once.
Chapter 4: Files
Sometimes databases are overkill for data storage, or you need to extract data from text files. The author gives several examples of uses of interacting with a local or remote file system. He explains:- how to slurp whole files into memory or to process them chunk-by-chunk.
- how to use the PHP built-in functions to interface with the file system (so you can make a self-updating "Last updated: " item on your pages).
- how to use .ini-style files to store configuration data -- a common configuration style which is much faster than keeping it in a RDBMS or XML file.
- how to use FTP with PHP.
- how to compress and decompress with tar through PHP.
- how to send create a file and send it to your web user (custom files generated on-the-fly and ready for download!).
Again, the security threat is raised, and the author gives pointers on how to prevent from crackers getting you to execute their code by including one of their files rather than your own.
Chapter 5: Text Manipulation
When building dynamic web sites, being able to manipulate code is a must. You need to validate the data that users send to you, as well as guard against simple HTML error or malicious cross-site scripting (XSS) attacks. There are lots of built in functions (strip_tags to remove the HTML from a string), but using regular expressions you can validate and filter just about anything. You can reimplement a restricted set of markup tags a la BBCode, or set up a custom, easily-updated profanity filter.Chapter 6: Dates and Times
Another real-world problem is formatting dates and times in a human-readable (and perhaps localizeable) way, and on the machine level manipulating dates correctly. Luckily these are all solved problems and PHP connects you to the C functions which do it. Whether you store dates as MySQL timestamps (e.g., 2004-08-03 20:07:00) or UNIX timestamps (1091578114 seconds since the epoch) is up to you, although if you use the former you'll probably have to convert to the latter at some point. Putting it all together you can create dynamic calendars where clicking on a day brings you to your appointments for that day. Another good use of date functions is a implementation of cron written entirely in PHP for those not on a unix platform.Chapter 7: Images
Once you've mastered the art of producing HTML with PHP (developed even further in Chapter 9), you'll wonder what else can do. It turns out that PHP, using glue to the GD image library, can output images as well. You can generate thumbnails of your images to create galleries. You can watermark images with text to discourage stealing them. You can hide your images behind a PHP script that protects people other than you from linking directly to your images. And you can analyze data with enough charts and graphs to make Ross Perot ecstatic.Chapter 8: Email
Contacting your users off-site is a must if you want them to come back. Furthermore, it's a nice way to register users by sending them links to an address they provide. PHP can send email natively using the mail function, but as always there are nice classes which jazz up the features. You can send HTML attachments (known by some as "spam", but we're not here to judge), even including the images in the mail. You can even use PHP as a replacement for procmail by parsing incoming mail and triggering actions based on headers.Chapter 9: Web Page Elements
Eventually you get tired of writing HTML, and interweaving markup and presentation logic can give you a headache. Can't PHP be told to format the table the right way? Another solved problem! Displaying data in a table is a common task, and classes such as PEAR::HTML_Table can take a simple data structure and beautify it for you. Forms are another area in which PHP-generated code can save you time. You can also use PHP to produce "breadcrumbs" (there's one at the top of every slashdot page) and drop-down menus that show your users where in the hierarchy of information they are. Finally the author shows how to use apache's url_rewrite module to get those question marks, file extensions, and ampersands out of your URLS and sex them up. (You can also do this without url_rewrite, completely inside PHP, but using a custom error document and examining the path requested.)Chapter 10: Error Handling
So you're all excited about your next web app, and you dive into coding, and something goes wrong. What then? This chapter is about errors. You can use the error_reporting function to customize which exceptions actually produce error messages, or create your own error messages that handle errors your own way. You can choose to log them in a database, send an e-mail to a coding team, and most importantly, recover gracefully so that your users don't see an error message. Not only is it unprofessional, it may reveal information about your program, file system, or database structure that can harm you.Appendices
There are several good appendices, which tell you which configuration directives you're probably most interested in (the complete list you can get on PHP's web site), some common security breaches, and how to install PEAR, PHP's version of CPAN. My favorite appendix is the "Hosting Provider Checklist," a great reference for evaluating whether kewlhosting.com is going to give you the freedom and support you need to make a great hosted web site.All in all, I liked this volume. Having read probably a dozen PHP books I wouldn't say it offers new information. But even though you know the plot, it's possible to enjoy a well-told story. See Volume II for heavier-duty ideas.
* My made-up calculus notation for "bang for your buck"
**Like this: http://books.slashdot.org/
In real life, Matthew Leingang is Preceptor in Mathematics at Harvard University. He promises to review any book sent to him for free, and sometimes actually does it. Slashdot welcomes readers' book reviews. To see your own review here, carefully read the book review guidelines, then visit the submission page. -
PHP 5 Release Sparks Up PHP-GTK 2.0
joeldg writes "Since the release of PHP5 a lot of interest has reverberated down through the whole PHP community. In particular, there's a call for a PHP-GTK 2.0 which will utilize GTK2 and will have an entire rewrite of it from the ground up to make use of new features. Additionally there is an open call to help add to the documentation and to help with the website, post to and join the php-gtk-general mailing list to follow along with the activity. The forthcoming PHP-GTK version 2.0 will bind GTK+ 2 to PHP 5. Until then, PHP-GTK 1.0.0 works only with PHP 4." -
PHP 5 Release Sparks Up PHP-GTK 2.0
joeldg writes "Since the release of PHP5 a lot of interest has reverberated down through the whole PHP community. In particular, there's a call for a PHP-GTK 2.0 which will utilize GTK2 and will have an entire rewrite of it from the ground up to make use of new features. Additionally there is an open call to help add to the documentation and to help with the website, post to and join the php-gtk-general mailing list to follow along with the activity. The forthcoming PHP-GTK version 2.0 will bind GTK+ 2 to PHP 5. Until then, PHP-GTK 1.0.0 works only with PHP 4." -
PHP 5 Release Sparks Up PHP-GTK 2.0
joeldg writes "Since the release of PHP5 a lot of interest has reverberated down through the whole PHP community. In particular, there's a call for a PHP-GTK 2.0 which will utilize GTK2 and will have an entire rewrite of it from the ground up to make use of new features. Additionally there is an open call to help add to the documentation and to help with the website, post to and join the php-gtk-general mailing list to follow along with the activity. The forthcoming PHP-GTK version 2.0 will bind GTK+ 2 to PHP 5. Until then, PHP-GTK 1.0.0 works only with PHP 4." -
PHP 5.0 Goes For Microsoft's ASP-dot-Net
Dozix007 writes "Uberhacker.Com reports : Zend Technologies quietly announced last week the final release of the open source PHP version 5. An interesting article reports the different strengths and weaknesses of ASP vs. PHP, and it becomes quite clear that with the release of PHP5, Zend has taken a shot at ASP's heart. The differences from PHP4 to 5 has created a clear advantage for the new preprocessor over Microsoft's proprietery ASP." -
PHP 4.3.8 Released, Fixing Remote Security Hole
christian klink writes "While it was already reported on Slashdot, that PHP5 was released, it was not mentioned that the PHP developers have also announced the release of PHP 4.3.8 which is supposed to fix a major remote security hole in nearly all PHP installations. Additionally this new version adds a workaround for another Internet Explorer bug. The bugs were found by security specialist Stefan Esser of e-matters who is also a member of the PHP developers." -
PHP 5 Released; PHP Compiler, Too
TheTomcat writes "After years of anticipation, PHP 5 was released today. This release represents a milestone in the evolution of PHP. It sports the new Zend Engine II, a completely re-worked object model, and many many new features. Check it and the changelog out." In other PHP news, remote_bob writes "There have been many attempts, like BinaryPHP and PASM, but finally there is a complete compiler for PHP. The Roadsend compiler produces standalone, native executables, and supports the entire PHP language (but not all extensions). It uses Bigloo Scheme to do its job, a variant of Lisp, the language that Paul Graham writes about. Benchmarks say that performance is pretty good. Is this another sign that dynamic languages are the future?" -
PHP 5 Released; PHP Compiler, Too
TheTomcat writes "After years of anticipation, PHP 5 was released today. This release represents a milestone in the evolution of PHP. It sports the new Zend Engine II, a completely re-worked object model, and many many new features. Check it and the changelog out." In other PHP news, remote_bob writes "There have been many attempts, like BinaryPHP and PASM, but finally there is a complete compiler for PHP. The Roadsend compiler produces standalone, native executables, and supports the entire PHP language (but not all extensions). It uses Bigloo Scheme to do its job, a variant of Lisp, the language that Paul Graham writes about. Benchmarks say that performance is pretty good. Is this another sign that dynamic languages are the future?" -
PHP 5 Released; PHP Compiler, Too
TheTomcat writes "After years of anticipation, PHP 5 was released today. This release represents a milestone in the evolution of PHP. It sports the new Zend Engine II, a completely re-worked object model, and many many new features. Check it and the changelog out." In other PHP news, remote_bob writes "There have been many attempts, like BinaryPHP and PASM, but finally there is a complete compiler for PHP. The Roadsend compiler produces standalone, native executables, and supports the entire PHP language (but not all extensions). It uses Bigloo Scheme to do its job, a variant of Lisp, the language that Paul Graham writes about. Benchmarks say that performance is pretty good. Is this another sign that dynamic languages are the future?" -
PHP 5 Released; PHP Compiler, Too
TheTomcat writes "After years of anticipation, PHP 5 was released today. This release represents a milestone in the evolution of PHP. It sports the new Zend Engine II, a completely re-worked object model, and many many new features. Check it and the changelog out." In other PHP news, remote_bob writes "There have been many attempts, like BinaryPHP and PASM, but finally there is a complete compiler for PHP. The Roadsend compiler produces standalone, native executables, and supports the entire PHP language (but not all extensions). It uses Bigloo Scheme to do its job, a variant of Lisp, the language that Paul Graham writes about. Benchmarks say that performance is pretty good. Is this another sign that dynamic languages are the future?" -
phpstack - A TCP/IP Stack and Web Server in PHP
Adam Dunkels writes "Following the trend of writing 'inappropriate' programs in the PHP scripting language, I have written a small TCP/IP stack and a web server entirely in PHP. It is extremely stripped down: the IP stack only implements the most basic functionality required for running the web server and the web server cannot handle pages larger than 1.5k. Nevertheless, the stack is able to support an unlimited number of simultaneous TCP connections and the web server has support for PHP scripting. A live demonstration server is up and running the phpstack software." -
Ming + PHP5 + AI = Pretty
cyberscribe writes "Project K++ just released its first alpha version today. The project aims to explore computer-generated abstract art using PHP and Ming. The name of the project is an homage to Wassily Kandinsky, father of abstract art. Caution: the Flash movies can be intensive on your graphics card. Other caution: hitting reload to see the next cool computer-generated abstract 'painting' can be highly addictive." -
Hardened PHP
Frank Kreuzbach writes "Yesterday the Hardened-PHP Project has announced its existence on the PHP-general mailinglist. It is the first public patch for PHP which adds security hardening features. It is meant as a proactive approach to protect servers against known and unknown weaknesses within PHP scripts or the engine itself. It enforces restrictions on include statements, adds canary protection to allocated memory and other internal structures and protects against internal format string vulnerabilities. It has syslog support and logs every attack together with the originating ip." -
PHP and SQL Security
An anonymous reader writes "PHP and SQL Security are being proven more weak every day. Uberhacker.Com is running a PHP and SQL security research project to raise awareness of secure scripting. The site hosts guides to secure PHP programming, forums, and scripting challenges to see who can create the most secure scripts." -
PHP 5 Release Candidate 2 Released
alexre1 writes "From the PHP website: 'The second Release Candidate of PHP 5 is now available! This mostly bug fix release improves PHP 5's stability and irons out some of the remaining issues before PHP 5 can be deemed release quality. Note that it is still not recommended for mission-critical use but people are encouraged to start playing with it and report any problems.' Cool! Hopefully we'll have a stable PHP 5.0 soon." -
PHP 5 Release Candidate 2 Released
alexre1 writes "From the PHP website: 'The second Release Candidate of PHP 5 is now available! This mostly bug fix release improves PHP 5's stability and irons out some of the remaining issues before PHP 5 can be deemed release quality. Note that it is still not recommended for mission-critical use but people are encouraged to start playing with it and report any problems.' Cool! Hopefully we'll have a stable PHP 5.0 soon." -
PHP 4.3.6 Released
ehmdjii writes "The PHP Development Team is proud to announce the release of PHP 4.3.6. This is is a bug fix release whose primary goal is to address two bugs which may result in crashes in PHP builds with thread-safety enabled. All users of PHP in a threaded environment (Windows) are strongly encouraged to upgrade to this release. All in all this release fixes approximately 25 bugs that have been discovered since the 4.3.5 release. For a full list of changes in PHP 4.3.6, see the ChangeLog." -
PHP 4.3.6 Released
ehmdjii writes "The PHP Development Team is proud to announce the release of PHP 4.3.6. This is is a bug fix release whose primary goal is to address two bugs which may result in crashes in PHP builds with thread-safety enabled. All users of PHP in a threaded environment (Windows) are strongly encouraged to upgrade to this release. All in all this release fixes approximately 25 bugs that have been discovered since the 4.3.5 release. For a full list of changes in PHP 4.3.6, see the ChangeLog." -
PHP 4.3.6 Released
ehmdjii writes "The PHP Development Team is proud to announce the release of PHP 4.3.6. This is is a bug fix release whose primary goal is to address two bugs which may result in crashes in PHP builds with thread-safety enabled. All users of PHP in a threaded environment (Windows) are strongly encouraged to upgrade to this release. All in all this release fixes approximately 25 bugs that have been discovered since the 4.3.5 release. For a full list of changes in PHP 4.3.6, see the ChangeLog." -
PHP Template Engines?
kubed asks: "I've recently learned how to use PHP template engines to separate business logic from presentation. Some argue that template engines make applications easier to maintain and make for cleaner code. Others argue that template engines introduce unnecessary overhead and require too much additional processing power. Do the readers of Slashdot think that it is important to use templates or are they just an extra unnecessary layer? There are dozens of PHP template engines to choose from including Smarty, phplib, and bTemplate. Which template engines do you have experience with and which ones have the best performance?" -
Apache 1.3.x vs. 2.0.x: The Debate Returns
darthcamaro writes "internetnews.com is running a story about the new Apache 2.0.49 release. They actually got a hold of a pair of Apache Software Foundation members and got them to speak out about the 1.3.x vs. 2.0.49 debate! Also Apache Director Sander Striker told internetnews.com that he expects the Apache 1.3.30 release cycle to begin this week... I still use 1.3.x because I've been using the Apache 1.x series 'forever' and I've never found a solid reason to change. Also, as pointed out in this article, the official PHP documentation clearly states, 'Do not use Apache 2.0 and PHP in a production environment neither on Unix nor on Windows.'"