php and mysql web development

984
“I’ve never purchased a better programming book… This book proved to be the most informative,easiest to follow, and had the best examples of any other computer-related book I have ever purchased.The text is very easy to follow!” —Nick Landman “…the Sams book by Welling & Thomson is the only one which I have found to be indispensable.The writing is clear and straightforward but never wastes my time.The book is extremely well laid out.The chapters are the right length and chapter titles quickly take you where you want to go.” —Wright Sullivan, President, A&E Engineering, Inc., Greer South Carolina “I just wanted to tell you that I think the book PHP and MySQL Web Development rocks! It’s logically structured, just the right difficulty level for me (intermediate), interesting and easy to read, and, of course, full of valuable information!” —CodE-E, Austria “There are several good introductory books on PHP,but Welling & Thomson is an excellent handbook for those who wish to build up complex and reliable systems. It’s obvious that the authors have a strong back- ground in the development of professional applications and they teach not only the language itself, but also how to use it with good software engineering practices.” —Javier Garcia, senior telecom engineer, Telefonica R&D Labs, Madrid “I picked up this book two days ago and I am half way finished. I just can’t put it down.The layout and flow is perfect. Everything is presented in such a way so that the information is very palatable. I am able to immediately grasp all the concepts. The examples have also been wonderful. I just had to take some time out to express to you how pleased I have been with this book.” —Jason B. Lancaster “This book has proven a trusty companion, with an excellent crash course in PHP and superb coverage of MySQL as used for Web applications. It also features several complete applications that are great examples of how to construct modular, scalable applications with PHP.Whether you are a PHP newbie or a veteran in search of a better desk-side reference, this one is sure to please!” —WebDynamic “The true PHP/MySQL bible, PHP and MySQL Web Development by Luke Welling and Laura Thomson, made me realize that programming and databases are now available to the commoners.Again, I know 1/10000th of what there is to know, and already I’m enthralled.” —Tim Luoma,TnTLuoma.com “Welling and Thomson’s book is a good reference for those who want to get to grips with practical projects straight off the bat. It includes webmail, shopping cart, session control, and web-forum/weblog applications as a matter of course, and begins with a sturdy look at PHP first, moving to MySQL once the basics are covered.” —twilight30 on Slashdot

Upload: laura-thomson

Post on 08-Dec-2016

262 views

Category:

Documents


10 download

