sopheaks377@gmail.com (+855) 087443646 sok.sopheak152

Wednesday, August 26, 2015

Book php for web developer website.

Beginning
PHP 5.3
Matt Doyle

Interact Take an active role online by participating in our P2P forums
Wrox Online Library Hundreds of our books are available online through Books24x7.com
Wrox Blox Download short informational pieces and code to keep you up to date and out of trouble!
Get WROX.com
more out of
Chapters on Demand Purchase individual book chapters in pdf format
Join the Community Sign up for our free monthly newsletter at newsletter.wrox.com
Browse Ready for more Wrox? We have books and e-books available on .NET, SQL Server, Java, XML, Visual Basic, C#/ C++, and much more!

Contact Us. We always like to get feedback from our readers. Have a book idea? Need community support? Let us know by e-mailing wrox-partnerwithus@wrox.com



Beginning PHP 5.3
Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .xxvii
Part I: Getting Up and Running with PHP Chapter 1: Introducing PHP . . . . . . . . . . . . 3 
Chapter 2: Your First PHP Script . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11
Part II: Learning the Language
Chapter 3: PHP Language Basics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33 
Chapter 4: Decisions and Loops . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 51 
Chapter 5: Strings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 73 
Chapter 6: Arrays . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 101
Chapter 7: Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 141
Chapter 8: Objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 165
Part III: Using PHP in Practice
Chapter 9: Handling HTML Forms with PHP . . . . . . . . . . . . . . . . . . . . . . . . 221
Chapter 10: Preserving State With Query Strings, Cookies, and Sessions . . 267
Chapter 11: Working with Files and Directories . . . . . . . . . . . . . . . . . . . . . 297 
Chapter 12: Introducing Databases and SQL . . . . . . . . . . . . . . . . . . . . . . . . 337
Chapter 13: Retrieving Data from MySQL with PHP . . . . . . . . . . . . . . . . . . . 367
Chapter 14: Manipulating MySQL Data with PHP . . . . . . . . . . . . . . . . . . . . 403 
Chapter 15: Making Your Job Easier with PEAR . . . . . . . . . . . . . . . . . . . . . 441 
Chapter 16: PHP and the Outside World . . . . . . . . . . . . . . . . . . . . . . . . . . . 471 
Chapter 17: Generating Images with PHP . . . . . . . . . . . . . . . . . . . . . . . . . . 507 
Chapter 18: String Matching with Regular Expressions . . . . . . . . . . . . . . . . 539 
Chapter 19: Working with XML . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 573
Chapter 20: Writing High-Quality Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . 619 
Appendix A: Solutions to Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 673 
Appendix B: Configuring PHP . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 719
Appendix C: Alternatives to MySQL . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 757
Appendix D: Using PHP from the Command Line . . . . . . . . . . . . . . . . . . . . . 765 
Index . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 775



Beginning PHP 5.3


Beginning PHP 5.3

Matt Doyle
Wiley Publishing, Inc.



