beginning php and mysql - gbv · beginning php andmysql fromnoviceto professional fourth edition...
TRANSCRIPT
Contents
* About the Author xxix
* About the Technical Reviewer xxx
a Acknowledgments xxxi
Introduction xxxii
Chapter 1: Introducing PHP 1
History 1
PHP 4 2
PHP 5 3
PHP 5.3 4
PHP 6 5
General Language Features 5
Practicality 5
Power 6
Possibility 7
Price 7
Summary 8
Chapter 2: Configuring Your Environment 9
Installation Prerequisites 9
Downloading Apache 10
Downloading PHP 10
Downloading the Documentation 11
Installing Apache and PHP on Linux 12
V
•* CONTENTS
Installing Apache and PHP on Windows 13
Installing IIS and PHP on Windows 15
Testing Your Installation 16
Configuring PHP 18
Configuring PHP at Build Time on Linux 18
Customizing the Windows Build 19
Run-Time Configuration 19
Managing PHP's Configuration Directives 19
PHP's Configuration Directives 21
Choosing a Code Editor 37
Adobe Dreamweaver CS5 37
Notepad++ 37
PDT (PHP Development Tools) 38
Zend Studio 38
Choosing a Web Hosting Provider 38
Seven Questions for Any Prospective Hosting Provider 39
Summary 41
Chapter 3: PHP Basics 41
Embedding PHP Code in Your Web Pages 41
Default Syntax 42
Short-Tags 42
Script 43
ASP Style 43
Embedding Multiple Code Blocks 44
Commenting Your Code 44
Single-Line C++ Syntax 44
Shell Syntax 44
Multiple-Line C Syntax 45
CONTENTS
Outputting Data to the Browser 45
The printO Statement 46
The echoO Statement 47
The printfO Statement 47
The sprintfO Statement 49
PHP's Supported Data Types 49
Scalar Data Types 49
Compound Data Types 51
Converting Between Data Types Using Type Casting 52
Adapting Data Types with Type Juggling 53
Type-Related Functions 55
Type Identifier Functions 56
Identifiers 56
Variables 57
Variable Declaration 58
Variable Scope 59
PHP's Superglobal Variables 62
Variable Variables 68
Constants 68
Expressions 69
Operands 69
Operators 69
String Interpolation 76
Double Quotes 77
Escape Sequences 77
Single Quotes 78
Curly Braces 79
Heredoc 79
vii
H CONTENTS
Nowdoc 80
Control Structures 80
Conditional Statements 80
Looping Statements 82
File-Inclusion Statements 88
Summary 91
f* Chapter 4: Functions 91
Invoking a Function 91
Creating a Function 92
Passing Arguments by Value 93
Passing Arguments by Reference 94
Default Argument Values 94
Using Type Hinting 95
Returning Values from a Function 96
Recursive Functions 97
Function Libraries 100
Summary 101
Chapter 5: Arrays 103
What Is an Array? 103
Creating an Array , 105
Creating Arrays with arrayO 105
Extracting Arrays with list() 106
Populating Arrays with a Predefined Value Range 107
Testing for an Array 107
Outputting an Array 108
Printing Arrays for Testing Purposes 109
Adding and Removing Array Elements 110
Adding a Value to the Front of an Array 110
viii
CONTENTS
Adding a Value to the End of an Array 110
Removing a Value from the Front of an Array 111
Removing a Value from the End of an Array 111
Locating Array Elements 111
Searching an Array 111
Retrieving Array Keys 113
Retrieving Array Values 113
Traversing Arrays 113
Retrieving the Current Array Key 114
Retrieving the Current Array Value 114
Retrieving the Current Array Key and Value 115
Moving the Array Pointer 115
Passing Array Values to a Function 116
Determining Array Size and Uniqueness 117
Determining the Size of an Array 117
Counting Array Value Frequency .118
Determining Unique Array Values 119
Sorting Arrays 119
Reversing Array Element Order 119
Flipping Array Keys and Values 121
Sorting an Array 121
Merging, Slicing, Splicing, and Dissecting Arrays 126
Merging Arrays 127
Recursively Appending Arrays 127
Combining Two Arrays 128
Slicing an Array 128
Splicing an Array 129
Calculating an Array Intersection 131
Calculating Associative Array Intersections 131
ix
« CONTENTS
Calculating Array Differences 132
Calculating Associative Array Differences 133
Other Useful Array Functions 133
Returning a Random Set of Keys 133
Shuffling Array Elements 134
Summary 135
Chapter 6: Object-Oriented PHP 135
The Benefits of OOP 135
Encapsulation 135
Inheritance 136
Polymorphism 136
Key OOP Concepts 137
Classes 137
Objects 138
Properties 138
Constants 144
Methods 145
Constructors and Destructors 149
Constructors 149
Destructors 152
Static Class Members 153
The instanceof Keyword 154
Helper Functions 154
Autoloading Objects 157
Summary 157
a Chapter 7: Advanced OOP Features 159
Advanced OOP Features Not Supported by PHP 159
X
» CONTENTS
Object Cloning .160
Cloning Example 160
The _clone() Method 162
Inheritance 163
Class Inheritance 163
Inheritance and Constructors 165
Inheritance and Late Static Binding 167
Interfaces .168
Implementing a Single Interface 169
Implementing Multiple Interfaces 170
Abstract Classes 171
Introducing Namespaces 172
Summary 174
Chapter 8: Error and Exception Handling 175
Configuration Directives 175
Error Logging 179
Exception Handling 182
Why Exception Handling Is Handy 182
PHP's Exception-Handling Implementation 183
SPL's Exceptions 189
Summary 191
Chapter 9: Strings and Regular Expressions 191
Regular Expressions ,191
Regular Expression Syntax (POSIX) 192
PHP's Regular Expression Functions (POSIX Extended) 194
Regular Expression Syntax (Perl) 198
Other String-Specific Functions 205
m CONTENTS
Determining the Length of a String 206
Comparing Two Strings 206
Manipulating String Case 209
Converting Strings to and from HTML 211
Alternatives for Regular Expression Functions 216
Padding and Stripping a String 223
Counting Characters and Words 225
Taking Advantage of PEAR: ValidateJJS 227
Installing ValidateJJS 227
Using ValidateJJS 228
Summary 228
Chapter 10: Working with the File and Operating System .229
Learning About Files and Directories 230
Parsing Directory Paths 230
Calculating File, Directory, and Disk Sizes 232
Determining Access and Modification Times 235
Working with Files 236
The Concept of a Resource 237
Recognizing Newline Characters 237
Recognizing the End-of-File Character 237
Opening and Closing a File 237
Reading from a File 239
Writing a String to a File 246
Moving the File Pointer 247
Reading Directory Contents 247
Executing Shell Commands 249
System-Level Program Execution 251
Sanitizing the Input 251
xii
CONTENTS
PHP's Program Execution Functions 252
Summary 255
Chapter 11: PEAR 257
The Power of PEAR: Converting Numeral Formats 257
Installing and Updating PEAR 258
Installing PEAR 258
PEAR and Hosting Companies 260
Updating PEAR 260
Using the PEAR Package Manager 260
Viewing an Installed PEAR Package 261
Learning More about an Installed PEAR Package 261
Installing a PEAR Package 262
Including a Package within Your Scripts 264
Upgrading Packages 264
Uninstalling a Package 265
Downgrading a Package 266
Introducing Pyrus 266
Installing Pyrus 266
Summary 267
Chapter 12: Date and Time 269
The Unix Timestamp 269
PHP's Date and Time Library 270
Validating Dates 270
Formatting Dates and Times 271
Converting a Timestamp to User-Friendly Values 275
Working with Timestamps 276
Date Fu 277
Displaying the Localized Date and Time 277
xiii
CONTENTS
Displaying the Web Page's Most Recent Modification Date 282
Determining the Number of Days in the Current Month 282
Determining the Number of Days in Any Given Month 282
Calculating the Date X Days from the Present Date 283
Date and Time Enhancements for PHP 5.1+ Users 283
Introducing the DateTime Constructor 284
Formatting Dates 284
Setting the Date After Instantiation 284
Setting the Time After Instantiation 285
Modifying Dates and Times 285
Calculating the Difference between Two Dates 286
Summary 286
Chapter 13: Working with HTML Forms 287
PHP and Web Forms 287
A Simple Example 288
Validating Form Data 289
File Deletion 289
Cross-Site Scripting 290
Sanitizing User Input 291
Validating and Sanitizing Data with the Filter Extension 294
Working with Multivalued Form Components 296
Taking Advantage of PEAR: HTML_QuickForm2 297
Installing HTML_QuickForm2 298
Creating and Validating a Simple Form 298
Summary 301
Chapter 14: Authenticating Your Users 303
HTTP Authentication Concepts 303
Using Apache's .htaccess Feature 304
xiv
CONTENTS
Authenticating Your Users with PHP 305
PHP's Authentication Variables 305
Useful Functions 306
Hard-Coded Authentication 307
File-Based Authentication 308
Database-Based Authentication 309
Taking Advantage of PEAR: Auth_HTTP 311
User Login Administration 313
Testing Password Guessability with the CrackLib Library 313
One-Time URLs and Password Recovery 315
Summary 318
Chapter 15: Handling File Uploads 319
Uploading Files via HTTP 319
Uploading Files with PHP 320
PHP's File Upload/Resource Directives 320
The $_FILES Array 322
PHP's File-Upload Functions 322
Upload Error Messages 324
A Simple Example 325
Taking Advantage of PEAR: HTTPJJpload 326
Installing HTTPJJpload 326
Uploading a File 326
Learning More About an Uploaded File 327
Uploading Multiple Files 328
Summary 329
Chapter 16: Networking 331
DNS, Services, and Servers 331
DNS 332
xv
CONTENTS
Services 336
Establishing Socket Connections 337
Mail 339
Configuration Directives 339
Sending E-mail Using a PHP Script 340
Common Networking Tasks 344
Pinging a Server 345
Creating a Port Scanner 345
Creating a Subnet Converter 346
Testing User Bandwidth 348
Summary... 349
Chapter 17: PHP and LDAP 351
Using LDAP from PHP 352
Configuring LDAP for PHP 352
Connecting to an LDAP Server 352
Retrieving LDAP Data 355
Counting Retrieved Entries 358
Sorting LDAP Records 359
Inserting LDAP Data 360
Updating LDAP Data 361
Deleting LDAP Data 362
Working with the Distinguished Name 363
Error Handling 364
Summary 365
Chapter 18: Session Handlers 367
What Is Session Handling? 367
The Session-Handling Process 368
Configuration Directives 369
xvi
CONTENTS
Managing the Session Storage Media 369
Setting the Session Files Path.
369
Automatically Enabling Sessions 370
Setting the Session Name 370
Choosing Cookies or URL Rewriting 370
Automating URL Rewriting 370
Setting the Session Cookie Lifetime 370
Setting the Session Cookie's Valid URL Path 371
Setting Caching Directions for Session-Enabled Pages 371
Working with Sessions 373
Starting a Session 373
Destroying a Session 373
Setting and Retrieving the Session ID 374
Creating and Deleting Session Variables 374
Encoding and Decoding Session Data 375
Practical Session-Handling Examples 377
Automatically Logging In Returning Users 378
Generating a Recently Viewed Document Index 379
Creating Custom Session Handlers 381
Tying Custom Session Functions into PHP's Logic 382
Using Custom MySQL-Based Session Handlers 382
Summary 385
Chapter 19: Templating with Smarty 387
What's a Templating Engine? 387
Introducing Smarty 389
Installing Smarty 390
Using Smarty 391
Smarty's Presentational Logic 393
xvii
CONTENTS
Comments 394
Variable Modifiers 394
Control Structures 397
Statements 401
Creating Configuration Files 404
configjoad 404
Referencing Configuration Variables 405
Using CSS in Conjunction with Smarty 405
Caching 406
Working with the Cache Lifetime 407
Eliminating Processing Overhead with isCached() 407
Creating Multiple Caches per Template 408
Some Final Words About Caching 409
Summary 409
w Chapter 20: Web Services 411
Why Web Services? 411
Really Simple Syndication 413
Understanding RSS Syntax 414
Introducing SimplePie ,416
Installing SimplePie 416
Parsing a Feed with SimplePie 417
Parsing Multiple Feeds 418
SimpleXML 419
Loading XML 420
Parsing XML 421
Summary 425
» Chapter 21: Securing Your Web Site 427
Configuring PHP Securely 428
xviii
CONTENTS
Security-Related Configuration Parameters 428
Hiding Configuration Details .430
Hiding Apache 430
Hiding PHP 431
Hiding Sensitive Data 432
Hiding the Document Root 432
Denying Access to Certain File Extensions 433
Data Encryption 433
PHP's Encryption Functions 434
The MCrypt Package 434
Summary 436
Chapter 22: Creating Ajax-enhanced Features with jQuery and PHP 437
Introducing Ajax 437
Introducing jQuery 439
Installing jQuery 439
A Simple Example 440
Responding to Events 441
jQuery and the DOM 442
Creating a Username Existence Validator 444
Determining If a Username Exists 445
Summary 448
Chapter 23: Building Web Sites for the World 449
Translating Web Sites with Gettext 450
Step 1: Update the Web Site Scripts 450
Step 2: Create the Localization Repository 452
Step 3: Create the Translation Files 452
Step 4: Translate the Text 453
Step 5: Generate Binary Files 454
xix
CONTENTS
Step 6: Set the Desired Language Within Your Scripts 454
Localizing Dates, Numbers, and Times 455
Summary 456
Chapter 24: Introducing the Zend Framework 457
Introducing MVC 457
PHP's Framework Solutions 459
The CakePHP Framework 460
The Solar Framework 460
The symfony Framework 460
The Zend Framework 461
Introducing the Zend Framework 461
Installing the Zend Framework 462
Creating Your First Zend Framework-Driven Web Site 463
Summary 475
Chapter 25: Introducing MySQL 477
What Makes MySQL So Popular? 477
Flexibility 477
Power 478
Flexible Licensing Options 480
A (Hyper)Active User Community 481
The Evolution of MySQL 481
MySQL 4 481
MySQL 5 482
MySQL 5.1 483
MySQL 5.4 and 5.5 484
Prominent MySQL Users 484
craigslist 484;
Wikipedia 484;
xx
a CONTENTS
Other Prominent Users 484
Summary 485
Chapter 26: Installing and Configuring MySQL , 487
Downloading MySQL 487
Installing MySQL 488
Installing MySQL on Linux 488
Installing and Configuring MySQL on Windows 492
Setting the MySQL Administrator Password 495
Starting and Stopping MySQL 495
Controlling the Daemon Manually 495
Configuring and Optimizing MySQL 496
The mysqld_safe Wrapper 497
MySQL's Configuration and Optimization Parameters 497
The my.cnf File 501
Configuring PHP to Work with MySQL ,504
Reconfiguring PHP on Linux 504
Reconfiguring PHP on Windows 504
Summary 505
Chapter 27: The Many MySQL Clients 505
Introducing the Command-Line Clients 505
The mysql Client 505
The mysqladmin Client 515
Other Useful Clients 517
Client Options 520
MySQL's GUI Client Programs 523
phpMyAdmin 524
Summary 525
CONTENTS
k Chapter 28: MySQL Storage Engines and Data Types 527
Storage Engines 527
MylSAM 528
IBMDB21 530
InnoDB 531
MEMORY 531
MERGE 533
FEDERATED 533
ARCHIVE 534
CSV 535
EXAMPLE 535
BLACKHOLE 535
Storage Engine FAQ 535
Data Types and Attributes 537
Data Types 537
Data Type Attributes 543
Working with Databases and Tables 546
Working with Databases 546
Working with Tables 548
Altering a Table Structure 551
The INFORMATION_SCHEMA 552
Summary 555
it Chapter 29: Securing MySQL 557
What You Should Do First 558
Securing the mysqld Daemon 559
The MySQL Access Privilege System 560
How the Privilege System Works 560'
Where Is Access Information Stored? 562
xxii
• CONTENTS
User and Privilege Management 573
Creating Users 573
Deleting Users 574
Renaming Users 574
The GRANT and REVOKE Commands 575
Reviewing Privileges 581
Limiting User Resources 581
Secure MySQL Connections 582
Grant Options 583
SSL Options 584
Starting the SSL-Enabled MySQL Server 586
Connecting Using an SSL-Enabled Client 586
Storing SSL Options in the my.cnf File 586
Summary 586
Chapter 30: Using PHP with MySQL 587
Installation Prerequisites 588
Enabling the mysqli Extension on Linux/Unix 588
Enabling the mysqli Extension on Windows 588
Using the MySQL Native Driver 588
Managing User Privileges 589
Working with Sample Data 589
Using the mysqli Extension 590
Setting Up and Tearing Down the Connection 590
Handling Connection Errors 591
Retrieving Error Information 591
Storing Connection Information in a Separate File 593
Securing Your Connection Information 593
Interacting with the Database 594
xxiii
st CONTENTS
Sending a Query to the Database 594
Parsing Query Results 596
Determining the Rows Sefected and Rows Affected 598
Working with Prepared Statements 599
Executing Database Transactions 605
Enabling Autocommit Mode 605
Committing a Transaction 605
Rolling Back a Transaction 605
Summary 606
Chapter 31: Introducing PDO 607
Another Database Abstraction Layer? 608
Using PDO 609
Installing PDO 610
PDO's Database Options 610
Connecting to a Database Server and Selecting a Database 611
Handling Errors 613
Getting and Setting Attributes 615
Executing Queries 616
Introducing Prepared Statements 618
Retrieving Data 621
Setting Bound Columns 624
Working with Transactions 625
Summary 626
m Chapter 32: Stored Routines 62?
Should You Use Stored Routines? 627
Stored Routine Advantages 627
Stored Routine Disadvantages 628
How MySQL Implements Stored Routines 629
xxiv
CONTENTS
Creating a Stored Routine 629
Declaring and Setting Variables 632
Executing a Stored Routine 633
Creating and Using Multistatement Stored Routines 634
Calling a Routine from Within Another Routine 641
Modifying a Stored Routine 642
Deleting a Stored Routine 642
Viewing a Routine's Status 643
Viewing a Routine's Creation Syntax 644
Handling Conditions 644
Integrating Routines into Web Applications 645
Creating the Employee Bonus Interface 645
Retrieving Multiple Rows 646
Summary 647
Chapter 33: MySQL Triggers 649
Introducing Triggers 649
Why Use Triggers? 649
Taking Action Before an Event 650
Taking Action After an Event 650
Before Triggers vs. After Triggers 651
MySQL's Trigger Support -652
Creating a Trigger 652
Viewing Existing Triggers 654
Modifying a Trigger • 656
Deleting a Trigger 656
Integrating Triggers into Web Applications 657
Summary 658
XXV
CONTENTS
m Chapter 34: MySQL Views 659
Introducing Views 660
MySQL's View Support 660
Creating and Executing Views 660
Viewing View Information 667
Modifying a View 669
Deleting a View 669
Updating Views 669
Incorporating Views into Web Applications 670
Summary 672
Chapter 35: Practical Database Queries 673
Sample Data 673
Creating Tabular Output with PEAR 674
Installing HTMLJable 674
Creating a Simple Table 675
Creating More Readable Row Output 676
Creating a Table from Database Data 677
Sorting Output 679
Creating Paged Output 680
Listing Page Numbers 682
Querying Multiple Tables with Subqueries 684
Performing Comparisons with Subqueries 681
Determining Existence with Subqueries 685
Performing Database Maintenance with Subqueries 681
Using Subqueries with PHP 687
Iterating Result Sets with Cursors 687
Cursor Basics 688?
Creating a Cursor 688
xxvi
CONTENTS
Opening a Cursor 689
Using a Cursor 689
Closing a Cursor 690
Using Cursors with PHP 690
Summary ,691
Chapter 36: Indexes and Searching 693
Database Indexing 693
Primary Key Indexes 694
Unique Indexes 695
Normal Indexes 696
Full-Text Indexes 698
Indexing Best Practices 701
Forms-Based Searches 702
Performing a Simple Search 702
Extending Search Capabilities 704
Performing a Full-Text Search 705
Summary 707
Chapter 37: Transactions 709
What's a Transaction? 709
MySQL's Transactional Capabilities 710
System Requirements 710
Table Creation 710
A Sample Project 711
Creating Tables and Adding Sample Data 711
Executing an Example Transaction 712
Usage Tips 714
Building Transactional Applications with PHP 715
The Swap Meet Revisited 715
xxvii
* CONTENTS
Summary 717
Chapter 38: Importing and Exporting Data 719
Sample Table 719
Using Data Delimitation 720
Importing Data 720
Importing Data with LOAD DATA INFILE 721
Importing Data with mysqlimport 724
Loading Table Data with PHP 727
Exporting Data 728
SELECT INTO OUTFILE 729
Summary 732
index 733
xxviii