TRANSCRIPT

  • Ive never purchased a better programming book This book proved tobe the most informative, easiest to follow,and had the best examples of any othercomputer-related book I have ever purchased.The text is very easy to follow!

    Nick Landman

    the Sams book by Welling &Thomson is the only one which I havefound to be indispensable.The writing isclear and straightforward but never wastesmy time.The book is extremely well laidout.The chapters are the right length andchapter titles quickly take you where youwant to go.

    Wright Sullivan, President,A&EEngineering, Inc., Greer South Carolina

    I just wanted to tell you that I think thebook PHP and MySQL Web Developmentrocks! Its logically structured, just the rightdifficulty level for me (intermediate),interesting and easy to read, and, of course,full of valuable information!

    CodE-E,Austria

    There are several good introductorybooks on PHP, but Welling & Thomson is anexcellent handbook for those who wish tobuild up complex and reliable systems. Itsobvious that the authors have a strong back-ground in the development of professionalapplications and they teach not only the language itself, but also how to use itwith good software engineering practices.

    Javier Garcia, senior telecom engineer,Telefonica R&D Labs, Madrid

    I picked up this book two days agoand I am half way finished. I just cant putit down.The layout and flow is perfect.Everything is presented in such a way sothat the information is very palatable. I amable to immediately grasp all the concepts.The examples have also been wonderful.I just had to take some time out to expressto you how pleased I have been with this book.

    Jason B. Lancaster

    This book has proven a trusty companion, with an excellent crash coursein PHP and superb coverage of MySQL asused for Web applications. It also featuresseveral complete applications that are greatexamples of how to construct modular,scalable applications with PHP.Whetheryou are a PHP newbie or a veteran insearch of a better desk-side reference, thisone is sure to please!

    WebDynamic

    The true PHP/MySQL bible, PHPand MySQL Web Development by LukeWelling and Laura Thomson, made merealize that programming and databases arenow available to the commoners.Again, Iknow 1/10000th of what there is to know,and already Im enthralled.

    Tim Luoma,TnTLuoma.com

    Welling and Thomsons book is a goodreference for those who want to get togrips with practical projects straight off thebat. It includes webmail, shopping cart,session control, and web-forum/weblogapplications as a matter of course, andbegins with a sturdy look at PHP first,moving to MySQL once the basics are covered.

    twilight30 on Slashdot

    00 6728 fm 9/2/04 1:15 PM Page i

  • This book is absolutely excellent, tosay the least. Luke Welling and LauraThomson give the best in-depth explana-tions Ive come across on such things asregular expressions, classes and objects,sessions etc. I really feel this book filled in alot of gaps for me with things I didnt quite understand.This book jumps right intothe functions and features most commonlyused with PHP, and from there it continuesin describing real-world projects, MySQLintegration, and security issues from a proj-ect managers point of view. I found everybit of this book to be well organized andeasy to understand.

    notepad on codewalkers.com

    A top-notch reference for programmers using PHP and MySQL.Highly recommended.

    The Internet Writing Journal

    This book rocks! I am an experienced programmer, so I didnt need a lot of helpwith PHP syntax; after all, its very close toC/C++. I dont know a thing about databases, though, so when I wanted todevelop a book review engine (amongother projects) I wanted a solid reference to using MySQL with PHP. I haveOReillys mSQL and MySQL book, andits probably a better pure-SQL reference,but this book has earned a place on my reference shelfHighly recommended.

    Paul Robichaux

    One of the best programming guidesIve ever read.

    jackofsometrades from Lahti, Finland

    This is a well-written book for learn-ing how to build Internet applications withtwo of the most popular open-source Webdevelopment technologies.The projectsare the real jewel of the book. Not only arethe projects described and constructed in alogical, component-based manner, but theselection of projects represents an excellentcross-section of common components thatare built into many web sites.

    Craig Cecil

    The book takes an easy, step-by-stepapproach to introduce even the cluelessprogrammer to the language of PHP. Ontop of that, I often find myself referringback to it in my Web design efforts. Im stilllearning new things about PHP, but thisbook gave me a solid foundation fromwhich to start and continues to help me tothis day.

    Stephen Ward

    This book is one of few that reallytouched me and made me love it. I cantput it in my bookshelf; I must put it in atouchable place on my working bench as Ialways like to refer from it. Its structure isgood, wordings are simple and straight for-ward, and examples are clear and step bystep. Before I read it, I knew nothing ofPHP and MySQL.After reading it, I havethe confidence and skill to develop anycomplicated Web application.

    Power Wong

    This book is God. I highly recom-mend this book to anyone who wants tojump in the deep end with database drivenWeb application programming. I wish morecomputer books were organized this way.

    Sean C Schertell

    00 6728 fm 9/2/04 1:15 PM Page ii

  • PHP and MySQLWeb Development

    Sams Publishing, 800 East 96th Street, Indianapolis, Indiana 46240

    DEVELOPERS LIBRARY

    Luke WellingLaura Thomson

    Third Edition

    00 6728 fm 9/2/04 1:15 PM Page iii

  • PHP and MySQL Web DevelopmentThird EditionCopyright 2005 by Sams Publishing

    All rights reserved. No part of this book shall be reproduced, stored in aretrieval system, or transmitted by any means, electronic, mechanical, photo-copying, recording, or otherwise, without written permission from the pub-lisher. No patent liability is assumed with respect to the use of the informa-tion contained herein.Although every precaution has been taken in thepreparation of this book, the publisher and authors assume no responsibilityfor errors or omissions. Neither is any liability assumed for damages resultingfrom the use of the information contained herein.

    International Standard Book Number: 0-672-32672-8

    Library of Congress Catalog Card Number: 2003099244

    Printed in the United States of America

    First Printing: October 2004

    07 06 05 04 4 3 2 1

    TrademarksAll terms mentioned in this book that are known to be trademarks or servicemarks have been appropriately capitalized. Sams Publishing cannot attest tothe accuracy of this information. Use of a term in this book should not beregarded as affecting the validity of any trademark or service mark.

    Warning and DisclaimerEvery effort has been made to make this book as complete and as accurate aspossible, but no warranty or fitness is implied.The information provided ison an as is basis.The authors and the publisher shall have neither liabilitynor responsibility to any person or entity with respect to any loss or damagesarising from the information contained in this book or from the use of theCD-ROM or programs accompanying it.

    Bulk SalesSams Publishing offers excellent discounts on this book when ordered inquantity for bulk purchases or special sales. For more information, pleasecontact

    U.S. Corporate and Government [email protected]

    For sales outside the U.S., please contact

    International [email protected]

    Acquisitions EditorShelley Johnston

    Development EditorScott Meyers

    Managing EditorCharlotte Clapp

    Copy EditorChuck Hutchinson

    IndexerMandie Frank

    ProofreaderPaula Lowell

    Technical EditorsSara GolemonChris Newman

    Media SpecialistDan Scherf

    DesignGary Adair

    Page LayoutCheryl LynchMichelle Mitchell

    00 6728 fm 9/2/04 1:15 PM Page iv

  • To our Mums and Dads

    00 6728 fm 9/2/04 1:15 PM Page v

  • Contents at a GlanceIntroduction 1

    I Using PHP

    1 PHP Crash Course 11

    2 Storing and Retrieving Data 57

    3 Using Arrays 79

    4 String Manipulation and Regular Expressions 105

    5 Reusing Code and Writing Functions 129

    6 Object-Oriented PHP 157

    7 Exception Handling 191

    II Using MySQL

    8 Designing Your Web Database 205

    9 Creating Your Web Database 217

    10 Working with Your MySQL Database 241

    11 Accessing Your MySQL Database from the Web with PHP 265

    12 Advanced MySQL Administration 285

    13 Advanced MySQL Programming 307

    III E-commerce and Security

    14 Running an E-commerce Site 323

    15 E-commerce Security Issues 337

    16 Implementing Authentication with PHP andMySQL 357

    17 Implementing Secure Transactions with PHP andMySQL 379

    00 6728 fm 9/2/04 1:15 PM Page vi

  • IV Advanced PHP Techniques

    18 Interacting with the File System and the Server401

    19 Using Network and Protocol Functions 419

    20 Managing the Date and Time 439

    21 Generating Images 451

    22 Using Session Control in PHP 479

    23 Other Useful Features 495

    V Building Practical PHP and MySQL Projects

    24 Using PHP and MySQL for Large Projects 507

    25 Debugging 523

    26 Building User Authentication and Personalization541

    27 Building a Shopping Cart 579

    28 Building a Content Management System 625

    29 Building a Web-Based Email Service 657

    30 Building a Mailing List Manager 695

    31 Building Web Forums 751

    32 Generating Personalized Documents in PortableDocument Format (PDF) 783

    33 Connecting to Web Services with XML and SOAP819

    VI Appendixes

    A Installing PHP and MySQL 867

    B Web Resources 889

    Index 893

    00 6728 fm 9/2/04 1:15 PM Page vii

  • Table of Contents

    Introduction 1

    I Using PHP

    1 PHP Crash Course 11Using PHP 12Creating a Sample Application: Bobs Auto Parts 12

    Creating the Order Form 12Processing the Form 14

    Embedding PHP in HTML 15Use of PHP Tags 16PHP Tag Styles 16PHP Statements 17Whitespace 18Comments 18

    Adding Dynamic Content 19Calling Functions 20Using the date() Function 20

    Accessing Form Variables 21Form Variables 21String Concatenation 24Variables and Literals 25

    Understanding Identifiers 26Creating User-Declared Variables 26Assigning Values to Variables 26Examining Variable Types 27

    PHPs Data Types 27Type Strength 27Type Casting 28Variable Variables 28

    Declaring and Using Constants 29Understanding Variable Scope 29

    00 6728 fm 9/2/04 1:15 PM Page viii

  • Using Operators 30Arithmetic Operators 31String Operators 32Assignment Operators 32Comparison Operators 34Logical Operators 36Bitwise Operators 36Other Operators 37

    Using Operators:Working Out the Form Totals 39Understanding Precedence and Associativity:Evaluating Expressions 40Using Variable Functions 42

    Testing and Setting Variable Types 42Testing Variable Status 43Reinterpreting Variables 44

    Implementing Control Structures 44Making Decisions with Conditionals 44

    if Statements 44Code Blocks 45else Statements 45elseif Statements 46switch Statements 47Comparing the Different Conditionals 49

    Repeating Actions Through Iteration 49while Loops 51for and foreach Loops 52do..while Loops 53

    Breaking Out of a Control Structure or Script 54Employing Alternative Control Structure Syntax 54Using declare 55Next: Saving the Customers Order 55

    2 Storing and Retrieving Data 57Saving Data for Later 57Storing and Retrieving Bobs Orders 58Processing Files 59

    00 6728 fm 9/2/04 1:15 PM Page ix

  • x Contents

    Opening a File 59Choosing File Modes 59Using fopen() to Open a File 60Opening Files Through FTP or HTTP 62Addressing Problems Opening Files 63

    Writing to a File 65Parameters for fwrite() 66File Formats 66

    Closing a File 67Reading from a File 69

    Opening a File for Reading: fopen() 70Knowing When to Stop: feof() 71Reading a Line at a Time: fgets(), fgetss(),and fgetcsv() 71Reading the Whole File: readfile(),fpassthru(), and file() 72Reading a Character: fgetc() 73Reading an Arbitrary Length: fread() 73

    Using Other Useful File Functions 74Checking Whether a File Is There:file_exists() 74Determining How Big a File Is: filesize()74Deleting a File: unlink() 74Navigating Inside a File: rewind(), fseek(),and ftell() 74

    Locking Files 76Doing It a Better Way: Database Management Systems 77

    Problems with Using Flat Files 77How RDBMSs Solve These Problems 78

    Further Reading 78Next 78

    3 Using Arrays 79What Is an Array? 79Numerically Indexed Arrays 80

    Initializing Numerically Indexed Arrays 80Accessing Array Contents 81Using Loops to Access the Array 82

    00 6728 fm 9/2/04 1:15 PM Page x

  • xiContents

    Arrays with Different Indices 83Initializing an Array 83Accessing the Array Elements 83Using Loops 83

    Array Operators 85Multidimensional Arrays 86Sorting Arrays 90

    Using sort() 90Using asort() and ksort() to Sort Arrays91Sorting in Reverse 91

    Sorting Multidimensional Arrays 91User-Defined Sorts 91Reverse User Sorts 93

    Reordering Arrays 94Using shuffle() 94Using array_reverse() 96

    Loading Arrays from Files 96Performing Other Array Manipulations 100

    Navigating Within an Array: each(),current(), reset(), end(), next(), pos(),and prev() 100Applying Any Function to Each Element in anArray: array_walk() 101Counting Elements in an Array: count(),sizeof(), and array_count_values() 102Converting Arrays to Scalar Variables: extract()103

    Further Reading 104Next 104

    4 String Manipulation and RegularExpressions 105Creating a Sample Application: Smart Form Mail 105Formatting Strings 107

    Trimming Strings: chop(), ltrim(), andtrim() 108Formatting Strings for Presentation 108Formatting Strings for Storage: addslashes()and stripslashes() 112

    00 6728 fm 9/2/04 1:15 PM Page xi

  • xii Contents

    Joining and Splitting Strings with String Functions113

    Using explode(), implode(), and join()114Using strtok() 114Using substr() 115

    Comparing Strings 116Performing String Ordering: strcmp(),strcasecmp(), and strnatcmp() 116Testing String Length with strlen() 117

    Matching and Replacing Substrings with StringFunctions 117

    Finding Strings in Strings: strstr(), strchr(),strrchr(), and stristr() 118Finding the Position of a Substring: strpos()and strrpos() 118Replacing Substrings: str_replace() andsubstr_replace() 119

    Introducing Regular Expressions 121The Basics 121Character Sets and Classes 121Repetition 123Subexpressions 123Counted Subexpressions 123Anchoring to the Beginning or End of a String 123Branching 124Matching Literal Special Characters 124Reviewing the Special Characters 124Putting It All Together for the Smart Form 125

    Finding Substrings with Regular Expressions 126Replacing Substrings with Regular Expressions 127Splitting Strings with Regular Expressions 127Comparing String Functions and Regular ExpressionFunctions 127Further Reading 128Next 128

    00 6728 fm 9/2/04 1:15 PM Page xii

  • xiiiContents

    5 Reusing Code and Writing Functions 129Reusing Code 129

    Cost 130Reliability 130Consistency 130

    Using require() and include() 130require() 131Filename Extensions and require() 132PHP Tags and require() 132

    Using require() for Website Templates 133Using include() 138Using require_once() and include_once()138Using auto_prepend_file andauto_append_file 138

    Using Functions in PHP 139Calling Functions 139Calling an Undefined Function 141Understanding Case and Function Names 142

    Understanding Why You Should Define Your OwnFunctions 142Examining Basic Function Structure 142

    Naming Your Function 143Using Parameters 144Understanding Scope 146Passing by Reference Versus Passing by Value 149Returning from Functions 150Returning Values from Functions 151

    Code Blocks 152Implementing Recursion 153Further Reading 155Next 155

    6 Object-Oriented PHP 157Understanding Object-Oriented Concepts 158

    Classes and Objects 158Polymorphism 159Inheritance 160

    00 6728 fm 9/2/04 1:15 PM Page xiii

  • xiv Contents

    Creating Classes,Attributes, and Operations in PHP 160

    Structure of a Class 160Constructors 161Destructors 161

    Instantiating Classes 162Using Class Attributes 162Controlling Access with private and public 164Calling Class Operations 165Implementing Inheritance in PHP 166

    Controlling Visibility Through Inheritance withprivate and protected 167Overriding 168Preventing Inheritance and Overriding with final 170Understanding Multiple Inheritance 171Implementing Interfaces 171

    Designing Classes 172Writing the Code for Your Class 173Understanding Advanced and New Object-OrientedFunctionality in PHP 181

    Note: PHP4 Versus PHP5 182Using Per-Class Constants 182Implementing Static Methods 182Checking Class Type and Type Hinting 183Cloning Objects 184Using Abstract Classes 184Overloading Methods with __call() 184Using __autoload() 185Implementing Iterators and Iteration 186Converting Your Classes to Strings 188Using the Reflection API 188

    Next 190

    7 Exception Handling 191Exception Handling Concepts 191The Exception Class 193

    00 6728 fm 9/2/04 1:15 PM Page xiv

  • xvContents

    User-Defined Exceptions 194Exceptions in Bobs Auto Parts 197Exceptions and PHPs Other Error HandlingMechanisms 200Further Reading 201Next 201

    II Using MySQL

    8 Designing Your Web Database 205Relational Database Concepts 206

    Tables 206Columns 207Rows 207Values 207Keys 207Schemas 208Relationships 209

    How to Design Your Web Database 209Think About the Real-World Objects You AreModeling 209Avoid Storing Redundant Data 210Use Atomic Column Values 212Choose Sensible Keys 213Think About the Questions You Want to Ask theDatabase 213Avoid Designs with Many Empty Attributes 213Summary of Table Types 214

    Web Database Architecture 214Architecture 214

    Further Reading 216Next 216

    9 Creating Your Web Database 217Using the MySQL Monitor 218Logging In to MySQL 219

    00 6728 fm 9/2/04 1:15 PM Page xv

  • xvi Contents

    Creating Databases and Users 220Creating the Database 220

    Setting Up Users and Privileges 221Introducing MySQLs Privilege System 221

    Principle of Least Privilege 221User Setup:The GRANT Command 221Types and Levels of Privileges 223The REVOKE Command 225Examples Using GRANT and REVOKE 225

    Setting Up a User for the Web 226Logging Out as root 227

    Using the Right Database 227Creating Database Tables 227

    Understanding What the Other Keywords Mean229Understanding the Column Types 230Looking at the Database with SHOW andDESCRIBE 231Creating Indexes 232A Note on Table Types 233

    Understanding MySQL Identifiers 233Choosing Column Data Types 234

    Numeric Types 235Further Reading 239Next 239

    10 Working with Your MySQL Database 241What Is SQL? 241Inserting Data into the Database 242Retrieving Data from the Database 244

    Retrieving Data with Specific Criteria 246Retrieving Data from Multiple Tables 247Retrieving Data in a Particular Order 253Grouping and Aggregating Data 254Choosing Which Rows to Return 256Using Subqueries 256

    Updating Records in the Database 259

    00 6728 fm 9/2/04 1:15 PM Page xvi

  • xviiContents

    Altering Tables After Creation 259Deleting Records from the Database 262Dropping Tables 262Dropping a Whole Database 262Further Reading 263Next 263

    11 Accessing Your MySQL Database from theWeb with PHP 265How Web Database Architectures Work 266Querying a Database from the Web 269Checking and Filtering Input Data 270Setting Up a Connection 271Choosing a Database to Use 272Querying the Database 272Retrieving the Query Results 273Disconnecting from the Database 274Putting New Information in the Database 275Using Prepared Statements 278Using Other PHP-Database Interfaces 280Using a Generic Database Interface: PEAR DB 280Further Reading 283Next 283

    12 Advanced MySQL Administration 285Understanding the Privilege System in Detail 285

    The userTable 286The db and hostTables 288The tables_priv and columns_privTables289Access Control: How MySQL Uses the GrantTables 290Updating Privileges:When Do Changes TakeEffect? 290

    Making Your MySQL Database Secure 291MySQL from the Operating Systems Point ofView 291Passwords 291

    00 6728 fm 9/2/04 1:15 PM Page xvii

  • xviii Contents

    User Privileges 292Web Issues 293

    Getting More Information About Databases 293Getting Information with SHOW 293Getting Information About Columns withDESCRIBE 296Understanding How Queries Work withEXPLAIN 296

    Speeding Up Queries with Indexes 301Optimizing Your Database 301

    Design Optimization 301Permissions 301Table Optimization 301Using Indexes 302Using Default Values 302Other Tips 302

    Backing Up Your MySQL Database 302Restoring Your MySQL Database 303Implementing Replication 303

    Setting Up the Master 304Performing the Initial Data Transfer 304Setting Up the Slave or Slaves 305

    Further Reading 306Next 306

    13 Advanced MySQL Programming 307The LOAD DATA INFILE Statement 307Storage Engines 308Transactions 309

    Understanding Transaction Definitions 309Using Transactions with InnoDB 310

    Foreign Keys 311Stored Procedures 312

    Basic Example 312Local Variables 315Cursors and Control Structures 315

    00 6728 fm 9/2/04 1:15 PM Page xviii

  • xixContents

    Further Reading 319Next 319

    III E-commerce and Security

    14 Running an E-commerce Site 323Deciding What You Want to Achieve 323Considering the Types of Commercial Websites 323

    Publishing Information Using Online Brochures324Taking Orders for Goods or Services 327Providing Services and Digital Goods 330Adding Value to Goods or Services 331Cutting Costs 331

    Understanding Risks and Threats 332Crackers 333Failure to Attract Sufficient Business 333Computer Hardware Failure 333Power, Communication, Network, or ShippingFailures 334Extensive Competition 334Software Errors 334Evolving Governmental Policies and Taxes 335System Capacity Limits 335

    Deciding on a Strategy 335Next 335

    15 E-commerce Security Issues 337How Important Is Your Information? 338Security Threats 338

    Exposure of Confidential Data 339Loss or Destruction of Data 340Modification of Data 341Denial of Service 342Errors in Software 343Repudiation 344

    Usability, Performance, Cost, and Security 345

    00 6728 fm 9/2/04 1:15 PM Page xix

  • xx Contents

    Security Policy Creation 345Authentication Principles 346Authentication 347Encryption Basics 347Private Key Encryption 349Public Key Encryption 349Digital Signatures 350Digital Certificates 351Secure Web Servers 352Auditing and Logging 353Firewalls 353Data Backups 354

    Backing Up General Files 354Backing Up and Restoring Your MySQLDatabase 354

    Physical Security 355Next 355

    16 Implementing Authentication with PHP andMySQL 357Identifying Visitors 357Implementing Access Control 358

    Storing Passwords 361Encrypting Passwords 364Protecting Multiple Pages 365

    Using Basic Authentication 366Using Basic Authentication in PHP 367Using Basic Authentication with Apaches .htaccess Files 369Using Basic Authentication with IIS 373Using mod_auth_mysql Authentication 375

    Installing mod_auth_mysql 375Did It Work? 376Using mod_auth_mysql 376

    Creating Your Own Custom Authentication 377Further Reading 378Next 378

    00 6728 fm 9/2/04 1:15 PM Page xx

  • xxiContents

    17 Implementing Secure Transactions withPHP and MySQL 379Providing Secure Transactions 379

    The Users Machine 380The Internet 381Your System 382

    Using Secure Sockets Layer (SSL) 383Screening User Input 387Providing Secure Storage 387Determining Whether to Store Credit Card Numbers389Using Encryption in PHP 389Further Reading 397Next 398

    IV Advanced PHP Techniques

    18 Interacting with the File System and theServer 401Uploading Files 401

    HTML for File Upload 402A Note on Security 403Writing the PHP to Deal with the File 403Common Problems 407

    Using Directory Functions 408Reading from Directories 408Getting Information About the CurrentDirectory 410Creating and Deleting Directories 410

    Interacting with the File System 411Getting File Information 411Changing File Properties 414Creating, Deleting, and Moving Files 414

    Using Program Execution Functions 415Interacting with the Environment: getenv() andputenv() 417Further Reading 418Next 418

    00 6728 fm 9/2/04 1:15 PM Page xxi

  • xxii Contents

    19 Using Network and Protocol Functions 419Examining Available Protocols 419Sending and Reading Email 420Using Other Websites 420Using Network Lookup Functions 424Using FTP 428

    Using FTP to Back Up or Mirror a File 428Uploading Files 435Avoiding Timeouts 435Using Other FTP Functions 436

    Further Reading 437Next 437

    20 Managing the Date and Time 439Getting the Date and Time from PHP 439

    Using the date() Function 439Dealing with Unix Timestamps 441Using the getdate() Function 442Validating Dates 443

    Converting Between PHP and MySQL Date Formats444Calculating Dates in PHP 445Calculating Dates in MySQL 446Using Microseconds 448Using the Calendar Functions 448Further Reading 449Next 449

    21 Generating Images 451Setting Up Image Support in PHP 452Understanding Image Formats 452

    JPEG 452PNG 453WBMP 453GIF 453

    00 6728 fm 9/2/04 1:15 PM Page xxii

  • xxiiiContents

    Creating Images 454Creating a Canvas Image 455Drawing or Printing Text on the Image 456Outputting the Final Graphic 458Cleaning Up 459

    Using Automatically Generated Images in Other Pages 459Using Text and Fonts to Create Images 460

    Setting Up the Base Canvas 463Fitting the Text onto the Button 464Positioning the Text 467Writing the Text onto the Button 467Finishing Up 468

    Drawing Figures and Graphing Data 468Using Other Image Functions 476Further Reading 477Next 477

    22 Using Session Control in PHP 479What Session Control Is 479Understanding Basic Session Functionality 479

    What Is a Cookie? 480Setting Cookies from PHP 480Using Cookies with Sessions 481Storing the Session ID 481

    Implementing Simple Sessions 482Starting a Session 482Registering Session Variables 482Using Session Variables 483Unsetting Variables and Destroying the Session483

    Creating a Simple Session Example 484Configuring Session Control 486Implementing Authentication with Session Control 487Further Reading 493Next 494

    00 6728 fm 9/2/04 1:15 PM Page xxiii

  • xxiv Contents

    23 Other Useful Features 495Using Magic Quotes 495Evaluating Strings: eval() 496Terminating Execution: die and exit 497Serializing Variables and Objects 497Getting Information About the PHP Environment 499

    Finding Out What Extensions Are Loaded 499Identifying the Script Owner 500Finding Out When the Script Was Modified500

    Loading Extensions Dynamically 500Temporarily Altering the Runtime Environment 500Highlighting Source Code 501Using PHP on the Command Line 502Next 503

    V Building Practical PHP and MySQLProjects

    24 Using PHP and MySQL for Large Projects 507Applying Software Engineering to Web Develop-ment 508Planning and Running a Web Application Project 508Reusing Code 509Writing Maintainable Code 510

    Coding Standards 510Breaking Up Code 513Using a Standard Directory Structure 514Documenting and Sharing In-House Functions 514

    Implementing Version Control 514Choosing a Development Environment 516Documenting Your Projects 516Prototyping 517

    00 6728 fm 9/2/04 1:15 PM Page xxiv

  • xxvContents

    Separating Logic and Content 518Optimizing Code 518

    Using Simple Optimizations 519Using Zend Products 519

    Testing 520Further Reading 521Next 521

    25 Debugging 523Programming Errors 523

    Syntax Errors 524Runtime Errors 525Logic Errors 530

    Variable Debugging Aid 531Error Reporting Levels 533Altering the Error Reporting Settings 534Triggering Your Own Errors 536Handling Errors Gracefully 536Next 539

    26 Building User Authentication andPersonalization 541The Problem 541Solution Components 542

    User Identification and Personalization 542Storing Bookmarks 543Recommending Bookmarks 543

    Solution Overview 543Implementing the Database 545Implementing the Basic Site 546Implementing User Authentication 549

    Registering 549Logging In 556Logging Out 560Changing Passwords 561Resetting Forgotten Passwords 563

    00 6728 fm 9/2/04 1:15 PM Page xxv

  • xxvi Contents

    Implementing Bookmark Storage and Retrieval 568Adding Bookmarks 568Displaying Bookmarks 570Deleting Bookmarks 571

    Implementing Recommendations 574Wrapping Up and Considering Possible Exten-sions 578Next 578

    27 Building a Shopping Cart 579The Problem 579Solution Components 580

    Building an Online Catalog 580Tracking Users Purchases While They Shop 580Implementing a Payment System 580Building an Administration Interface 581

    Solution Overview 581Implementing the Database 585Implementing the Online Catalog 587

    Listing Categories 589Listing Books in a Category 592Showing Book Details 594

    Implementing the Shopping Cart 595Using the show_cart.php Script 596Viewing the Cart 599Adding Items to the Cart 602Saving the Updated Cart 604Printing a Header Bar Summary 604Checking Out 605

    Implementing Payment 611Implementing an Administration Interface 613Extending the Project 622Using an Existing System 622Next 623

    00 6728 fm 9/2/04 1:15 PM Page xxvi

  • xxviiContents

    28 Building a Content Management System 625The Problem 625Solution Requirements 626Existing Systems 626Editing Content 626

    Getting Content into the System 626Databases Versus File Storage 627Document Structure 627

    Using Metadata 628Formatting the Output 629Solution Design/Overview 630Designing the Database 631Implementing the CMS 633

    Front End 633Back End 640Searches 650Editor Screen 653

    Extending the Project 655Next 655

    29 Building a Web-Based Email Service 657The Problem 657Solution Components 658Solution Overview 659Setting Up the Database 661Examining the Script Architecture 663Logging In and Out 669Setting Up Accounts 672

    Creating a New Account 674Modifying an Existing Account 676Deleting an Account 676

    Reading Mail 677Selecting an Account 677Viewing Mailbox Contents 680Reading a Mail Message 683

    00 6728 fm 9/2/04 1:15 PM Page xxvii

  • xxviii Contents

    Viewing Message Headers 686Deleting Mail 687

    Sending Mail 688Sending a New Message 688Replying To or Forwarding Mail 691

    Extending the Project 692Next 693

    30 Building a Mailing List Manager 695The Problem 695Solution Components 696

    Setting Up a Database of Lists and Subscribers 696Using File Upload 696Sending Mail with Attachments 697

    Solution Overview 697Setting Up the Database 700Defining the Script Architecture 702Implementing Login 711

    Creating a New Account 711Logging In 714

    Implementing User Functions 717Viewing Lists 717Viewing List Information 723Viewing List Archives 725Subscribing and Unsubscribing 726Changing Account Settings 728Changing Passwords 728Logging Out 730

    Implementing Administrative Functions 731Creating a New List 731Uploading a New Newsletter 734Handling Multiple File Upload 736Previewing the Newsletter 741Sending the Message 743

    Extending the Project 749Next 750

    00 6728 fm 9/2/04 1:15 PM Page xxviii

  • xxixContents

    31 Building Web Forums 751The Problem 751Solution Components 752Solution Overview 753Designing the Database 754Viewing the Tree of Articles 757

    Expanding and Collapsing 759Displaying the Articles 762Using the treenode Class 763

    Viewing Individual Articles 770Adding New Articles 773Adding Extensions 780Using an Existing System 780Next 781

    32 Generating Personalized Documents inPortable Document Format (PDF) 783The Problem 783

    Evaluating Document Formats 784Solution Components 788

    Question and Answer System 788Document Generation Software 788

    Solution Overview 791Asking the Questions 792Grading the Answers 794Generating an RTF Certificate 796Generating a PDF Certificate from a Template800Generating a PDF Document Using PDFlib803A Hello World Script for PDFlib 803Generating a Certificate with PDFlib 808

    Handling Problems with Headers 816Extending the Project 817Further Reading 817Next 817

    00 6728 fm 9/2/04 1:15 PM Page xxix

  • xxx Contents

    33 Connecting to Web Services with XML andSOAP 819The Problem 819

    Understanding XML 820Understanding Web Services 824

    Solution Components 826Building a Shopping Cart 826Using Amazons Web Services Interfaces 826Parsing XML 827Using SOAP with PHP 827Caching 828

    Solution Overview 828Core Application 833Showing Books in a Category 839Getting an AmazonResultSet Class 841Using REST/XML Over HTTP 849Using SOAP 854Caching the Data 856Building the Shopping Cart 858Checking Out to Amazon 862

    Installing the Project Code 863Extending the Project 863Further Reading 864

    VI Appendixes

    A Installing PHP and MySQL 867Running PHP as a CGI Interpreter or Module 868Installing Apache, PHP, and MySQL Under Unix 868

    Binary Installation 868Source Installation 868httpd.conf File: Snippets 875Is PHP Support Working? 876Is SSL Working? 877

    00 6728 fm 9/2/04 1:15 PM Page xxx

  • xxxiContents

    Installing Apache, PHP, and MySQL Under Windows878

    Installing MySQL Under Windows 879Installing Apache Under Windows 882Installing PHP for Windows 884

    Installing PEAR 887Setting Up Other Configurations 888

    B Web Resources 889PHP Resources 889MySQL and SQL Specific Resources 891Apache Resources 891Web Development 892

    Index 893

    00 6728 fm 9/2/04 1:15 PM Page xxxi

  • About the AuthorsLaura Thomson is a lecturer in the School of Computer Science and InformationTechnology at RMIT University in Melbourne,Australia. She is also a partner in theaward-winning web development firm Tangled Web Design. Laura has previously workedfor Telstra and the Boston Consulting Group. She holds a Bachelor of Applied Science(Computer Science) degree and a Bachelor of Engineering (Computer SystemsEngineering) degree with honors, and is currently completing her Ph.D. in AdaptiveWeb Sites. In her spare time, she enjoys sleeping. Laura can be reached via email [email protected].

    Luke Welling is a senior web developer at MySQL AB, the company behind theMySQL database. He has previously taught engineering and computer science at RMITUniversity in Melbourne,Australia and worked as a computer programmer for manyyears. He holds a Bachelor of Applied Science (Computer Science) degree. In his spare time, he attempts to perfect his insomnia. Luke can be reached via email [email protected].

    Both authors have attained the MySQL Core Certification offered by MySQL AB andthe Zend Certified PHP Engineer offered by Zend Technologies Ltd.

    About the ContributorsIsrael Denis Jr. is a freelance consultant working on e-commerce projects throughoutthe world. He specializes in integrating ERP packages such as SAP and Lawson withcustom web solutions.When he is not busy designing software or writing books, Israelenjoys traveling to Italy, a place he considers home. Israel obtained a masters degree inElectrical Engineering from Georgia Tech in Atlanta, Georgia, in 1998. He is the authorof numerous articles about Linux,Apache, PHP, and MySQL. He has worked for compa-nies such as GE and Procter & Gamble with mainly Unix-based computer systems. Israelcan be reached via email at [email protected].

    Chris Newman is a consultant programmer specializing in the development of dynam-ic Internet applications. He has extensive commercial experience using PHP andMySQL to produce a wide range of applications for an international client base.A grad-uate of Keele University, Chris lives in Stoke-on-Trent, England, where he runsLightwood Consultancy Ltd., the company he founded in 1999 to further his interest inInternet development. Chris became fascinated with the potential of the Internet whileat the university and is thrilled to be working with cutting-edge technology. More infor-mation on Lightwood Consultancy Ltd. can be found at http://www.lightwood.net, andChris can be contacted at [email protected].

    00 6728 fm 9/2/04 1:15 PM Page xxxii

  • AcknowledgmentsWe would like to thank the team at Sams for all their hard work. In particular, we wouldlike to thank Shelley Johnston without whose dedication and patience this book wouldnot have been possible.We would also like to thank Israel Denis Jr. and Chris Newmanfor their valuable contributions.

    We appreciate immensely the work done by the PHP and MySQL developmentteams.Their work has made our lives easier for a number of years now and continues todo so on a daily basis.

    We thank Adrian Close at eSec for saying You can build that in PHP back in 1998.He said we would like PHP, and it seems he was right.

    Finally, we would like to thank our family and friends for putting up with us whilewe have been repeatedly antisocial while working on books. Specifically, thank you foryour support to our family members: Julie, Robert, Martin, Lesley,Adam, Paul,Archer,and Barton.

    00 6728 fm 9/2/04 1:15 PM Page xxxiii

  • We Want to Hear from You!As the reader of this book, you are our most important critic and commentator.We valueyour opinion and want to know what were doing right, what we could do better, whatareas youd like to see us publish in, and any other words of wisdom youre willing topass our way.

    You can email or write me directly to let me know what you did or didnt like aboutthis bookas well as what we can do to make our books stronger.

    Please note that I cannot help you with technical problems related to the topic of this book, andthat due to the high volume of mail I receive, I might not be able to reply to every message.

    When you write, please be sure to include this books title and authors as well as yourname and phone or email address. I will carefully review your comments and share themwith the authors and editors who worked on the book.

    Email: [email protected]: Mark Taber

    Associate PublisherSams Publishing800 East 96th StreetIndianapolis, IN 46240 USA

    Reader ServicesFor more information about this book or others from Sams Publishing, visit our Web siteat www.samspublishing.com.Type the ISBN (excluding hyphens) or the title of the bookin the Search box to find the book youre looking for.

    00 6728 fm 9/2/04 1:15 PM Page xxxiv

  • Introduction

    WELCOME TO PHP AND MYSQL WEB DEVELOPMENT. Within its pages, you will finddistilled knowledge from our experiences using PHP and MySQL, two of the hottestweb development tools around.

    In this introduction, we covern Why you should read this bookn What you will be able to achieve using this bookn What PHP and MySQL are and why theyre greatn What the new features of PHP 5.0 and MySQL 5.0 aren How this book is organized

    Lets get started.

    Why You Should Read This BookThis book will teach you how to create interactive websites from the simplest orderform through to complex, secure e-commerce sites.Whats more, youll learn how to doit using open source technologies.

    This book is aimed at readers who already know at least the basics of HTML andhave done some programming in a modern programming language before but have notnecessarily programmed for the Internet or used a relational database. If you are a begin-ning programmer, you should still find this book useful, but digesting it might take a lit-tle longer.Weve tried not to leave out any basic concepts, but we do cover them atspeed.The typical readers of this book want to master PHP and MySQL for the purposeof building a large or commercial website.You might already be working in another webdevelopment language; if so, this book should get you up to speed quickly.

    We wrote the first edition of this book because we were tired of finding PHP booksthat were basically function references.These books are useful, but they dont help whenyour boss or client has said,Go build me a shopping cart. In this book, we have doneour best to make every example useful.You can use many of the code samples directly inyour website, and you can use many others with only minor modifications.

    01 6728 IN 9/2/04 1:24 PM Page 1

  • 2 Introduction

    What You Will Be Able to Achieve Using This BookReading this book will enable you to build real-world, dynamic websites. If youve builtwebsites using plain HTML, you realize the limitations of this approach. Static contentfrom a pure HTML website is just thatstatic. It stays the same unless you physicallyupdate it.Your users cant interact with the site in any meaningful fashion.

    Using a language such as PHP and a database such as MySQL allows you to makeyour sites dynamic: to have them be customizable and contain real-time information.

    We have deliberately focused this book on real-world applications, even in the intro-ductory chapters.We begin by looking at a simple online ordering system and work ourway through the various parts of PHP and MySQL.

    We then discuss aspects of electronic commerce and security as they relate to buildinga real-world website and show you how to implement these aspects in PHP and MySQL.

    In the final part of this book, we describe how to approach real-world projects andtake you through the design, planning, and building of the following projects:

    n User authentication and personalizationn Shopping cartsn Content-management systemsn Web-based emailn Mailing list managersn Web forumsn PDF document generationn Web services with XML and SOAP

    You should be able to use any of these projects as is, or you can modify them to suityour needs.We chose them because we believe they represent some the most commonweb-based applications built by programmers. If your needs are different, this bookshould help you along the way to achieving your goals.

    What Is PHP?PHP is a server-side scripting language designed specifically for the Web.Within anHTML page, you can embed PHP code that will be executed each time the page is vis-ited.Your PHP code is interpreted at the web server and generates HTML or other out-put that the visitor will see.

    PHP was conceived in 1994 and was originally the work of one man, RasmusLerdorf. It was adopted by other talented people and has gone through four majorrewrites to bring us the broad, mature product we see today.As of August 2004, it wasinstalled on more than 17 million domains worldwide, and this number is growing rap-idly. You can see the current number at

    http://www.php.net/usage.php

    01 6728 IN 9/2/04 1:24 PM Page 2

  • 3Introduction

    PHP is an Open Source product, which means you have access to the source codeand can use, alter, and redistribute it all without charge.

    PHP originally stood for Personal Home Page but was changed in line with the GNUrecursive naming convention (GNU = Gnus Not Unix) and now stands for PHPHypertext Preprocessor.

    The current major version of PHP is 5.This version has seen a complete rewrite ofthe underlying Zend engine and some major improvements to the language.

    The home page for PHP is available athttp://www.php.net

    The home page for Zend Technologies ishttp://www.zend.com

    What Is MySQL?MySQL (pronounced My-Ess-Que-Ell ) is a very fast, robust, relational database managementsystem (RDBMS).A database enables you to efficiently store, search, sort, and retrievedata.The MySQL server controls access to your data to ensure that multiple users canwork with it concurrently, to provide fast access to it, and to ensure that only authorizedusers can obtain access. Hence, MySQL is a multiuser, multithreaded server. It usesStructured Query Language (SQL), the standard database query language worldwide.MySQL has been publicly available since 1996 but has a development history going backto 1979. It is the worlds most popular open source database and has won the LinuxJournal Readers Choice Award on a number of occasions.

    MySQL is available under a dual licensing scheme.You can use it under an opensource license (the GPL) free as long as you are willing to meet the terms of that license.If you want to distribute a non-GPL application including MySQL, you can buy a com-mercial license instead.

    Why Use PHP and MySQL?When setting out to build an e-commerce site, you could use many different products.You need to choose the following:

    n Hardware for the web servern An operating systemn Web server softwaren A database management systemn A programming or scripting language

    Some of these choices are dependent on the others. For example, not all operating systems run on all hardware, not all scripting languages can connect to all databases, andso on.

    01 6728 IN 9/2/04 1:24 PM Page 3

  • 4 Introduction

    In this book, we do not pay much attention to hardware, operating systems, or webserver software.We dont need to. One of the best features of both PHP and MySQL isthat they work with any major operating system and many of the minor ones.

    To demonstrate this, we have written the examples in this book and tested them ontwo popular setups:

    n Linux using the Apache web servern Microsoft Windows XP using Microsoft Internet Information Server (IIS)

    Whatever hardware, operating system, and web server you choose, we believe you shouldseriously consider using PHP and MySQL.

    Some of PHPs StrengthsSome of PHPs main competitors are Perl, Microsoft ASP.NET, JavaServer Pages (JSP),and ColdFusion.

    In comparison to these products, PHP has many strengths, including the following:n High performancen Interfaces to many different database systemsn Built-in libraries for many common web tasksn Low costn Ease of learning and usen Strong object-oriented supportn Portabilityn Availability of source coden Availability of support

    A more detailed discussion of these strengths follows.

    PerformancePHP is very efficient. Using a single inexpensive server, you can serve millions of hits perday. If you use large numbers of commodity servers, your capacity is effectively unlimit-ed. Benchmarks published by Zend Technologies (http://www.zend.com) show PHPoutperforming its competition.

    Database IntegrationPHP has native connections available to many database systems. In addition to MySQL,you can directly connect to PostgreSQL, mSQL, Oracle, dbm, FilePro, Hyperwave,Informix, InterBase, and Sybase databases, among others. PHP 5 also has a built-in SQLinterface to a flat file, called SQLite.

    01 6728 IN 9/2/04 1:24 PM Page 4

  • 5Introduction

    Using the Open Database Connectivity Standard (ODBC), you can connect to any data-base that provides an ODBC driver.This includes Microsoft products and many others.

    Built-in LibrariesBecause PHP was designed for use on the Web, it has many built-in functions for per-forming many useful web-related tasks.You can generate GIF images on the fly, connectto web services and other network services, parse XML, send email, work with cookies,and generate PDF documents, all with just a few lines of code.

    CostPHP is free.You can download the latest version at any time from http://www.php.netfor no charge.

    Ease of Learning PHPThe syntax of PHP is based on other programming languages, primarily C and Perl. Ifyou already know C or Perl, or a C-like language such as C++ or Java, you will be pro-ductive using PHP almost immediately.

    Object-Oriented SupportPHP version 5 has well-designed object-oriented features. If you learned to program inJava or C++, you will find the features (and generally the syntax) that you expect, suchas inheritance, private and protected attributes and methods, abstract classes and methods,interfaces, constructors, and destructors.You will even find some less common featuressuch as built-in iteration behavior. Some of this functionality was available in PHP ver-sions 3 and 4, but the object-oriented support in version 5 is much more complete.

    PortabilityPHP is available for many different operating systems.You can write PHP code on freeUnix-like operating systems such as Linux and FreeBSD, commercial Unix versions suchas Solaris and IRIX, or on different versions of Microsoft Windows.

    Well-written code will usually work without modification on a different system run-ning PHP.

    Source CodeYou have access to PHPs source code.With PHP, unlike commercial, closed-sourceproducts, if you want to modify something or add to the language, you are free to do so.

    You do not need to wait for the manufacturer to release patches.You also dont needto worry about the manufacturer going out of business or deciding to stop supporting aproduct.

    01 6728 IN 9/2/04 1:24 PM Page 5

  • 6 Introduction

    Availability of SupportZend Technologies (www.zend.com), the company behind the engine that powers PHP,funds its PHP development by offering support and related software on a commercialbasis.

    What Is New in PHP 5.0?You may have recently moved to PHP 5.0 from one of the PHP 4.x versions.As youwould expect in a new major version, it has some significant changes.The Zend enginebeneath PHP has been rewritten for this version. Major new features are as follows:

    n Better object-oriented support built around a completely new object model (seeChapter 6,Object-Oriented PHP)

    n Exceptions for scalable, maintainable error handling (see Chapter 7,ExceptionHandling)

    n SimpleXML for easy handling of XML data (see Chapter 33,Connecting to WebServices with XML and SOAP)

    Other changes include moving some extensions out of the default PHP install and intothe PECL library, improving streams support, and adding SQLite.

    Some of MySQLs StrengthsMySQLs main competitors are PostgreSQL, Microsoft SQL Server, and Oracle.MySQL has many strengths, including the following:

    n High performancen Low costn Ease of configuration and learningn Portabilityn Availability of source coden Availability of support

    A more detailed discussion of these strengths follows.

    PerformanceMySQL is undeniably fast.You can see the developers benchmark page athttp://web.mysql.com/benchmark.html. Many of these benchmarks show MySQL to beorders of magnitude faster than the competition. In 2002, eWeek published a benchmarkcomparing five databases powering a web application.The best result was a tie betweenMySQL and the much more expensive Oracle.

    01 6728 IN 9/2/04 1:24 PM Page 6

  • 7Introduction

    Low CostMySQL is available at no cost under an open source license or at low cost under a com-mercial license.You need a license if you want to redistribute MySQL as part of anapplication and do not want to license your application under an Open Source license. Ifyou do not intend to distribute your application or are working on Free Software, youdo not need to buy a license.

    Ease of UseMost modern databases use SQL. If you have used another RDBMS, you should have notrouble adapting to this one. MySQL is also easier to set up than many similar products.

    PortabilityMySQL can be used on many different Unix systems as well as under MicrosoftWindows.

    Source CodeAs with PHP, you can obtain and modify the source code for MySQL.This point is notimportant to most users most of the time, but it provides you with excellent peace ofmind, ensuring future continuity and giving you options in an emergency.

    Availability of SupportNot all open source products have a parent company offering support, training, consult-ing, and certification, but you can get all of these benefits from MySQL AB(www.mysql.com).

    What Is New in MySQL 5.0?Major changes introduced for MySQL 5.0 include

    n Stored procedures (see Chapter 13,Advanced MySQL Programming)n Cursor support

    Other changes include more ANSI standard compliance and speed improvements.If you are still using an early 4.x version or a 3.x version of the MySQL server, youshould know that the following features were added to various versions from 4.0:

    n Subquery supportn GIS types for storing geographical datan Improved support for internationalizationn The transaction-safe storage engine InnoDB included as standardn The MySQL query cache, which greatly improves the speed of repetitive queries

    as often run by web applications

    01 6728 IN 9/2/04 1:24 PM Page 7

  • 8 Introduction

    How Is This Book Organized?This book is divided into five main parts:

    Part I,Using PHP, provides an overview of the main parts of the PHP languagewith examples. Each example is a real-world example used in building an e-commercesite rather than toy code.We kick off this section with Chapter 1,PHP CrashCourse. If youve already used PHP, you can whiz through this chapter. If you are newto PHP or new to programming, you might want to spend a little more time on it. Evenif you are quite familiar with PHP, you will want to read Chapter 6,Object-OrientedPHP, because the object-oriented functionality has changed significantly in PHP5.

    Part II,Using MySQL, discusses the concepts and design involved in using relationaldatabase systems such as MySQL, using SQL, connecting your MySQL database to theworld with PHP, and employing advanced MySQL techniques, such as security and opti-mization.

    Part III,E-commerce and Security, covers some of the general issues involved indeveloping an e-commerce site using any language.The most important of these issues issecurity.We then discuss how you can use PHP and MySQL to authenticate your usersand securely gather, transmit, and store data.

    Part IV,Advanced PHP Techniques, offers detailed coverage of some of the majorbuilt-in functions in PHP.We have selected groups of functions that are likely to be use-ful when building an e-commerce site.You will learn about interaction with the server,interaction with the network, image generation, date and time manipulation, and sessionvariables.

    Part V,Building Practical PHP and MySQL Projects, is our favorite section. It dealswith practical real-world issues such as managing large projects and debugging, and pro-vides sample projects that demonstrate the power and versatility of PHP and MySQL.

    FinallyWe hope you enjoy this book and enjoy learning about PHP and MySQL as much aswe did when we first began using these products.They are really a pleasure to use. Soon,youll be able to join the thousands of web developers who use these robust, powerfultools to easily build dynamic, real-time websites.

    01 6728 IN 9/2/04 1:24 PM Page 8

  • IUsing PHP

    1 PHP Crash Course

    2 Storing and Retrieving Data

    3 Using Arrays

    4 String Manipulation and Regular Expressions

    5 Reusing Code and Writing Functions

    6 Object-Oriented PHP

    7 Exception Handling

    02 6728 Part1 9/2/04 1:15 PM Page 9

  • 02 6728 Part1 9/2/04 1:15 PM Page 10

  • 1PHP Crash Course

    THIS CHAPTER GIVES YOU A QUICK OVERVIEW of PHP syntax and language constructs.If you are already a PHP programmer, it might fill some gaps in your knowledge. If youhave a background using C,Active Server Pages (ASP), or another programming lan-guage, it will help you get up to speed quickly.

    In this book, youll learn how to use PHP by working through lots of real-worldexamples taken from our experiences in building e-commerce sites. Often, programmingtextbooks teach basic syntax with very simple examples.We have chosen not to do that.We recognize that often what you want to do is get something up and running, tounderstand how the language is used, instead of plowing through yet another syntax andfunction reference thats no better than the online manual.

    Try the examples.Type them in or load them from the CD-ROM, change them,break them, and learn how to fix them again.

    This chapter begins with the example of an online product order form to show howvariables, operators, and expressions are used in PHP. It also covers variable types andoperator precedence.You learn how to access form variables and manipulate them byworking out the total and tax on a customer order.

    You then develop the online order form example by using a PHP script to validatethe input data.You examine the concept of Boolean values and look at examples usingif, else, the ?: operator, and the switch statement. Finally, you explore looping bywriting some PHP to generate repetitive HTML tables.

    Key topics you learn in this chapter includen Embedding PHP in HTMLn Adding dynamic contentn Accessing form variables

    03 6728 CH01 9/2/04 1:23 PM Page 11

  • 12 Chapter 1 PHP Crash Course

    n Understanding identifiersn Creating user-declared variablesn Examining variable typesn Assigning values to variablesn Declaring and using constantsn Understanding variable scopen Understanding operators and precedencen Evaluating expressionsn Using variable functionsn Making decisions with if, else, and switchn Taking advantage of iteration using while, do, and for loops

    Using PHPTo work through the examples in this chapter and the rest of the book, you need accessto a web server with PHP installed.To gain the most from the examples and case studies,you should run them and try changing them.To do this, you need a testbed where youcan experiment.

    If PHP is not installed on your machine, you need to begin by installing it or havingyour system administrator install it for you.You can find instructions for doing so inAppendix A,Installing PHP5 and MySQL5. Everything you need to install PHP underUnix or Windows can be found on the accompanying CD-ROM.

    Creating a Sample Application: Bobs Auto PartsOne of the most common applications of any server-side scripting language is processingHTML forms.Youll start learning PHP by implementing an order form for Bobs AutoParts, a fictional spare parts company.You can find all the code for the examples used inthis chapter in the directory called chapter01 on the CD-ROM.

    Creating the Order FormBobs HTML programmer has set up an order form for the parts that Bob sells.This rel-atively simple order form, shown in Figure 1.1, is similar to many you have probablyseen while surfing. Bob would like to be able to know what his customers ordered, workout the total prices of their orders, and determine how much sales tax is payable on theorders.

    03 6728 CH01 9/2/04 1:23 PM Page 12

  • 13Creating a Sample Application: Bobs Auto Parts

    Figure 1.1 Bobs initial order form records only products and quantities.

    Part of the HTML for this form is shown in Listing 1.1.

    Listing 1.1 orderform.html HTML for Bobs Basic Order Form

    ItemQuantity

    Tires

    Oil

    03 6728 CH01 9/2/04 1:23 PM Page 13

  • 14 Chapter 1 PHP Crash Course

    Spark Plugs

    Notice that the forms action is set to the name of the PHP script that will process thecustomers order. (Youll write this script next.) In general, the value of the actionattribute is the URL that will be loaded when the user clicks the Submit button.Thedata the user has typed in the form will be sent to this URL via the method specified inthe method attribute, either get (appended to the end of the URL) or post (sent as aseparate message).

    Also note the names of the form fields: tireqty, oilqty, and sparkqty.Youll usethese names again in the PHP script. Because the names will be reused, its important togive your form fields meaningful names that you can easily remember when you beginwriting the PHP script. Some HTML editors generate field names like field23 bydefault.They are difficult to remember.Your life as a PHP programmer will be easier ifthe names you use reflect the data typed into the field.

    You might want to consider adopting a coding standard for field names so that allfield names throughout your site use the same format.This way, you can more easilyremember whether, for example, you abbreviated a word in a field name or put inunderscores as spaces.

    Processing the FormTo process the form, you need to create the script mentioned in the action attribute ofthe form tag called processorder.php. Open your text editor and create this file.Thentype in the following code:

    Bobs Auto Parts - Order Results

    Bobs Auto PartsOrder Results

    Listing 1.1 Continued

    03 6728 CH01 9/2/04 1:23 PM Page 14

  • 15Embedding PHP in HTML

    Notice how everything youve typed so far is just plain HTML. Its now time to addsome simple PHP code to the script.

    Embedding PHP in HTMLUnder the heading in your file, add the following lines:

    Save the file and load it in your browser by filling out Bobs form and clicking theSubmit Order button.You should see something similar to the output shown in Figure 1.2.

    Figure 1.2 Text passed to PHPs echo construct is echoed to the browser.

    Notice how the PHP code you wrote was embedded inside a normal-looking HTMLfile.Try viewing the source from your browser.You should see this code:

    03 6728 CH01 9/2/04 1:23 PM Page 15

  • 16 Chapter 1 PHP Crash Course

    Bobs Auto Parts - Order Results

    Bobs Auto PartsOrder Results

    Order processed.

    None of the raw PHP is visible because the PHP interpreter has run through the scriptand replaced it with the output from the script.This means that from PHP you can pro-duce clean HTML viewable with any browser; in other words, the users browser doesnot need to understand PHP.

    This example illustrates the concept of server-side scripting in a nutshell.The PHPhas been interpreted and executed on the web server, as distinct from JavaScript andother client-side technologies interpreted and executed within a web browser on a usersmachine.

    The code that you now have in this file consists of four types of text:n HTMLn PHP tagsn PHP statementsn Whitespace

    You can also addn Comments

    Most of the lines in the example are just plain HTML.

    Use of PHP TagsThe PHP code in the preceding example began with .This issimilar to all HTML tags because they all begin with a less than () symbol.These symbols () are called PHP tags.They tellthe web server where the PHP code starts and finishes.Any text between the tags isinterpreted as PHP.Any text outside these tags is treated as normal HTML.The PHPtags allow you to escape from HTML.

    You can choose different tag styles. Lets look at these tags in more detail.

    PHP Tag StylesThere are actually four different styles of PHP tags. Each of the following fragments ofcode is equivalent:

    03 6728 CH01 9/2/04 1:23 PM Page 16

  • 17Embedding PHP in HTML

    n XML style

    This is the tag style that we use in this book; it is the preferred PHP tag style.Theserver administrator cannot turn it off, so you can guarantee it will be available onall servers, which is especially important if you are writing applications that may beused on different installations.This tag style can be used with Extensible MarkupLanguage (XML) documents. If you plan to serve XML on your site, you shoulddefinitely use this tag style.

    n Short style

    This tag style is the simplest and follows the style of a Standard GeneralizedMarkup Language (SGML) processing instruction.To use this type of tagwhichis the shortest to typeyou either need to enable the short_open_tag setting inyour config file or compile PHP with short tags enabled.You can find more infor-mation on how to use this tag style in Appendix A.The use of this style is not rec-ommended because, although this tag style is currently enabled by default, systemadministrators occasionally disable it because it interferes with XML documentdeclarations.

    n SCRIPT style

    echo Order processed.;

    This tag style is the longest and will be familiar if youve used JavaScript orVBScript.You might use it if youre using an HTML editor that gives you prob-lems with the other tag styles.

    n ASP style

    This tag style is the same as used in Active Server Pages (ASP) or ASP.NET.Youcan use it if you have enabled the asp_tags configuration setting.You might wantto use this style of tag if you are using an editor that is geared toward ASP orASP.NET or if you already program in ASP or ASP.NET. Note that, by default,this tag style is disabled.

    PHP StatementsYou tell the PHP interpreter what to do by including PHP statements between youropening and closing tags.The preceding example used only one type of statement:

    echo Order processed.;

    03 6728 CH01 9/2/04 1:23 PM Page 17

  • 18 Chapter 1 PHP Crash Course

    As you have probably guessed, using the echo construct has a very simple result: It prints(or echoes) the string passed to it to the browser. In Figure 1.2, you can see the result isthat the text Order processed. appears in the browser window.

    Notice that a semicolon appears at the end of the echo statement. It separates state-ments in PHP much like a period separates sentences in English. If you have pro-grammed in C or Java before, you will be familiar with using the semicolon in this way.

    Leaving off the semicolon is a common syntax error that is easily made. However, itsequally easy to find and to correct.

    WhitespaceSpacing characters such as newlines (carriage returns), spaces, and tabs are known aswhitespace.As you probably already know, browsers ignore whitespace in HTML. So doesthe PHP engine. Consider these two HTML fragments:

    Welcome to Bobs Auto Parts!What would you like to order today?

    and

    Welcome to BobsAuto Parts!

    What would you like

    to order today?

    These two snippets of HTML code produce identical output because they appear thesame to the browser. However, you can and are encouraged to use whitespace in yourHTML as an aid to humansto enhance the readability of your HTML code.The sameis true for PHP.You dont need to have any whitespace between PHP statements, but itmakes the code much easier to read if you put each statement on a separate line. Forexample,

    echo hello ;echo world;

    and

    echo hello ;echo world;

    are equivalent, but the first version is easier to read.

    CommentsComments are exactly that: Comments in code act as notes to people reading the code.Comments can be used to explain the purpose of the script, who wrote it, why theywrote it the way they did, when it was last modified, and so on.You generally find com-ments in all but the simplest PHP scripts.

    The PHP interpreter ignores any text in comments. Essentially, the PHP parser skipsover the comments, making them equivalent to whitespace.

    03 6728 CH01 9/2/04 1:23 PM Page 18

  • 19Adding Dynamic Content

    PHP supports C, C++, and shell scriptstyle comments.The following is a C-style, multiline comment that might appear at the start of a

    PHP script:

    /* Author: Bob Smith

    Last modified: April 10

    This script processes the customer orders.

    */

    Multiline comments should begin with a /* and end with */.As in C, multiline com-ments cannot be nested.

    You can also use single-line comments, either in the C++ style:

    echo Order processed.; // Start printing order

    or in the shell script style:

    echo Order processed.; # Start printing order

    With both of these styles, everything after the comment symbol (# or //) is a commentuntil you reach the end of the line or the ending PHP tag, whichever comes first.

    In the following line of code, the text before the closing tag, here is a comment, ispart of a comment.The text after the closing tag, here is not, will be treated asHTML because it is outside the closing tag:

    // here is a comment ?> here is not

    Adding Dynamic ContentSo far, you havent used PHP to do anything you couldnt have done with plain HTML.

    The main reason for using a server-side scripting language is to be able to providedynamic content to a sites users.This is an important application because content thatchanges according to users needs or over time will keep visitors coming back to a site.PHP allows you to do this easily.

    Lets start with a simple example. Replace the PHP in processorder.php with thefollowing code:

    In this code, PHPs built-in date() function tells the customer the date and time whenhis order was processed.This information will be different each time the script is run.The output of running the script on one occasion is shown in Figure 1.3.

    03 6728 CH01 9/2/04 1:23 PM Page 19

  • 20 Chapter 1 PHP Crash Course

    Figure 1.3 PHPs date() function returns a formatted date string.

    Calling FunctionsLook at the call to date().This is the general form that function calls take. PHP has anextensive library of functions you can use when developing web applications. Most ofthese functions need to have some data passed to them and return some data.

    Now look at the function call again:

    date(H:i, jS F)

    Notice that it passes a string (text data) to the function inside a pair of parentheses.Theelement within the parentheses is called the functions argument or parameter. Such argu-ments are the input the function uses to output some specific results.

    Using the date() FunctionThe date() function expects the argument you pass it to be a format string, represent-ing the style of output you would like. Each letter in the string represents one part ofthe date and time. H is the hour in a 24-hour format with leading zeros where required,i is the minutes with a leading zero where required, j is the day of the month without aleading zero, S represents the ordinal suffix (in this case th), and F is the full name of themonth.

    03 6728 CH01 9/2/04 1:23 PM Page 20

  • 21Accessing Form Variables

    For a full list of formats supported by date(), see Chapter 20,Managing the Dateand Time.

    Accessing Form VariablesThe whole point of using the order form is to collect customers orders. Getting thedetails of what the customers typed is easy in PHP, but the exact method depends on theversion of PHP you are using and a setting in your php.ini file.

    Form VariablesWithin your PHP script, you can access each form field as a PHP variable whose namerelates to the name of the form field.You can recognize variable names in PHP becausethey all start with a dollar sign ($). (Forgetting the dollar sign is a common programmingerror.)

    Depending on your PHP version and setup, you can access the form data via variablesin three ways.These methods do not have official names, so we have nicknamed themshort, medium, and long style. In any case, each form field on a page submitted to a PHPscript is available in the script.

    You can access the contents of the field tireqty in the following ways:

    $tireqty // short style

    $_POST[tireqty] // medium style$HTTP_POST_VARS[tireqty] // long style

    In this example and throughout this book, we have used the medium style (that is,$_POST[tireqty]) for referencing form variables, but we have created short versionsof the variables for ease of use. (This has been the recommended approach since PHPversion 4.2.0.)

    For your own code, you might decide to use a different approach.To make aninformed choice, look at the different methods:

    n Short style ($tireqty) is convenient but requires the register_globals configu-ration setting be turned on.Whether it is on or off by default depends on the ver-sion of PHP. In all versions since 4.2.0, it has been off by default. Previously, it wason by default, and most PHP programmers used the short tag style. This changecaused quite a lot of confusion at the time it was made.This style also allows youto make errors that could make your code insecure, which is why it is no longerthe recommended approach.

    n Medium style ($_POST[tireqty]) is now the recommended approach. It isfairly convenient but came into existence only with PHP 4.1.0, so it does notwork on older installations.

    03 6728 CH01 9/2/04 1:23 PM Page 21

  • 22 Chapter 1 PHP Crash Course

    n Long style ($HTTP_POST_VARS[tireqty]) is the most verbose. Note, however,that it is deprecated and is therefore likely to be removed in the long term.Thisstyle used to be the most portable but can now be disabled via theregister_long_arrays configuration directive, which improves performance.

    When you use the short style, the names of the variables in the script are the same as thenames of the form fields in the HTML form.You dont need to declare the variables ortake any action to create these variables in your script.They are passed into your script,essentially as arguments are passed to a function. If you are using this style, you can use avariable such as $tireqty.The field tireqty in the form creates the variable $tireqtyin the processing script.

    Such convenient access to variables is appealing, but before you simply turn on register_globals, it is worth considering why the PHP development team set it to off.

    Having direct access to variables like this is very convenient, but it does allow you to makeprogramming mistakes that could compromise your scripts security.With form variablesautomatically turned into global variables like this, there is no obvious distinction betweenvariables that you have created and untrusted variables that have come directly from users.

    If you are not careful to give all your own variables a starting value, your scripts userscan pass variables and values as form variables that will be mixed with your own. If youchoose to use the convenient short style of accessing variables, you need to give all yourown variables a starting value.

    Medium style involves retrieving form variables from one of the arrays $_POST,$_GET, or $_REQUEST. One of the $_GET or $_POST arrays holds the details of all theform variables.Which array is used depends on whether the method used to submit theform was GET or POST, respectively. In addition, all data submitted via GET or POST is alsoavailable through $_REQUEST.

    If the form was submitted via the POST method, the data entered in the tireqty boxwill be stored in $_POST[tireqty]. If the form was submitted via GET, the data willbe in $_GET[tireqty]. In either case, the data will also be available in$_REQUEST[tireqty].

    These arrays are some of the superglobal arrays.We will revisit the superglobals whenwe discuss variable scope.

    If you are using an older version of PHP, you might not have access to $_POST or$_GET. Prior to version 4.1.0, this information was stored in arrays named$HTTP_POST_VARS and $HTTP_GET_VARS.We call this the long style.As mentioned previ-ously, this style has been deprecated.There is no equivalent of $_REQUEST in this style.

    If you are using long style, you can access a users response through$HTTP_POST_VARS[tireqty] or $HTTP_GET_VARS[tireqty].

    03 6728 CH01 9/2/04 1:23 PM Page 22

  • 23Accessing Form Variables

    The examples in this book were tested with PHP version 5.0 and will sometimes beincompatible with older versions of PHP prior to version 4.1.0.We recommend that,where possible, you use the current version.

    Lets look at another example. Because the long and medium style variable names aresomewhat cumbersome and rely on a variable type known as arrays, which are not covered properly until Chapter 3,Using Arrays, you can start by creating easier-to-usecopies.

    To copy the value of one variable into another, you use the assignment operator,which in PHP is an equal sign (=).The following statement creates a new variable named$tireqty and copies the contents of $ POST [tireqty] into the new variable:

    $tireqty = $_POST[tireqty];

    Place the following block of code at the start of the processing script.All other scripts inthis book that handle data from a form contain a similar block at the start. Because thiscode will not produce any output, placing it above or below the and otherHTML tags that start your page makes no difference.We generally place such blocks atthe start of the script to make them easy to find.

    This code creates three new variables$tireqty, $oilqty, and $sparkqtyand setsthem to contain the data sent via the POST method from the form.

    To make the script start doing something visible, add the following lines to the bot-tom of your PHP script:

    echo Your order is as follows: ;echo $tireqty. tires;echo $oilqty. bottles of oil;echo $sparkqty. spark plugs;

    At this stage, you have not checked the variable contents to make sure sensible data hasbeen entered in each form field.Try entering deliberately wrong data and observe whathappens.After you have read the rest of the chapter, you might want to try adding somedata validation to this script.

    If you now load this file in your browser, the script output should resemble what isshown in Figure 1.4.The actual values shown, of course, depend on what you typed intothe form.

    03 6728 CH01 9/2/04 1:23 PM Page 23

  • 24 Chapter 1 PHP Crash Course

    Figure 1.4 The form variables the user typed in are easily accessible inprocessorder.php.

    The following subsections describe a couple of interesting elements of this example.

    String ConcatenationIn the sample script, echo prints the value the user typed in each form field, followed bysome explanatory text. If you look closely at the echo statements, you can see that thevariable name and following text have a period (.) between them, such as this:

    echo $tireqty. tires;

    This period is the string concatenation operator, which adds strings (pieces of text)together.You will often use it when sending output to the browser with echo.This way,you can avoid writing multiple echo commands.

    You can also place any nonarray variables inside a double-quoted string to be echoed.(Arrays are somewhat more complicated, so we look at combining arrays and strings inChapter 4,String Manipulation and Regular Expressions.) Consider this example:

    echo $tireqty tires;

    03 6728 CH01 9/2/04 1:23 PM Page 24

  • 25Accessing Form Variables

    This is equivalent to the first statement shown in this section. Either format is valid, andwhich one you use is a matter of personal taste.This process, replacing a variable with itscontents within a string, is known as interpolation.

    Note that interpolation is a feature of double-quoted strings only.You cannot placevariable names inside a single-quoted string in this way. Running the following line ofcode

    echo $tireqty tires;

    simply sends $tireqty tires to the browser.Within double quotation marks,the variable name is replaced with its value.Within single quotation marks, the variablename or any other text is sent unaltered.

    Variables and LiteralsThe variables and strings concatenated together in each of the echo statements in thesample script are different types of things.Variables are symbols for data.The strings aredata themselves.When we use a piece of raw data in a program like this, we call it a liter-al to distinguish it from a variable. $tireqty is a variable, a symbol that represents thedata the customer typed in. On the other hand, tires is a literal.You can takeit at face value.Well, almost. Remember the second example in the preceding section?PHP replaced the variable name $tireqty in the string with the value stored in thevariable.

    Remember the two kinds of strings mentioned already: ones with double quotationmarks and ones with single quotation marks. PHP tries to evaluate strings in doublequotation marks, resulting in the behavior shown earlier. Single-quoted strings are treat-ed as true literals.

    Recently, a third way of specifying strings was added.The heredoc syntax (

  • 26 Chapter 1 PHP Crash Course

    Understanding IdentifiersIdentifiers are the names of variables. (The names of functions and classes are also identi-fiers; we look at functions and classes in Chapters 5,Reusing Code and WritingFunctions, and 6,Object-Oriented PHP.) You need to be aware of the simple rulesdefining valid identifiers:

    n Identifiers can be of any length and can consist of letters, numbers, and under-scores.

    n Identifiers cannot begin with a digit.n In PHP, identifiers are case sensitive. $tireqty is not the same as $TireQty.Trying

    to use them interchangeably is a common programming error. Function names arean exception to this rule:Their names can be used in any case.

    n A variable can have the same name as a function.This usage is confusing, however,and should be avoided.Also, you cannot create a function with the same name asanother function.

    Creating User-Declared VariablesYou can declare and use your own variables in addition to the variables you are passedfrom the HTML form.

    One of the features of PHP is that it does not require you to declare variables beforeusing them.A variable is created when you first assign a value to it. See the next sectionfor details.

    Assigning Values to VariablesYou assign values to variables using the assignment operator (=) as you did when copyingone variables value to another. On Bobs site, you want to work out the total number ofitems ordered and the total amount payable.You can create two variables to store thesenumbers.To begin with, you need to initialize each of these variables to zero.

    Add these lines to the bottom of your PHP script:

    $totalqty = 0;

    $totalamount = 0.00;

    Each of these two lines creates a variable and assigns a literal value to it.You can alsoassign variable values to variables, as shown in this example:

    $totalqty = 0;

    $totalamount = $totalqty;

    03 6728 CH01 9/2/04 1:23 PM Page 26

  • 27Examining Variable Types

    Examining Variable TypesA variables type refers to the kind of data stored in it. PHP provides a growing set ofdata types. Different data can be stored in different data types.

    PHPs Data TypesPHP supports the following basic data types:

    n IntegerUsed for whole numbersn Float (also called double)Used for real numbersn StringUsed for strings of charactersn BooleanUsed for true or false valuesn ArrayUsed to store multiple data items (see Chapter 3,Using Arrays)n ObjectUsed for storing instances of classes (see Chapter 6)

    Two special types are also available: NULL and resource.Variables that have not beengiven a value, have been unset, or have been given the specific value NULL are of typeNULL. Certain built-in functions (such as database functions) return variables that havethe type resource. They represent external resources (such as database connections).Youwill almost certainly not directly manipulate a resource variable, but frequently they arereturned by functions and must be passed as parameters to other functions.

    Type StrengthPHP is a very weakly typed language. In most programming languages, variables canhold only one type of data, and that type must be declared before the variable can beused, as in C. In PHP, the type of a variable is determined by the value assigned to it.

    For example, when you created $totalqty and $totalamount, their initial types weredetermined as follows:

    $totalqty = 0;

    $totalamount = 0.00;

    Because you assigned 0, an integer, to $totalqty, this is now an integer type variable.Similarly, $totalamount is now of type float.

    Strangely enough, you could now add a line to your script as follows:

    $totalamount = Hello;

    The variable $totalamount would then be of type string. PHP changes the variable typeaccording to what is stored in it at any given time.

    03 6728 CH01 9/2/04 1:23 PM Page 27

  • 28 Chapter 1 PHP Crash Course

    This ability to change types transparently on the fly can be extremely useful.Remember PHP automagically knows what data type you put into your variable. Itreturns the data with the same data type when you retrieve it from the variable.

    Type CastingYou can pretend that a variable or value is of a different type by using a type cast.Thisfeature works identically to the way it works in C.You simply put the temporary type inparentheses in front of the variable you want to cast.

    For example, you could have declared the two variables from the preceding sectionusing a cast:

    $totalqty = 0;

    $totalamount = (float)$totalqty;

    The second line means Take the value stored in $totalqty, interpret it as a float, andstore it in $totalamount.The $totalamount variable will be of type float.The castvariable does not change types, so $totalqty remains of type integer.

    Variable VariablesPHP provides one other type of variable: the variable variable.Variable variables enableyou to change the name of a variable dynamically.

    As you can see, PHP allows a lot of freedom in this area.All languages enable you tochange the value of a variable, but not many allow you to change the variables type, andeven fewer allow you to change the variables name.

    A variable variable works by using the value of one variable as the name of another.For example, you could set

    $varname = tireqty;

    You can then use $$varname in place of $tireqty. For example, you can set the value of$tireqty as follows:

    $$varname = 5;

    This is exactly equivalent to

    $tireqty = 5;

    This approach might seem somewhat obscure, but well revisit its use later. Instead ofhaving to list and use each form variable separately, you can use a loop and variable toprocess them all automatically.You can find an example illustrating this in the section onfor loops.

    03 6728 CH01 9/2/04 1:23 PM Page 28

  • 29Understanding Variable Scope

    Declaring and Using ConstantsAs you saw previously, you can readily change the value stored in a variable.You can alsodeclare constants.A constant stores a value just like a variable, but its value is set onceand then cannot be changed elsewhere in the script.

    In the sample application, you might store the prices for each item on sale as a con-stant.You can define these constants using the define function:

    define(TIREPRICE, 100);define(OILPRICE, 10);define(SPARKPRICE, 4);

    Now add these lines of code to your script.You now have three constants that can beused to calculate the total of the customers order.

    Notice that the names of the constants appear in uppercase.This convention bor-rowed from C makes it easy to distinguish between variables and constants at a glance.Following this convention is not required but will make your code easier to read andmaintain.

    One important difference between constants and variables is that when you refer to aconstant, it does not have a dollar sign in front of it. If you want to use the value of aconstant, use its name only. For example, to use one of the constants just created, youcould type

    echo TIREPRICE;

    As well as the constants you define, PHP sets a large number of its own.An easy way toobtain an overview of them is to run the phpinfo() command:

    phpinfo();

    This function provides a list of PHPs predefined variables and constants, among otheruseful information.We will discuss some of them as we go along.

    One other difference between variables and constants is that constants can store onlyboolean, integer, float, or string data.These types are collectively known as scalar values.

    Understanding Variable ScopeThe term scope refers to the places within a script where a particular variable is visi-

    ble.The six basic scope rules in PHP are as follows:n Built-in superglobal variables are visible everywhere within a script.n Constants, once declared, are always visible globally; that is, they can be used inside

    and outside functions.n Global variables declared in a script are visible throughout that script, but not inside

    functions.

    03 6728 CH01 9/2/04 1:23 PM Page 29

  • 30 Chapter 1 PHP Crash Course

    n Variables used inside functions that are declared as global refer to the global vari-ables of the same name.

    n Variables created inside functions and declared as static are invisible from outside