Beginning PHP 5.3 Published by Wiley Publishing, Inc. 10475 Crosspoint Boulevard Indianapolis, IN 46256
www.wiley.com
Copyright © 2010 by Wiley Publishing, Inc., Indianapolis, Indiana
ISBN: 978-0-470-41396-8
Manufactured in the United States of America
10 9 8 7 6 5 4 3 2 1
Library of Congress Control Number: 2009017149
No part of this publication may be reproduced, stored in a retrieval system or transmitted in any form or by any means, electronic, mechanical, photocopying, recording, scanning or otherwise, except as permitted under Sections 107 or 108 of the 1976 United States Copyright Act, without either the prior written permission of the Publisher, or authorization through payment of the appropriate per-copy fee to the Copyright Clearance Center, 222 Rosewood Drive, Danvers, MA 01923, (978) 750-8400, fax (978) 646-8600. Requests to the Publisher for permission should be addressed to the Permissions Department, John Wiley & Sons, Inc., 111 River Street, Hoboken, NJ 07030, (201) 748-6011, fax (201) 748-6008, or online at http://www .wiley.com/go/permissions.
Limit of Liability/Disclaimer of Warranty: The publisher and the author make no representations or warranties with respect to the accuracy or completeness of the contents of this work and specifically disclaim all warranties, including without limitation warranties of fitness for a particular purpose. No warranty may be created or extended by sales or promotional materials. The advice and strategies contained herein may not be suitable for every situation. This work is sold with the understanding that the publisher is not engaged in rendering legal, accounting, or other professional services. If professional assistance is required, the services of a competent professional person should be sought. Neither the publisher nor the author shall be liable for damages arising herefrom. The fact that an organization or Web site is referred to in this work as a citation and/or a potential source of further information does not mean that the author or the publisher endorses the information the organization or Web site may provide or recommendations it may make. Further, readers should be aware that Internet Web sites listed in this work may have changed or disappeared between when this work was written and when it is read.
For general information on our other products and services please contact our Customer Care Department within the United States at (877) 762-2974, outside the United States at (317) 572-3993 or fax (317) 572-4002.
Trademarks: Wiley and the Wiley logo are trademarks or registered trademarks of John Wiley & Sons, Inc. and/or its affiliates, in the United States and other countries, and may not be used without written permission. All other trademarks are the property of their respective owners. Wiley Publishing, Inc. is not associated with any product or vendor mentioned in this book.
Wiley also publishes its books in a variety of electronic formats. Some content that appears in print may not be available in electronic books.


This book is dedicated to Cat, my rock in stormy seas, and Zack, my sunshine on a cloudy day.
About the Author
Matt Doyle, born and bred in England, discovered the joys of computing from an early age, thanks to his
mom ’ s prudent decision to invest in a rusty old build - it - yourself computer with a whopping 4K of RAM.
Since then, he ’ s never looked back, gaining a B.Sc. in Computer Science and moving into the IT industry.
After working at various companies in such disparate roles as IT manager, C programmer, software
tester, Web designer, and Web developer, Matt decided it was time to start his own business. In 1997 he
co - founded ELATED ( www.elated.com )— a company dedicated to helping people build great
Web sites.
Cutting his Web development teeth on C, Perl, and JavaScript, Matt has worked with a few other Web
programming languages over the years, including Java, ASP, and Python. PHP is his current language of
choice when building dynamic Web sites.
In 2002, deciding he ’ d had enough of the freezing English weather, he retreated to the sunny shores
of Sydney ’ s Northern Beaches in Australia with his wife, Cat. They now live in the New South Wales
Southern Highlands (which, ironically, has rather English weather) with their son, Isaac.






About the Author
Matt Doyle, born and bred in England, discovered the joys of computing from an early age, thanks to his
mom ’ s prudent decision to invest in a rusty old build - it - yourself computer with a whopping 4K of RAM.
Since then, he ’ s never looked back, gaining a B.Sc. in Computer Science and moving into the IT industry.
After working at various companies in such disparate roles as IT manager, C programmer, software
tester, Web designer, and Web developer, Matt decided it was time to start his own business. In 1997 he
co - founded ELATED ( www.elated.com )— a company dedicated to helping people build great
Web sites.
Cutting his Web development teeth on C, Perl, and JavaScript, Matt has worked with a few other Web
programming languages over the years, including Java, ASP, and Python. PHP is his current language of
choice when building dynamic Web sites.
In 2002, deciding he ’ d had enough of the freezing English weather, he retreated to the sunny shores
of Sydney ’ s Northern Beaches in Australia with his wife, Cat. They now live in the New South Wales
Southern Highlands (which, ironically, has rather English weather) with their son, Isaac.
ffirs.indd ix 9/21/09 7:22:47 PM
ffirs.indd x 9/21/09 7:22:47 PM
Credits
Executive Editor
Carol Long
Development Editor
Ed Connor
Technical Editor
Ben Schupak
Production Editor
Rebecca Anderson
Copy Editor
Kim Cofer
Editorial Manager
Mary Beth Wakefield
Production Manager
Tim Tate
Vice President and Executive Group Publisher
Richard Swadley
Vice President and Executive Publisher
Barry Pruett
Associate Publisher
Jim Minatel
Project Coordinator, Cover
Lynsey Stanford
Proofreader
Nate Pritts, Word One
Indexer
J & J Indexing
Cover Image
© Purestock/Punchstock




