Programming PHP > m o c . k o o b e w o w . w w w < k o o B e
! w o W m o r f d a o l n w o D Other resources from O’Reilly
Related titles Managing and Using MySQL Web Database Applications MySQL Cookbook™ with PHP and MySQL PHP Cookbook™ Learning PHP 5 PHP Pocket Reference Upgrading to PHP 5
oreilly.com oreilly.com is more than a complete catalog of O’Reilly books. You’ll also find links to news, events, articles, weblogs, sample chapters, and code examples.
oreillynet.com is the essential portal for developers interested in open and emerging technologies, including new platforms, pro- gramming languages, and operating systems.
Conferences O’Reilly brings diverse innovators together to nurture the ideas that spark revolutionary industries. We specialize in document- ing the latest tools and systems, translating the innovator’s knowledge into useful skills for those in the trenches. Visit con- ferences.oreilly.com for our upcoming events.
Safari Bookshelf (safari.oreilly.com) is the premier online refer- ence library for programmers and IT professionals. Conduct searches across more than 1,000 books. Subscribers can zero in on answers to time-critical questions in a matter of seconds. Read the books on your Bookshelf from cover to cover or sim- ply flip to the page you need. Try it today for free. SECOND EDITION Programming PHP
Rasmus Lerdorf, Kevin Tatroe, and Peter MacIntyre
Beijing • Cambridge • Farnham • Köln • Paris • Sebastopol • Taipei • Tokyo Programming PHP, Second Edition by 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 Highway North, Sebastopol, CA 95472. O’Reilly books may be purchased for educational, business, or sales promotional use. Online editions are also available for most titles (safari.oreilly.com). For more information, contact our corporate/institutional sales department: (800) 998-9938 or [email protected].
Editors: Tatiana Apandi and Allison Randal Cover Designer: Ellie Volckhausen Production Editor: Matt Hutchinson Interior Designer: David Futato Production Services: GEX, Inc. llustrators: Robert Romano, Jessamyn Read, and Lesley Borash
Printing History: March 2002: First Edition. April 2006: Second Edition.
Nutshell Handbook, the Nutshell Handbook logo, and the O’Reilly logo are registered trademarks of O’Reilly Media, Inc. Programming PHP, the image of a cuckoo, and related trade dress are trademarks of O’Reilly Media, Inc. Many of the designations used by manufacturers and sellers to distinguish their products are claimed as trademarks. Where those designations appear in this book, and O’Reilly Media, Inc. was aware of a trademark claim, the designations have been printed in caps or initial caps. While every precaution has been taken in the preparation of this book, the publisher and authors assume no responsibility for errors or omissions, or for damages resulting from the use of the information contained herein.
This book uses RepKover™, a durable and flexible lay-flat binding.
ISBN-10: 0-596-00681-0 ISBN-13: 978-0-596-00681-5 [M] [10/07] Table of Contents
Foreword ...... ix Preface ...... xi 1. Introduction to PHP ...... 1 What Does PHP Do? 1 A Brief History of PHP 2 Installing PHP 7 A Walk Through PHP 9
2. Language Basics ...... 18 Lexical Structure 18 Data Types 25 Variables 32 Expressions and Operators 36 Flow-Control Statements 49 Including Code 57 Embedding PHP in Web Pages 59
3. Functions ...... 63 Calling a Function 63 Defining a Function 64 Variable Scope 66 Function Parameters 68 Return Values 71 Variable Functions 72 Anonymous Functions 73
v 4. Strings ...... 74 Quoting String Constants 74 Printing Strings 78 Accessing Individual Characters 82 Cleaning Strings 82 Encoding and Escaping 83 Comparing Strings 89 Manipulating and Searching Strings 91 Regular Expressions 97 POSIX-Style Regular Expressions 101 Perl-Compatible Regular Expressions 106
5. Arrays ...... 119 Indexed Versus Associative Arrays 119 Identifying Elements of an Array 120 Storing Data in Arrays 120 Multidimensional Arrays 123 Extracting Multiple Values 123 Converting Between Arrays and Variables 127 Traversing Arrays 128 Sorting 133 Acting on Entire Arrays 138 Using Arrays 140
6. Objects ...... 143 Terminology 144 Creating an Object 144 Accessing Properties and Methods 145 Declaring a Class 146 Introspection 153 Serialization 159
7. Web Techniques ...... 164 HTTP Basics 164 Variables 165 Server Information 166 Processing Forms 168 Setting Response Headers 182 Maintaining State 185 SSL 195 vi | Table of Contents 8. Databases ...... 196 Using PHP to Access a Database 196 Relational Databases and SQL 198 PEAR DB Basics 199 Advanced Database Techniques 205 Sample Application 211
9. Graphics ...... 225 Embedding an Image in a Page 225 The GD Extension 226 Basic Graphics Concepts 227 Creating and Drawing Images 228 Images with Text 232 Dynamically Generated Buttons 236 Scaling Images 239 Color Handling 240
10. PDF ...... 246 PDF Extensions 246 Documents and Pages 246 Text 248
11. XML ...... 261 Lightning Guide to XML 261 Generating XML 263 Parsing XML 264 Parsing XML with DOM 277 Parsing XML with SimpleXML 277 Transforming XML with XSLT 278 Web Services 280
12. Security ...... 285 Filter Input 285 Escape Output 290 Cross-Site Scripting 293 Session Fixation 294 File Uploads 295 File Access 296 PHP Code 299
Table of Contents | vii Shell Commands 300 More Information 301 Security Recap 301
13. Application Techniques ...... 302 Code Libraries 302 Templating Systems 303 Handling Output 306 Error Handling 308 Performance Tuning 313
14. Extending PHP ...... 321 Architectural Overview 321 What You’ll Need 322 Building Your First Extensions 323 The config.m4 File 333 Memory Management 336 The pval/zval Data Type 338 Parameter Handling 342 Returning Values 345 References 349 Global Variables 350 Creating Variables 353 Extension INI Entries 354 Resources 356 Where to Go from Here 358
15. PHP on Windows ...... 359 Installing and Configuring PHP on Windows 359 Writing Portable Code for Windows and Unix 363 Interfacing with COM 366 Interacting with ODBC Data Sources 372
A. Function Reference ...... 377 B. Extension Overview ...... 491 Index ...... 503
viii | Table of Contents Foreword
Today, PHP is the most widely used programming language on the Web, with over 40 percent of all web applications written in PHP. It is installed on over 22 million domain servers (source: Netcraft), as shown in Figure F-1. The number of develop- ers using PHP has now reached over 2.5 million. The community developing PHP is very impressive, withover 450 CVS committers whowrote a total of 1 million lines of code. The PHP community is one of the most dynamic, with thousands of people sharing code, evangelizing about PHP, supporting each other, and creating many projects suchas Wikipedia, Mambo, PHP-Nuke, FUDforum, SugarCRM, and Horde, just to mention a few.
IBM, Oracle Endorse PHP PHP 5.0 Yahoo! • XML, SOAP, OOP 20M Standardizes • Zend Studio on PHP
PHP 4 15M Released • 1M Internet domains • Zend Engine • Zend Founded Zeek Suraski, Andi Gutmans 10M Rasmus develop Lerdolf PHP 3 develops PHP/Fl 5M PHP internet domains 1995 1997 1999 2000 2002 2004 2005
Figure F-1. PHP development timeline with usage
Its simplicity is what made PHP so successful. Simplicity equals less code. Develop- ers and companies have been developing projects with PHP in a fraction of the time it would take another language.
ix
This is the Title of the Book, eMatter Edition Copyright © 2007 O’Reilly & Associates, Inc. All rights reserved. There 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 between those who want simple, sloppy, flexible, human ways to write code and those who want clean, crisp, clear, correct ways to write code. It is the war between PHP and C++/Java. —Adam Bosworth Google The future of PHP looks very bright. Leading platform vendors such as IBM, Oracle, MySQL, Intel, and, most recently, Red Hat have all endorsed it. The new Collabora- tion Project initiated by Zend Technologies rallies many leading companies and com- munity 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 develop- ment and deployment environment. The Project’s first two open initiatives are: Zend PHP Framework This is a web application framework that will accelerate and improve the devel- > m
o opment and deployment of mission-critical PHP web applications. c . k
o Support for the Eclipse Development platform o b
e Zend is joining the Eclipse Foundation as a Strategic Developer. It will develop, w o in collaboration with partners, a PHP IDE based on the Eclipse platform. w . w Rasmus Lerdorf, the initial creator of the first version of PHP (then called PHP/FI), w w and Kevin Tatroe provided the guidelines for this book. The newest author on the < k o revision project is Peter MacIntyre, a Zend Certified Engineer withmore thanfive o B
e years experience in PHP. Wez Furlong and Chris Shiflett have also contributed to
!
w this book. Wez modernized the “Extending PHP” chapter, and Chris brought his o W
renowned expertise in updating the “Security” chapter. m o r f This book is a must-have for anybody working with PHP. Some of the most recog- d a nizable names in the PHP community have contributed to it. So you know that you o l n are getting quality information. It covers all of the important PHP topics, plus unique w o
D issues suchas extending and securing PHP, and discusses newer features of XML and Objects and PDO. —Michel Gerin Vice President, Marketing Zend Technologies, Inc., the PHP Company
x | Foreword
This is the Title of the Book, eMatter Edition Copyright © 2007 O’Reilly & Associates, Inc. All rights reserved. Preface1
Now more than ever, the Web is a major vehicle for corporate and personal commu- nications. Web sites carry satellite images of Earthin its entirety, searchfor life in outer space, and house personal photo albums, business shopping carts, and prod- uct lists. Many of those web sites are driven by PHP, an open source scripting lan- guage primarily designed for generating HTML content. Since its inception in 1994, PHP has swept the Web and continues its phenomenal growthwithrecent endorsements by IBM 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 between Perl/CGI, Active Server Pages (ASP), and HTML. Everyday people can learn PHP and can build powerful dynamic web sites withit. Marc Andreessen, chairmanof Opsware Inc. and founder of Netscape Communications, recently described PHP as having replaced Java as the ideal pro- gramming language for the Web. The core PHP language (Version 5+) features powerful string- and array-handling facilities, as well as greatly improved support for object-oriented programming. With the use of standard and optional extension modules, a PHP application can interact witha database suchas MySQL or Oracle, draw graphs,create PDF files, and parse XML files. You can write your own PHP extension modules in C—for example, to provide a PHP interface to the functions in an existing code library. You can even 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 many powerful extensions that come stan- dard with PHP, and how to design and build your own PHP web applications.
xi
This is the Title of the Book, eMatter Edition Copyright © 2007 O’Reilly & Associates, Inc. All rights reserved. Audience PHP is a melting pot of cultures. Web designers appreciate its accessibility and con- venience, while programmers appreciate its flexibility, power, diversity, and speed. Bothcultures need a clear and accurate reference to thelanguage. If you are a pro- grammer, 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 will help you become not just a PHP programmer, but a good PHP programmer. 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 get the information you need from the language chapters, which explain basic programming concepts in simple terms. This book has been fully revised to cover the latest features of PHP Version 5. We have endeavored to even talk about some of the features that were still on the draw- ing board while we were writing this edition. One feature in particular is the new PDO database interface that was still in development during our writing, but we felt it important enough to cover in the discussion on databases (Chapter 8). Assumptions This Book Makes This book assumes you have a working knowledge of HTML. If you don’t know HTML, you should gain some experience with simple 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). Contents of This Book We’ve arranged the material in this book so that you can either read it from start to finish or jump around to hit just the topics that interest you. The book is divided into 15 chapters and 2 appendixes, as follows: Chapter 1, Introduction to PHP Talks about the history of PHP and gives a lightning-fast overview of what is possible with PHP programs. Chapter 2, Language Basics Is a concise guide to PHP program elements suchas identifiers, data types, oper- ators, and flow-control statements. Chapter 3, Functions Discusses user-defined functions, including scope, variable-lengthparameter lists, and variable and anonymous functions.
xii | Preface
This is the Title of the Book, eMatter Edition Copyright © 2007 O’Reilly & Associates, Inc. All rights reserved. Chapter 4, Strings Covers the functions you’ll use when building, dissecting, searching, and modi- fying strings in your PHP code. Chapter 5, Arrays Details the notation and functions for constructing, processing, and sorting arrays in your PHP code. Chapter 6, Objects Covers PHP’s updated object-oriented features. In this chapter, you’ll learn about classes, objects, inheritance, and introspection. Chapter 7, Web Techniques Discusses web basics such as form parameters and validation, cookies, and sessions. Chapter 8, Databases Discusses PHP’s modules and functions for working withdatabases, using the PEAR DB library and the MySQL database as examples. Also, the new SQLite database engine and the new PDO database interface are covered. Chapter 9, Graphics Demonstrates how to create and modify image files in a variety of formats from within PHP. Chapter 10, PDF Explains how to create dynamic PDF files from a PHP application. Chapter 11, XML Introduces PHP’s updated extensions for generating and parsing XML data. Chapter 12, Security Provides valuable advice and guidance for programmers creating secure scripts. You’ll learn best practices programming techniques here that will help you avoid mistakes that can lead to disaster. Chapter 13, Application Techniques Talks about the advanced techniques that most PHP programmers eventually want to use, including error handling 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 Discusses the tricks and traps of the Windows port of PHP. It also discusses the features unique to Windows, such as COM and ODBC. Appendix A, Function Reference A handy quick reference to all the core functions in PHP. Appendix B, Extension Overview Describes the standard extensions that ship with PHP.
Preface | xiii
This is the Title of the Book, eMatter Edition Copyright © 2007 O’Reilly & Associates, Inc. All rights reserved. Conventions Used in This Book The following typographical conventions are used in this book: Plain text Indicates menu titles, menu options, menu buttons, and keyboard accelerators (such as Alt and Ctrl). Italic Indicates new terms, URLs, email addresses, filenames, file extensions, path- names, 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, the contents 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 Shows text that should be replaced with user-supplied values.
This icon signifies a tip, suggestion, or general note.
This icon indicates a warning or caution.
Using Code Examples This book is here to help you get your job done. In general, you may use the code in this book in your programs and documentation. You do not need to contact us for permission unless you’re reproducing a significant portion of the code. For example, writing a program that uses several chunks of code from this book does not require permission. Selling or distributing a CD-ROM of examples from O’Reilly books does require permission. Answering a question by citing this book and quoting example code does not require permission. Incorporating a significant amount of example code from this book into your product’s documentation does require permission. We appreciate, but do not require, attribution. An attribution usually 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.”
xiv | Preface
This is the Title of the Book, eMatter Edition Copyright © 2007 O’Reilly & Associates, Inc. All rights reserved. If you feel your use of code examples falls outside fair use or the permission provided, feel free to contact us at [email protected]. Comments and Questions Please address comments and questions concerning this book to the publisher: O’Reilly Media, Inc. 1005 Gravenstein Highway North Sebastopol, CA 95472 (800) 998-9938 (in the United States or Canada) (707) 829-0515 (international or local) (707) 829-0104 (fax) We have a web page for this book, where we list errata, examples, and any addi- tional information. You can access this page at: http://www.oreilly.com/catalog/progphp2 To comment or ask technical questions about this book, send email to: [email protected] For more information about our books, conferences, Resource Centers, and the O’Reilly Network, see our web site at: http://www.oreilly.com Safari® Enabled When you see a Safari® Enabled icon on the cover of your favorite tech- nology book, that means the book is available online through the O’Reilly Network Safari Bookshelf. Safari offers a solution that’s better than e-books. It’s a virtual library that lets you easily searchthousandsof top techbooks, cut and paste code samples, download chapters, and find quick answers when you need the most accurate, current informa- tion. Try it for free at http://safari.oreilly.com. Acknowledgments Rasmus Lerdorf I would like to acknowledge the large and wonderfully boisterous PHP community, without which there would be no PHP today.
Preface | xv
This is the Title of the Book, eMatter Edition Copyright © 2007 O’Reilly & Associates, Inc. All rights reserved. Kevin Tatroe Thanks to every individual who ever committed code to PHP or who wrote a line of code in PHP—you all made PHP what it is today. To my parents, who once purchased a small LEGO set for a long and frightening plane trip, beginning an obsession withcreativity and organization thatcontinues to relax and inspire. Finally, a heaping second spoonful of gratitude to Jennifer and Hadden, who con- tinue to inspire and encourage me even as I pound out words and code every day.
Peter MacIntyre I would first like to praise the Lord of Hosts who gives me the strength to face each day. He created electricity through which I make my livelihood; thanks and praise to Him for this totally unique and fascinating portion of His creation. Closer to home, I would like to thank Rasmus for the initial (and continuing) efforts behind this great language called PHP. I have been using PHP exclusively for many years now and love its simplicity and logic more each day. To Kevin, my main coauthor in this edition, thanks for the efforts and desire to stick with this project to the end. You took on a big task with the “harder” chapters, and with the help of Wez Furlong and Chris Shiflett we finally pulled it off! To Allison Randal and Tatiana Apandi at O’Reilly, great patience and professional- ism came from you both on this project. Thanks for giving me this opportunity and for working with us from start to finish. I would also like to thank my friends Mike Burns and Ian Morse, who performed the almost thankless job of doing the technical editing on this book. My hat goes off to you both—thanks a lot! And finally to all those at O’Reilly who so often go unmentioned—I don’t know all your names, but I know what you have to do to make a book like this finally make it to the bookshelves. The editing, graphics work, layout, planning, marketing, and so on all 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’t pay off, she still supports my efforts of the ones that do. I love you, Dawn, and look forward to the teenage-free years with you. To our children, too, I would like to dedicate this effort: Daniel Tomas Walker, Charity Margaret Marie MacIntyre, Michael Peter Walker, and Simon Peter MacIntyre (just to get their names in print).
xvi | Preface
This is the Title of the Book, eMatter Edition Copyright © 2007 O’Reilly & Associates, Inc. All rights reserved. Chapter 1 CHAPTER 1 Introduction to PHP
PHP is a simple yet powerful language designed for creating HTML content. This chapter covers essential background on the PHP language. It describes the nature and history of PHP; which platforms it runs on; and how to download, install, and configure it. This chapter ends by showing you PHP in action, with a quick walk- through of several PHP programs that illustrate common tasks, such as processing form data, interacting with a database, and creating graphics. What Does PHP Do? 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 generating XML documents, graphics, Flash animations, PDF files, and more. Command-line scripting PHP can run scripts from the command line, much like Perl, awk, or the Unix shell. You might use the command-line scripts for system administration tasks, such as backup and log parsing. Client-side GUI applications Using PHP-GTK (http://gtk.php.net), you can write full-blown, cross-platform GUI applications in PHP. In this book, we’ll concentrate on the first item, using PHP to develop dynamic web content. PHP runs on all major operating systems, from Unix variants including Linux, FreeBSD, and Solaris to Windows and Mac OS X. It can be used withall leading web servers, including Apache, Microsoft IIS, and the Netscape/iPlanet servers.
1
This is the Title of the Book, eMatter Edition Copyright © 2007 O’Reilly & Associates, Inc. All rights reserved. The language is very flexible. For example, you aren’t limited to outputting just HTML or other text files—any document format can be generated. PHP has built-in support for generating PDF files, 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. WithPHP, creating web pages with dynamic content from a database is remarkably simple. Finally, PHP provides a library of PHP code to perform common tasks, suchas data- base abstraction, error handling, and so on, with the PHP Extension and Applica- tion Repository (PEAR). PEAR is a framework and distribution system for reusable PHP components. You can find out more about it at http://pear.php.net. A Brief History of PHP Rasmus Lerdorf first conceived of PHP in 1994, but the PHP that people use today is quite different from the initial version. To understand how PHP got where it is today, it is useful to know the historical evolution of the language. Here’s that story, as told by Rasmus.
The Evolution of PHP Here is the PHP 1.0 announcement that I posted to the Usenet newsgroup comp.info- systems.www.authoring.cgi in June 1995: From: [email protected] (Rasmus Lerdorf) Subject: Announce: Personal Home Page Tools (PHP Tools) Date: 1995/06/08 Message-ID: <[email protected]>#1/1 organization: none newsgroups: comp.infosystems.www.authoring.cgi
Announcing the Personal Home Page Tools (PHP Tools) version 1.0.
These tools are a set of small tight cgi binaries written in C. They perform a number of functions including:
. Logging accesses to your pages in your own private log files . Real-time viewing of log information . Providing a nice interface to this log information . Displaying last access information right on your pages . Full daily and total access counters . Banning access to users based on their domain . Password protecting pages based on users' domains . Tracking accesses ** based on users' e-mail addresses ** . Tracking referring URL's - HTTP_REFERER support . Performing server-side includes without needing server support for it . Ability to not log accesses from certain domains (ie. your own)
2 | Chapter 1: Introduction to PHP
This is the Title of the Book, eMatter Edition Copyright © 2007 O’Reilly & Associates, Inc. All rights reserved. . Easily create and display forms . Ability to use form information in following documents
Here is what you don't need to use these tools:
. You do not need root access - install in your ~/public_html dir . You do not need server-side includes enabled in your server . You do not need access to Perl or Tcl or any other script interpreter . You do not need access to the httpd log files
The only requirement for these tools to work is that you have the ability to execute your own cgi programs. Ask your system administrator if you are not sure what this means.
The tools also allow you to implement a guestbook or any other form that needs to write information and display it to users later in about 2 minutes.
The tools are in the public domain distributed under the GNU Public License. Yes, that means they are free!
For a complete demonstration of these tools, point your browser at: http://www.io.org/~rasmus
-- Rasmus Lerdorf [email protected] http://www.io.org/~rasmus Note that the URL and email address shown in this message are long gone. The lan- guage of this announcement reflects the concerns that people had at the time, such as password-protecting pages, easily creating forms, and accessing form data on sub- sequent pages. The announcement also illustrates PHP’s initial positioning as a framework for a number of useful tools. The announcement talks only about the tools that came with PHP, but behind the scenes the goal was to create a framework to make it easy to extend PHP and add more tools. The business logic for these add-ons was written in C—a simple parser picked tags out of the HTML and called the various C functions. It was never my plan to create a scripting language. So, what happened? I started working on a rather large project for the University of Toronto that needed a tool to pull together data from various places and present a nice web-based admin- istration interface. Of course, I decided that PHP would be ideal for the task, but for performance reasons, the various small tools of PHP 1 had to be brought together better and integrated into the web server. Initially, I made some hacks to the NCSA web server, to patch it to support the core PHP functionality. The problem with this approach was that as a user, you had to
A Brief History of PHP | 3
This is the Title of the Book, eMatter Edition Copyright © 2007 O’Reilly & Associates, Inc. All rights reserved. replace your web-server software with this special, hacked-up version. Fortunately, Apache was starting to gain momentum around this time, and the Apache API made it easier to add functionality like PHP to the server. Over the next year or so, a lot was done and the focus changed quite a bit. Here’s the PHP Version 2 (PHP/FI) announcement I sent in April 1996: From: [email protected] (Rasmus Lerdorf) Subject: ANNOUNCE: PHP/FI Server-side HTML-Embedded Scripting Language Date: 1996/04/16 Newsgroups: comp.infosystems.www.authoring.cgi
PHP/FI is a server-side HTML embedded scripting language. It has built-in access logging and access restriction features and also support for embedded SQL queries to mSQL and/or Postgres95 backend databases.
It is most likely the fastest and simplest tool available for creating database-enabled web sites.
It will work with any UNIX-based web server on every UNIX flavour out there. The package is completely free of charge for all uses including commercial.
Feature List:
. Access Logging Log every hit to your pages in either a dbm or an mSQL database. Having hit information in a database format makes later analysis easier. . Access Restriction Password protect your pages, or restrict access based on the refering URL plus many other options. . mSQL Support Embed mSQL queries right in your HTML source files . Postgres95 Support Embed Postgres95 queries right in your HTML source files . DBM Support DB,DBM,NDBM and GDBM are all supported . RFC-1867 File Upload Support Create file upload forms . Variables, Arrays, Associative Arrays . User-Defined Functions with static variables + recursion . Conditionals and While loops Writing conditional dynamic web pages could not be easier than with the PHP/FI conditionals and looping support . Extended Regular Expressions Powerful string manipulation support through full regexp support . Raw HTTP Header Control Lets you send customized HTTP headers to the browser for advanced features such as cookies. . Dynamic GIF Image Creation Thomas Boutell's GD library is supported through an easy-to-use set of tags.
4 | Chapter 1: Introduction to PHP
This is the Title of the Book, eMatter Edition Copyright © 2007 O’Reilly & Associates, Inc. All rights reserved. It can be downloaded from the File Archive at:
-- Rasmus Lerdorf [email protected] This was the first time the term “scripting language” was used. PHP 1’s simplistic tag-replacement code was replaced with a parser that could handle a more sophisti- cated embedded tag language. By today’s standards, the tag language wasn’t particu- larly sophisticated, but compared to PHP 1 it certainly was. The main reason for this change was that few people who used PHP 1 were actually interested in using the C-based framework for creating add-ons. Most users were muchmore interested in being able to embed logic directly in theirweb pages for cre- ating conditional HTML, custom tags, and other such features. PHP 1 users were constantly requesting the ability to add the hit-tracking footer or send different HTML blocks conditionally. This led to the creation of an if tag. Once you have if, you need else as well and from there, it’s a slippery slope to the point where, whether you want to or not, you end up writing an entire scripting language. By mid-1997, PHP Version 2 had grown quite a bit and had attracted a lot of users, but there were still some stability problems with the underlying parsing engine. The project was also still mostly a one-man effort, witha few contributions hereand there. At this point, Zeev Suraski and Andi Gutmans in Tel Aviv volunteered to rewrite the underlying parsing engine, and we agreed to make their rewrite the base for PHP Version 3. Other people also volunteered to work on other parts of PHP, and the project changed from a one-person effort with a few contributors to a true open source project with many developers around the world. Here is the PHP 3.0 announcement from June 1998: June 6, 1998 -- The PHP Development Team announced the release of PHP 3.0, the latest release of the server-side scripting solution already in use on over 70,000 World Wide Web sites.
This all-new version of the popular scripting language includes support for all major operating systems (Windows 95/NT, most versions of Unix, and Macintosh) and web servers (including Apache, Netscape servers, WebSite Pro, and Microsoft Internet Information Server).
PHP 3.0 also supports a wide range of databases, including Oracle, Sybase, Solid, MySQ, mSQL, and PostgreSQL, as well as ODBC data sources.
New features include persistent database connections, support for the SNMP and IMAP protocols, and a revamped C API for extending the language with new features.
"PHP is a very programmer-friendly scripting language suitable for people with little or no programming experience as well as the seasoned web developer who needs to get things done quickly. The best thing about PHP is that you get results quickly," said Rasmus Lerdorf, one of the developers of the language.
A Brief History of PHP | 5
This is the Title of the Book, eMatter Edition Copyright © 2007 O’Reilly & Associates, Inc. All rights reserved. "Version 3 provides a much more powerful, reliable and efficient implementation of the language, while maintaining the ease of use and rapid development that were the key to PHP's success in the past," added Andi Gutmans, one of the implementors of the new language core.
"At Circle Net we have found PHP to be the most robust platform for rapid web-based application development available today," said Troy Cobb, Chief Technology Officer at Circle Net, Inc. "Our use of PHP has cut our development time in half, and more than doubled our client satisfaction. PHP has enabled us to provide database-driven dynamic solutions which perform at phenomenal speeds."
PHP 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.
For more information, the PHP Development Team can be contacted at [email protected]. After the release of PHP 3, usage really started to take off. Version 4 was prompted by a number of developers who were interested in making some fundamental changes to the architecture of PHP. These changes included abstracting the layer between the language and the web server, adding a thread-safety mechanism, and adding a more advanced, two-stage parse/execute tag-parsing system. This new parser, primarily written by Zeev and Andi, was named the Zend engine. After a lot of work by a lot of developers, PHP 4.0 was released on May 22, 2000. Since that release, there have been a few minor releases of PHP 4, with the latest ver- sion as of this writing being 4.3.11. As this book goes to press, PHP Version 5 has been released for some time. There have already been a few minor ‘dot’ releases, and the stability of this current version is quite high. As you will see in this book, there have been some major advances made in this version of PHP. XML, object orienta- tion, and SQLite are among the major updates. Many other minor changes, function additions, and feature enhancements have also been incorporated.
The Growth of PHP Figure 1-1 shows the growth of PHP as measured by the usage numbers collected by Netcraft (http://www.netcraft.com) since January 2000. This figure shows the total number of unique IP addresses that report they are using Apache with the PHP mod- ule 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 the Web. The overall number of servers that Netcraft found also went down for the first time during this period. You can see an update of this chart for yourself at any time by accessing this web address: http://www.php.net/usage.php.
6 | Chapter 1: Introduction to PHP
This is the Title of the Book, eMatter Edition Copyright © 2007 O’Reilly & Associates, Inc. All rights reserved. > m o c . k o o b e
w Figure 1-1. The growth of PHP usage since 2000 o w . w w w Installing PHP < k o
o PHP is available for many operating systems and platforms. The most common B e
setup, however, is to use PHP as a module for the Apache web server on a Unix ! w
o machine. This section briefly describes how to install Apache with PHP. If you’re W interested in running PHP on Windows, see Chapter 15, which explains many of m o r your options for that operating system. f d a
o To install Apache with PHP, you’ll need a Unix machine with an ANSI-compliant C l n
w compiler, and around 10 MB of available disk space for source and object files. o
D 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 sites for the respective tools. Since there are so many options on installation, we are showing here the generic installation instructions for a Linux server as shown on the PHP web site at http://ca3.php.net/manual/en/install. unix.php. You will have to replace the xxx signifier in the following steps with the version of the software that you choose to install.
Although Apache has a Version 2.x you may find that it is more adept at serving PHP withVersion 1.3.xx, so generally we will be using the 1.3.xx version throughout this book.
1. gunzip apache_xxx.tar.gz 2. tar -xvf apache_xxx.tar
Installing PHP | 7
This is the Title of the Book, eMatter Edition Copyright © 2007 O’Reilly & Associates, Inc. All rights reserved. 3. gunzip php-xxx.tar.gz 4. tar -xvf php-xxx.tar 5. cd apache_xxx 6. ./configure --prefix=/www --enable-module=so 7. make 8. make install 9. cd ../php-xxx 10. Now, configure your PHP. This is where you customize your PHP with various options, like which extensions will be enabled. Do a ./configure --help for a list of available options. In our example we’ll do a simple configure withApache1 and MySQL support. Your path to apxs may differ from our example. ./configure --with-mysql --with-apxs=/www/bin/apxs 11. make 12. make install If you decide to change your configure options after installation, you only need to repeat the last three steps. You only need to restart apache for the new mod- ule to take effect. A recompile of Apache is not needed. Note that unless told otherwise, make install will also install PEAR, various PHP tools such as phpize, install the PHP CLI, and more. 13. Set up your php.ini file: cp php.ini-dist /usr/local/lib/php.ini You may edit your .ini file to set PHP options. If you prefer your php.ini in another location, use --with-config-file-path=/some/path in step 10. If you instead choose php.ini-recommended, be certain to read the list of changes within, as they affect how PHP behaves. 14. Edit your httpd.conf to load the PHP module. The path on the righthand side of the LoadModule statement must point to the path of the PHP module on your system. The make install from above may have already added this for you, but be sure to check. LoadModule php5_module libexec/libphp5.so 15. And in the AddModule section of httpd.conf, somewhere under the ClearMod- uleList, add this: AddModule mod_php5.c 16. Tell Apache to parse certain extensions as PHP. For example, let’s have Apache parse the .php extension as PHP. You could have any extension(s) parse as PHP
8 | Chapter 1: Introduction to PHP
This is the Title of the Book, eMatter Edition Copyright © 2007 O’Reilly & Associates, Inc. All rights reserved. by simply adding more, witheachseparated by a space. We’ll add .phtml to demonstrate: AddType application/x-httpd-php .php .phtml It’s also common to setup the .phps extension to show highlighted PHP source, this can be done with: AddType application/x-httpd-php-source .phps 17. Use your normal procedure for starting the Apache server. (You must stop and restart the server, not just cause the server to reload by using a HUP or USR1 signal.) You should now have Apache installed with PHP enabled. You will also have some of PHP’s many extensions installed. You may also want to change the PHP configu- ration. To do that you will have to change the php.ini file and restart your Apache server. Each time you make a change to PHP’s environment you will have to re-start the Apache server in order for those changes to take effect. As was mentioned, PHP’s configuration settings go in a file called php.ini. The set- tings in this file control the behavior of PHP features, such as session handling and form processing. Later chapters refer to some of the php.ini options, but in general the code in this book does not require a customized configuration. See http://ca3.php.net/manual/en/configuration.php#configuration.file for more infor- mation on php.ini configuration. The PHP and Apache source directories both include files called INSTALL that con- tain detailed instructions on troubleshooting and building those programs. If you want a nonstandard installation, or if you encounter problems withtheinstructions presented here, be sure to read the INSTALL files or go to their respective web sites for further assistance. A Walk Through PHP PHP pages are HTML pages with PHP commands embedded in them. This is in con- trast to many other dynamic web-page solutions which are scripts that generate HTML. The web server processes the PHP commands and sends their output (and any HTML from the file) to the browser. Example 1-1 shows a complete PHP page.
Example 1-1. Hello_world.php
A Walk Through PHP | 9
This is the Title of the Book, eMatter Edition Copyright © 2007 O’Reilly & Associates, Inc. All rights reserved. Example 1-1. Hello_world.php (continued)
Save the contents of Example 1-1 to a file, hello_world.php, and point your browser to it. The results appear in Figure 1-2.Figure 1-2. Output of hello_world.php
The PHP echo command produces output (the string “Hello, world!” in this case), which is inserted into the HTML file. In this example, the PHP code is placed between the tags. There are other ways to tag your PHP code—see Chapter 2 for a full description.
Configuration Page The PHP function phpinfo( ) creates an HTML page full of information on how PHP was installed. You can use it to see whether you have particular extensions installed, or whether the php.ini file has been customized. Example 1-2 is a complete page that displays the phpinfo( ) page.
Example 1-2. Using phpinfo( )
Figure 1-3 shows the first part of the output of Example 1-2.
Forms Example 1-3 creates and processes a form. When the user submits the form, the information typed into the name field is sent back to this page. The PHP code tests for a name field and displays a greeting if it finds one.
10 | Chapter 1: Introduction to PHP
This is the Title of the Book, eMatter Edition Copyright © 2007 O’Reilly & Associates, Inc. All rights reserved. Figure 1-3. Partial output of phpinfo( )
Example 1-3. Processing a form
A Walk Through PHP | 11
This is the Title of the Book, eMatter Edition Copyright © 2007 O’Reilly & Associates, Inc. All rights reserved. Example 1-3. Processing a form (continued)
The form and the message are shown in Figure 1-4.Figure 1-4. Form and greeting page
PHP programs access form values through the $_POST and $_GET array variables. Chapter 7 discusses forms and form processing in more detail. For now be sure that you are processing your pages with the REGISTER_GLOBALS value set to off (the default) in the php.ini file.
Databases PHP supports all the popular database systems, including MySQL, PostgreSQL, Ora- cle, Sybase, SQLite, and ODBC-compliant databases. Figure 1-5 shows part of a MySQL database query run through a PHP script showing the results of a book search on a book review site. This is showing the book title, the category of the book, the publisher of that book and the books’ ISBN number. The code in Example 1-4 connects to the database, issues a query to retrieve all avail- able books (withtheWHERE clause), and produces a table as output for all returned results through a for next loop.
12 | Chapter 1: Introduction to PHP
This is the Title of the Book, eMatter Edition Copyright © 2007 O’Reilly & Associates, Inc. All rights reserved. Figure 1-5. A MySQL Book list query run through a PHP script
Example 1-4. Querying the Books database
$sql = "SELECT * FROM books WHERE available = 1 ORDER BY title";
$result = mysql_query($sql, $connection) or die( "Could not execut sql: $sql"); $num_result = mysql_num_rows($result);
?>
These Books are currently available | ||||||
Title | Publisher | Category | ISBN | |||
"; echo stripslashes($row["title"]); echo " | "; if ( !$row["company"] ) { echo " "; } else { echo $row["company"]; } echo " | "; echo $row["typedesc"]; echo " | "; echo $row["isbn"]; echo " | "; echo "