By Rasmus Lerdorf, Peter MacIntyre, Kevin Tatroe .... With style tips and practical programming advice, this book will help you become not just a PHP --Chapters that show you how to gene
Trang 1By Rasmus Lerdorf, Peter MacIntyre, Kevin Tatroe
Publisher: O'Reilly Pub Date: April 2006 Print ISBN-10: 0-596-00681-0 Print ISBN-13: 978-0-59-600681-5 Pages: 540
Table of Contents | Index
Programming PHP, Second Edition is the authoritative guide to PHP 5 and is filled with the
unique knowledge of the creator of PHP (Rasmus Lerdorf) and other PHP experts When it comes to creating web sites, the PHP scripting language is truly a red-hot property In fact, PHP is currently used on more than 19 million web sites, surpassing Microsoft's ASP NET technology in popularity Programmers love its flexibility and speed; designers love its accessibility and convenience.
As the industry standard book on PHP, all of the essentials are covered in a clear and concise manner Language syntax and programming techniques are coupled with
numerous examples that illustrate both correct usage and common idioms With style tips and practical programming advice, this book will help you become not just a PHP
Chapters that show you how to generate dynamic images, create PDF files, and parse XML files with PHP
Trang 2Advanced topics, such as creating secure scripts, error handling, performance tuning, and writing your own C language extensions to PHP
of PHP's strengths."
David Dooling, Slashdot.org
Trang 3By Rasmus Lerdorf, Peter MacIntyre, Kevin Tatroe
Publisher: O'Reilly Pub Date: April 2006 Print ISBN-10: 0-596-00681-0 Print ISBN-13: 978-0-59-600681-5 Pages: 540
Trang 7by Rasmus Lerdorf, Kevin Tatroe, and Peter MacIntyre
Copyright © 2006, 2002 O'Reilly Media, Inc All rights reserved.Printed in the United States of America
Published by O'Reilly Media, Inc., 1005 Gravenstein HighwayNorth, Sebastopol, CA 95472
O'Reilly books may be purchased for educational, business, orsales promotional use Online editions are also available for
most titles (safari.oreilly.com) For more information, contactour corporate/institutional sales department: (800) 998-9938 orcorporate@oreilly.com
Trang 8ISBN: 0-596-00681-0
[M]
Trang 9Today, PHP is the most widely used programming language onthe Web, with over 40 percent of all web applications written inPHP It is installed on over 22 million domain servers (source:Netcraft), as shown in Figure F-1 The number of developersusing PHP has now reached over 2.5 million The communitydeveloping PHP is very impressive, with over 450 CVS
committers who wrote a total of 1 million lines of code The PHPcommunity is one of the most dynamic, with thousands of
people sharing code, evangelizing about PHP, supporting eachother, and creating many projects such as Wikipedia, Mambo,PHP-Nuke, FUDforum, SugarCRM, and Horde, just to mention afew
Figure F-1 PHP development timeline with usage
Its simplicity is what made PHP so successful Simplicity equalsless code Developers and companies have been developing
Trang 10There is an unacknowledged war that goes on every day
in the world of programming It is a war between the
humans and the computer scientists It is a war betweenthose who want simple, sloppy, flexible, human ways to
write code and those who want clean, crisp, clear, correctways to write code It is the war between PHP and
C++/Java
Adam Bosworth
The future of PHP looks very bright Leading platform vendorssuch as IBM, Oracle, MySQL, Intel, and, most recently, Red Hathave all endorsed it The new Collaboration Project initiated byZend Technologies rallies many leading companies and
community members around new open source initiatives aimed
at taking PHP to the next level by creating an industrial-grade,
de facto standard PHP web application development and
deployment environment The Project's first two open initiativesare:
Zend PHP Framework
This is a web application framework that will accelerate andimprove the development and deployment of mission-
critical PHP web applications
Support for the Eclipse Development platform
Zend is joining the Eclipse Foundation as a Strategic
Developer It will develop, in collaboration with partners, a
Trang 11Rasmus Lerdorf, the initial creator of the first version of PHP(then called PHP/FI), and Kevin Tatroe provided the guidelinesfor this book The newest author on the revision project is PeterMacIntyre, a Zend Certified Engineer with more than five yearsexperience in PHP Wez Furlong and Chris Shiflett have alsocontributed to this book Wez modernized the "Extending PHP"chapter, and Chris brought his renowned expertise in updatingthe "Security" chapter
This book is a must-have for anybody working with PHP Some
of the most recognizable names in the PHP community havecontributed to it So you know that you are getting quality
Trang 12Now more than ever, the Web is a major vehicle for corporateand personal communications Web sites carry satellite images
of Earth in its entirety, search for life in outer space, and housepersonal photo albums, business shopping carts, and productlists Many of those web sites are driven by PHP, an open sourcescripting language primarily designed for generating HTML
content
Since its inception in 1994, PHP has swept the Web and
continues its phenomenal growth with recent endorsements byIBM and ORACLE corporations (to name a few) Also, the
millions of web sites powered by PHP are testament to its
popularity and ease of use It lies in the sweet spot betweenPerl/CGI, Active Server Pages (ASP), and HTML Everyday
people can learn PHP and can build powerful dynamic web siteswith it Marc Andreessen, chairman of Opsware Inc and
founder of Netscape Communications, recently described PHP ashaving replaced Java as the ideal programming language for theWeb
and array-handling facilities, as well as greatly improved
The core PHP language (Version 5+) features powerful string-support for object-oriented programming With the use of
standard and optional extension modules, a PHP application caninteract with a database such as MySQL or Oracle, draw graphs,create PDF files, and parse XML files You can write your ownPHP extension modules in Cfor example, to provide a PHP
interface to the functions in an existing code library You caneven run PHP on Windows, which lets you control other
Windows applications such as Word and Excel with COM or
interact with databases using ODBC
This book is a guide to the PHP language When you finish it,you will know how the PHP language works, how to use the
Trang 13many powerful extensions that come standard with PHP, andhow to design and build your own PHP web applications.
Trang 14PHP is a melting pot of cultures Web designers appreciate itsaccessibility and convenience, while programmers appreciate itsflexibility, power, diversity, and speed Both cultures need a
clear and accurate reference to the language If you are a
programmer, then this book is for you We show the big picture
of the PHP language, and then discuss the details without
wasting your time The many examples clarify the explanations,and the practical programming advice and many style tips willhelp you become not just a PHP programmer, but a good PHPprogrammer
If you're a web designer, you will appreciate the clear and
useful guides to specific technologies, such as XML, sessions,PDF generation, and graphics And you'll be able to quickly getthe information you need from the language chapters, whichexplain basic programming concepts in simple terms
This book has been fully revised to cover the latest features ofPHP Version 5 We have endeavored to even talk about some ofthe features that were still on the drawing board while we werewriting this edition One feature in particular is the new PDOdatabase interface that was still in development during our
writing, but we felt it important enough to cover in the
discussion on databases (Chapter 8)
Trang 15
This book assumes you have a working knowledge of HTML Ifyou don't know HTML, you should gain some experience withsimple web pages before you try to tackle PHP For more
information on HTML, we recommend HTML & XHTML: The
Definitive Guide by Chuck Musciano and Bill Kennedy (O'Reilly).
Trang 16We've arranged the material in this book so that you can eitherread it from start to finish or jump around to hit just the topicsthat interest you The book is divided into 15 chapters and 2appendixes, as follows:
Chapter 1, Introduction to PHP
Talks about the history of PHP and gives a lightning-fastoverview of what is possible with PHP programs
Discusses user-defined functions, including scope, variable-functions
Chapter 4, Strings
Covers the functions you'll use when building, dissecting,searching, and modifying strings in your PHP code
Trang 17engine and the new PDO database interface are covered
Chapter 9, Graphics
Demonstrates how to create and modify image files in avariety of formats from within PHP
Trang 18Explains how to create dynamic PDF files from a PHPapplication
Chapter 11, XML
Introduces PHP's updated extensions for generating andparsing XML data
Chapter 12, Security
Provides valuable advice and guidance for programmerscreating secure scripts You'll learn best practices
programming techniques here that will help you avoidmistakes that can lead to disaster
Chapter 13, Application Techniques
Talks about the advanced techniques that most PHPprogrammers eventually want to use, including errorhandling and performance tuning
Chapter 14, Extending PHP
An advanced chapter that presents easy-to-follow
instructions for building a PHP extension in C
Chapter 15, PHP on Windows
Trang 19It also discusses the features unique to Windows, such asCOM and ODBC
Trang 20The following typographical conventions are used in this book:
Plain text
Indicates menu titles, menu options, menu buttons, andkeyboard accelerators (such as Alt and Ctrl)
Italic
Indicates new terms, URLs, email addresses, filenames, fileextensions, pathnames, directories, and Unix utilities
Constant width
Indicates commands, options, switches, variables,
attributes, keys, functions, types, classes, namespaces,methods, modules, properties, parameters, values, objects,events, event handlers, XML tags, HTML tags, macros, thecontents of files, or the output from commands
Constant width bold
Shows commands or other text that should be typed
literally by the user
Constant width italic
Trang 21This icon signifies a tip, suggestion, or general note.
This icon indicates a warning or caution.
Trang 22
This book is here to help you get your job done In general, youmay use the code in this book in your programs and
documentation You do not need to contact us for permissionunless you're reproducing a significant portion of the code Forexample, writing a program that uses several chunks of codefrom this book does not require permission Selling or
distributing a CD-ROM of examples from O'Reilly books doesrequire permission Answering a question by citing this bookand quoting example code does not require permission
Incorporating a significant amount of example code from thisbook into your product's documentation does require
permission
We appreciate, but do not require, attribution An attributionusually includes the title, author, publisher, and ISBN For
example: "Programming PHP, Second Edition, by Rasmus
Lerdorf, Kevin Tatroe, and Peter MacIntyre Copyright 2006
O'Reilly Media, Inc., 0-596-00681-0."
If you feel your use of code examples falls outside fair use orthe permission provided, feel free to contact us at
permissions@oreilly.com
Trang 23
Please address comments and questions concerning this book tothe publisher:
http://www.oreilly.com/catalog/progphp2
To comment or ask technical questions about this book, sendemail to:
bookquestions@oreilly.com
For more information about our books, conferences, ResourceCenters, and the O'Reilly Network, see our web site at:
http://www.oreilly.com
Trang 24
When you see a Safari® Enabled icon on the cover ofyour favorite technology book, that means the book is availableonline through the O'Reilly Network Safari Bookshelf
Safari offers a solution that's better than e-books It's a virtuallibrary that lets you easily search thousands of top tech books,cut and paste code samples, download chapters, and find quickanswers when you need the most accurate, current information.Try it for free at http://safari.oreilly.com
Trang 25
Rasmus Lerdorf
I would like to acknowledge the large and wonderfully
boisterous PHP community, without which there would be noPHP today
Kevin Tatroe
Thanks to every individual who ever committed code to PHP orwho wrote a line of code in PHPyou all made PHP what it is
today
To my parents, who once purchased a small LEGO set for a longand frightening plane trip, beginning an obsession with
creativity and organization that continues to relax and inspire
Finally, a heaping second spoonful of gratitude to Jennifer andHadden, who continue to inspire and encourage me even as Ipound out words and code every day
Peter MacIntyre
I would first like to praise the Lord of Hosts who gives me thestrength to face each day He created electricity through which Imake my livelihood; thanks and praise to Him for this totallyunique and fascinating portion of His creation
Closer to home, I would like to thank Rasmus for the initial (andcontinuing) efforts behind this great language called PHP I have
Trang 26start to finish
I would also like to thank my friends Mike Burns and Ian Morse,who performed the almost thankless job of doing the technicalediting on this book My hat goes off to you boththanks a lot!
And finally to all those at O'Reilly who so often go unmentionedIdon't know all your names, but I know what you have to do tomake a book like this finally make it to the bookshelves Theediting, graphics work, layout, planning, marketing, and so onall has to be done, and I appreciate your work toward this end
Dedication
I would like to dedicate my portions of this book to my
wonderful wife, Dawn Etta Riley She has been supportive of me
in my personal endeavors, and although some of them don'tpay off, she still supports my efforts of the ones that do I loveyou, Dawn, and look forward to the teenage-free years withyou To our children, too, I would like to dedicate this effort:Daniel Tomas Walker, Charity Margaret Marie MacIntyre, MichaelPeter Walker, and Simon Peter MacIntyre (just to get their
names in print)
Trang 27PHP is a simple yet powerful language designed for creatingHTML content This chapter covers essential background on thePHP language It describes the nature and history of PHP; whichplatforms it runs on; and how to download, install, and
configure it This chapter ends by showing you PHP in action,with a quick walkthrough of several PHP programs that illustratecommon tasks, such as processing form data, interacting with adatabase, and creating graphics
Trang 28
PHP can be used in three primary ways:
Server-side scripting
PHP was originally designed to create dynamic web content,and it is still best suited for that task To generate HTML,you need the PHP parser and a web server to send the
documents PHP has also become popular for generatingXML documents, graphics, Flash animations, PDF files, andmore
Command-line scripting
PHP can run scripts from the command line, much like Perl,awk, or the Unix shell You might use the command-linescripts for system administration tasks, such as backup andlog parsing
Client-side GUI applications
blown, cross-platform GUI applications in PHP
Using PHP-GTK (http://gtk.php.net), you can write full-In this book, we'll concentrate on the first item, using PHP todevelop dynamic web content
PHP runs on all major operating systems, from Unix variantsincluding Linux, FreeBSD, and Solaris to Windows and Mac OS
X It can be used with all leading web servers, including
Trang 29The language is very flexible For example, you aren't limited tooutputting just HTML or other text filesany document formatcan be generated PHP has built-in support for generating PDFfiles, GIF, JPG, and PNG images, and Flash movies
One of PHP's most significant features is its wide-ranging
support for databases PHP supports all major databases
(including MySQL, PostgreSQL, Oracle, Sybase, and ODBC-compliant databases), and even many obscure ones With PHP,creating web pages with dynamic content from a database isremarkably simple
Finally, PHP provides a library of PHP code to perform commontasks, such as database abstraction, error handling, and so on,with the PHP Extension and Application Repository (PEAR)
PEAR is a framework and distribution system for reusable PHPcomponents You can find out more about it at
http://pear.php.net
Trang 30
Logging accesses to your pages in your own private log files Real-time viewing of log information
Trang 31Performing server-side includes without needing server support for it Ability to not log accesses from certain domains (ie your own)
Trang 32Newsgroups: comp.infosystems.www.authoring.cgi
Trang 33Password protect your pages, or restrict access based on the refering URL plus many other options
Trang 34Thomas Boutell's GD library is supported through an easy-to-use set of tags
Trang 36PHP 3.0 is available for free download in source form and binaries for several platforms at http://www.php.net/
The PHP Development Team is an international group of programmers who lead the open development of PHP and related projects
Trang 37Figure 1-1 shows the growth of PHP as measured by the usagenumbers collected by Netcraft (http://www.netcraft.com) sinceJanuary 2000 This figure shows the total number of unique IPaddresses that report they are using Apache with the PHP
module enabled (PHP: 19,720,597 Domains, 1,310,181 IP
Addresses) The slight dip at the end of 2001 reflects the
demise of a number of dot-coms that disappeared from theWeb The overall number of servers that Netcraft found alsowent down for the first time during this period You can see anupdate of this chart for yourself at any time by accessing thisweb address: http://www.php.net/usage.php
Figure 1-1 The growth of PHP usage since 2000
Trang 38
PHP is available for many operating systems and platforms Themost common setup, however, is to use PHP as a module forthe Apache web server on a Unix machine This section brieflydescribes how to install Apache with PHP If you're interested inrunning PHP on Windows, see Chapter 15, which explains many
of your options for that operating system
To install Apache with PHP, you'll need a Unix machine with anANSI-compliant C compiler, and around 10 MB of available diskspace for source and object files You'll also need Internet
access to fetch the source code for PHP and Apache
Start by downloading the source distributions of PHP and
Apache The latest files are always available from the web sitesfor the respective tools Since there are so many options oninstallation , we are showing here the generic installation
instructions for a Linux server as shown on the PHP web site athttp://ca3.php.net/manual/en/install.unix.php You will have toreplace the xxx signifier in the following steps with the version ofthe software that you choose to install
Although Apache has a Version 2.x you may find that it is more adept
at serving PHP with Version 1.3.xx, so generally we will be using the 1.3.xx version throughout this book.
Trang 3913 Set up your php.ini file:
cp php.ini-dist /usr/local/lib/php.ini
Trang 40You may edit your ini file to set PHP options If you prefer your php.ini in another location, use with-config-file-