Acknowledgments
This book would not have been possible without the help and support of my wife Cat and my ELATED
partner - in - crime Simon. Thank you both so very much for all that you have done. Thanks also go to the
editors and managers at Wiley — particularly Ed Connor and Jenny Watson — for all their hard work
helping to knock this book into shape.

















Introduction
  1. Chapter 2 walks you through installing a copy of the PHP engine on Ubuntu Linux, Windows, and Mac
  2. OS X; looks at other ways you can install or use PHP; and shows you how to write a simple PHP script.
  3. Chapter 4 shows you how to change the flow of your scripts by creating decisions and loops. You
  4. Chapter 3 looks at some basic PHP language concepts. You look at variables, data types, operators,
  5. continue statements. You also learn how to nest loops, and how to mix decisions and looping with
  6. explore the if , else , and switch statements; the ternary operator; and the do , while , for , break , and
  7. strlen() , substr() , strstr() , strpos() , str_replace() , and printf() , to name but a few.
  8. Chapter 5 explores PHP ’ s handling of strings, or sequences of characters. You learn how to create strings;
  9. how to retrieve characters from a string; and how to manipulate strings with functions such as
  10. The rest of the chapter focuses on array manipulation, including functions such as print_r() , array_
  11. Chapter 6 covers arrays — variables that can hold multiple values. You learn the difference between
  12. indexed and associative arrays, and find out how to create arrays and access their individual elements.
  13. at how to call built - in functions, and how to work with variable functions. You also study how to create
  14. slice() , count() , sort() , array_merge() , and list() . You also learn how to create foreach loops,
  15. Chapter 7 looks at the concept of functions — blocks of code that you can use again and again. You look
  16. your own functions, including defining parameters, returning values, understanding scope, and using
  17. object - oriented approach, and learn how to build classes, properties, and methods, and how to create
  18. anonymous functions. Other function - related topics such as references and recursion are also explored.
  19. Chapter 8 delves into the world of object - oriented programming. You look at the advantages of an
  20. and use objects. You also explore more advanced topics such as overloading, inheritance, interfaces,
  21. different strategies: query strings, cookies, and PHP sessions. The chapter includes an example user
  22. Chapter 9 shows you how to use PHP to create interactive Web forms. You learn how to create HTML
  23. forms, how to capture form data in PHP, and how to use PHP to generate dynamic forms. You also
  24. Chapter 10 looks at how to preserve an application ’ s state between page views. You explore three
  25. Chapter 11 takes a look at PHP ’ s file and directory handling functions. You learn how to open and close
  26. MySQL from PHP; and study how to retrieve, insert, update, and delete data in a MySQL database.
  27. files; how to find out more information about a file; how to read from and write to files; how to work
  28. with file permissions; how to copy, rename, and delete files; and how to manipulate directories. The
  29. Chapters 12 – 14 explore databases in general and MySQL in particular, and show how to work with
  30. MySQL databases using PHP. You learn some database and SQL theory; look at how to connect to


Introduction


Chapter 15 introduces PEAR, the PHP Extension and Application Repository. It ’ s a large collection of reusable code modules that can really help to speed up your application development. You look at 
how to install and use PEAR packages, and explore three useful packages: Net_UserAgent_Detect , 
HTML_Table , and HTML_QuickForm . 
 Chapter 16 looks at various ways that your PHP applications can interact with the outside world. You take a detailed look at date and time handling, including various useful built - in date functions, as well as the DateTime and DateTimeZone classes. You also look at how to work closely with HTTP request and response headers, how to retrieve Web server information, and how to send email from within your scripts. 
 Chapter 17 shows how you can use PHP to generate graphics on the fly. You study some computer 
graphics fundamentals, then look at how to create new images, as well as modify existing images. Along the way you explore colors, drawing functions, image formats, transparency, opacity, and generating text within images. 
 Chapter 18 looks at the power of regular expressions. These clever pattern - matching tools let you search for very specific patterns of text within strings. The chapter introduces regular expression syntax, and shows how to use PHP ’ s regular expression functions to search for and replace patterns of text. Lots of examples are included to make the concepts clear. 
 Chapter 19 explores XML — eXtensible Markup Language — and shows you how to manipulate XMLfrom within your PHP scripts. You learn about XML and its uses, and look at various ways to read and write XML with PHP, including XML Parser, the XML DOM extension, and SimpleXML. You also take a brief look at XML stylesheets, including XSL and XSLT. 
 Chapter 20 wraps up the book with a discussion on good programming practices. You look at strategies for writing modular code; how to design and implement coding standards for consistency; ways to document your code; how to harden your applications against attack; how to handle errors gracefully; why it ’ s important to separate application from presentation logic; and ways to test your application code for robustness. Appendix A contains answers to the exercises found throughout the book.  Appendix B looks at how to configure PHP, and lists all the configuration directives available.  Appendix C explores some alternative databases to MySQL that are supported by PHP. 
 Appendix D shows you how to use PHP to write command - line scripts, further enhancing the power and flexibility of your applications.
What You Need to Use This Book
To work through the examples in this book you ’ ll find it helpful to install, or have access to, a Web server running PHP. Because PHP runs happily on most operating systems, including Windows, Linux, and Mac OS X, you should have no trouble installing a Web server with the PHP engine on your setup. 
Chapter 2 contains easy instructions on how to install PHP and the Apache Web server on Windows, Linux, and the Mac. You can also use a remote Web server — for example, at your Web hosting provider — to run the example scripts. Although this book covers PHP 5.3, the production version available at the time of writing was 5.2. Therefore some sections of the book — particularly Chapter 2 — contain references to version 5.2. However, as long as you install a version of PHP greater than 5.1 — whether that ’ s 5.2, 5.3, or later — you ’ ll be fine. You ’ ll need a text editor to create and edit your PHP scripts, and many decent free editors are available. Windows has the Notepad editor built in, which is fine for small projects. On the Mac you can use TextEdit, or one of the command - line editors such as vi or Emacs. Again, on Linux you can use vi, Emacs, or another command - line editor, or install one of the graphical text editors available for Linux, such as Bluefish ( http://bluefish.openoffice.nl/ ).
Using the Command Line
Some parts of the book — notably the chapters on databases, as well as Appendix D — make use of the command - line interface, or “ shell, ” to enter commands and run programs. This is a powerful tool for communicating with your system. Before rich graphical environments came into common use, the only way to interact with computers was to type commands, one line at a time. You wanted to run a program? There was no icon to click — you typed the program ’ s name. Many programs still make use of the command - line interface. For one thing, it ’ s a lot simpler to write them that way. What ’ s more, many people still find it easier to interact with the command prompt than with a mouse - driven windowed environment. In order to access the command line, you need to do one of the following: On Windows, bring up the Start menu and choose All Programs Accessories Command
❑Prompt. Alternatively, press Windows+R to call up the Run dialog, type cmd , and click OK. On Ubuntu Linux, choose Applications Accessories Terminal. (On other Linux distros or 
❑flavors of UNIX, look for a program with a name such as console, terminal, konsole, xterm, eterm, or kterm. These are all widely used shell programs that can be found on a broad range of UNIX - based systems.) On Mac OS X, double - click the Applications Utilities Terminal app in the Finder. ❑On Ubuntu Linux, choose Applications Accessories Terminal. (On other Linux distros or flavors of UNIX, look for a program with a name such as console, terminal, konsole, xterm, eterm, or kterm. These are all widely used shell programs that can be found on a broad range of UNIX - based systems.) On Mac OS X, double - click the Applications Utilities Terminal app in the Finder.
Introduction

 After you ’ ve called up the interface, you ’ ll probably be confronted by a nearly blank window, with just a 

snippet of text such as one of these:

$

%

C:/ > 

#

bash$

 This is a command prompt or shell prompt , which is simply there to let you know that the interface is ready 

to receive instructions — prompting you for commands, in effect. It doesn ’ t really matter what the 

prompt looks like, just that you recognize it when it appears. In this book, the prompt is designated 

this way:

$

 The book shows you any commands that you need to type after the prompt ($). The computer - generated 

output follows. For example:

$ ./hello.php

Hello, world!

$

 Sometimes a different prompt is shown. For example, if you ’ re working with the MySQL command - line 

program, the following prompt will be shown:

mysql > 

Conventions 

 To help you get the most from the text and keep track of what ’ s happening, we ’ ve used a number of 

conventions throughout the book. 

Try It Out

 The Try It Out section contains an exercise you should work through, following the text in the book. 

The section includes one or more code listings, instructions on how to run the script and, often, a 

screen shot showing the script in action. 

 How It Works 

 After each Try It Out , the code you ’ ve typed will be explained in detail. 

 Notes, tips, hints, tricks, and asides to the current discussion are offset and placed in italics like this. 

 As for styles in the text: 

❑ I highlight new terms and important words when I introduce them. 

xxxii

❑ I show keyboard strokes like this: Ctrl+A. 
❑ I show file names, URLs, and code within the text like so: hello.php . 
❑ I present code in two different ways:
I use gray highlighting to highlight new and important code.
I use a monofont type with no highlighting for code that’s less important, or 
that has been shown before.
Source Code 
 As you work through the examples in this book, you may choose either to type in all the code manually 
or to use the source code files that accompany the book. All of the source code used in this book is 
available for download at http://www.wrox.com . Once at the site, simply locate the book ’ s title (either 
by using the Search box or by using one of the title lists) and click the Download Code link on the book ’ s 
detail page to obtain all the source code for the book. 
 Because many books have similar titles, you may find it easiest to search by ISBN; this book ’ s ISBN is 
978 - 0 - 470 - 41396 - 8. 
 Once you download the code, just decompress it with your favorite compression tool. Alternately, you 
can go to the main Wrox code download page at http://www.wrox.com/dynamic/books/download
.aspx to see the code available for this book and all other Wrox books. 
Errata 
 We make every effort to ensure that there are no errors in the text or in the code. However, no one is 
perfect, and mistakes do occur. If you find an error in one of our books, like a spelling mistake or faulty 
piece of code, we would be very grateful for your feedback. By sending in errata you may save another 
reader hours of frustration and at the same time you will be helping us provide even higher quality 
information. 
 To find the errata page for this book, go to www.wrox.com and locate the title using the Search box or 
one of the title lists. Then, on the book details page, click the Book Errata link. On this page you can view 
all errata that has been submitted for this book and posted by Wrox editors. A complete book list 
including links to each book ’ s errata is also available at www.wrox.com/misc-pages/booklist
.shtml . 
 If you don ’ t spot “ your ” error on the Book Errata page, go to www.wrox.com/contact/techsupport
.shtml and complete the form there to send us the error you have found. We ’ ll check the information 
and, if appropriate, post a message to the book ’ s errata page and fix the problem in subsequent editions 
of the book. 
Introduction
p2p.wrox.com 
 For author and peer discussion, join the P2P forums at p2p.wrox.com . The forums are a Web - based 
system for you to post messages relating to Wrox books and related technologies and interact with other 
readers and technology users. The forums offer a subscription feature to e - mail you topics of interest of 
your choosing when new posts are made to the forums. Wrox authors, editors, other industry experts, 
and your fellow readers are present on these forums. 
 At http://p2p.wrox.com you will find a number of different forums that will help you not only as 
you read this book, but also as you develop your own applications. To join the forums, just follow 
these steps: 
 1. Go to p2p.wrox.com and click the Register link. 
 2. Read the terms of use and click Agree. 
 3. Complete the required information to join as well as any optional information you wish to 
provide and click Submit. 
 4. You will receive an e - mail with information describing how to verify your account and complete 
the joining process. 
 You can read messages in the forums without joining P2P but in order to post your own messages, you 
must join. 
 Once you join, you can post new messages and respond to messages other users post. You can read
messages at any time on the Web. If you would like to have new messages from a particular forum 
e - mailed to you, click the Subscribe to this Forum icon by the forum name in the forum listing. 
 For more information about how to use the Wrox P2P, be sure to read the P2P FAQs for answers to 
questions about how the forum software works as well as many common questions specific to P2P and 
Wrox books. To read the FAQs, click the FAQ link on any P2P page. 

Beginning PHP 5.3