Tải bản đầy đủ (.pdf) (915 trang)

php 6 and mysql 6 bible

Bạn đang xem bản rút gọn của tài liệu. Xem và tải ngay bản đầy đủ của tài liệu tại đây (22.56 MB, 915 trang )

Shelving Category:
COMPUTERS / Internet /
Web Page Design
Reader Level:
Beginning to Advanced
$49.99 USA
$59.99 Canada
Explore PHP syntax,
datatypes, and functions
Create database-driven,
dynamic Web sites
Master server-side
Web programming
Suehring,
Converse, Park
The book you need to succeed!
Harness PHP and MySQL for
robust Web development
Start quickly building dynamic Web applications with
the leading open-source scripting tool, the leading
open-source database, and this comprehensive guide
that shows you exactly how to do it. You’ll learn PHP6
and MySQL inside and out, explore the ups and downs
of using open-source technologies, and discover pages
of tips and techniques that help you get the most out
of this powerful development duo.  is book includes
extensive code examples, full working applications, and
much more.
• Install, develop, debug, and troubleshoot the newest versions of PHP
and MySQL
• Get up to speed on PHP basics, including syntax, datatypes, functions,


and pitfalls
• Review Structured Query Language (SQL) and data administration basics
• Master advanced PHP features, including object-oriented programming
and session handling
• Examine PHP’s interaction with other databases technologies,
such as Oracle
®
• Explore advanced topics, such as PHP with e-mail programs, and PHP
and XML
• Learn how to create a game and much more in extended case studies

PHP6 and MySQL
®
Steve Suehring
is a technology consultant with a
diverse business and computing
background. He is the former security
editor for LinuxWorld Magazine and
has published several books.
Tim Converse
is a software engineer at Inktomi
Corporation, which is owned by
Yahoo!. He has more than a dozen
years of programming experience
in Lisp, C, C++, Java, and Web
techniques, including PHP.
Joyce Park
is a Web developer in Silicon
Valley. She has worked on PHP
projects of all sizes, including

co-lead of the Mod-pulsub project.
Spine: 1.824"
Steve Suehring, Tim Converse, and Joyce Park
PHP6
and MySQL
®
www.it-ebooks.info
84503ffirs.indd 2 12/16/08 1:09:21 PM
www.it-ebooks.info
PHP 6 and
MySQL
®
6
Bible
84503ffirs.indd 1 12/16/08 1:09:21 PM
www.it-ebooks.info
84503ffirs.indd 2 12/16/08 1:09:21 PM
www.it-ebooks.info
Steve Suehring
Tim Converse
Joyce Park
PHP 6 and
MySQL
®
6
Bible
84503ffirs.indd 3 12/16/08 1:09:22 PM
www.it-ebooks.info
PHP 6 and MySQL 6 Bible
Published by

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

Suehring, Steve.
PHP 6 and MySQL 6 bible / Steve Suehring.
p. cm.
Includes index.
ISBN 978-0-470-38450-3 (pbk.)
1. PHP (Computer program language) 2. MySQL (Electronic resource) I. Title.
QA76.73.P224S94 2009
005.2’762 — dc22
2008048198
Trademarks: Wiley and the Wiley logo are trademarks or registered trademarks of John Wiley & Sons, Inc. and/or its
affiliates, in the United States and other countries, and may not be used without written permission. MySQL is a registered
trademark of MySQL AB in the United States, European Union, and other countries. All other trademarks are the property
of their respective owners. Wiley Publishing, Inc. is not associated with any product or vendor mentioned in this book.
Wiley also publishes its books in a variety of electronic formats. Some content that appears in print may not be available
in electronic books.
84503ffirs.indd 4 12/16/08 1:09:22 PM
www.it-ebooks.info
About the Authors
Steve Suehring is a technology consultant with a diverse business and computing background.
Steve’s extensive experience enables him to work cross-functionally within organizations to help
create computing architectures that fit the business need. Steve has written several books and mag-
azine articles and contributed to many others. Steve has spoken internationally at user groups and
conventions. When he has the chance, Steve plays just about any sport or any musical instrument,
some with better success than others.
Tim Converse has written software to recommend neckties, answer questions about space sta-
tions, pick value stocks, and make simulated breakfast. He has an M.S. in Computer Science from
the University of Chicago, where he taught several programming classes. He is now an engineering
manager in the Web search group at Yahoo!.
Joyce Park has an M.A. in history from the University of Chicago, and has worked for several
Silicon Valley startups including Epinions, KnowNow, and Friendster. She is a co-lead of the

Mod-pubsub Open Source project.
84503ffirs.indd 5 12/16/08 1:09:22 PM
www.it-ebooks.info
Acquisitions Editor
Jenny Watson
Development Editor
Christopher J. Rivera
Technical Editor
Aaron Saray
Production Editor
Rachel McConlogue
Copy Editor
Foxxe Editorial Services
Editorial Manager
Mary Beth Wakefield
Production Manager
Tim Tate
Vice President and Executive Group Publisher
Richard Swadley
Vice President and Executive Publisher
Barry Pruett
Associate Publisher
Jim Minatel
Project Coordinator, Cover
Lynsey Stanford
Compositor
Jeffrey Wilson, Happenstance Type-O-Rama
Proofreader
Publication Services, Inc.
Indexer

Ted Laux
Cover Illustration
Joyce Haughey
Cover Designer
Michael E. Trent
Credits
84503ffirs.indd 6 12/16/08 1:09:23 PM
www.it-ebooks.info
Acknowledgments
People sometimes ask me how many books I’ve written. I never have the answer. You see, I’ve con-
tributed to well over a dozen (maybe two dozen or more) books in one form or another, be it a chap-
ter or two here, a section there, a rewrite of an existing title with much new material, a revision of
another edition where the existing material is already pretty good (as was the case for this book), or
an original, authored work. The short answer is: I don’t know. It’s really somewhat difficult to claim
that I, alone, wrote a book. At best I put some words down into a word processor and several other
people look them over, edit them, change them for both technical and grammatical usage, and the
end result is my name on the cover or somewhere in the book, or sometimes not at all.
This brings me to the difficulty at hand. I’ve written a sufficient number books that writing
acknowledgments is becoming a bit mundane. Sure, I’ll thank my wife, Rebecca, and son, Jakob,
for their patience while I wrote this. I’ll thank my family for their continued support. I’ll thank
the Tueschers, Heins, Leus, and Guthries. I’ll thank Jason Keup and Aaron Saray, too. I’ll thank
my agent Neil Salkind at Studio B., Jim Oliva and John Eckendorf, and the 90fm staff along with
Nightmare Squad.
Of course, I’ll thank Tim and Rob @ Partners, and Jay, Deb, and Brian, and Andy Hale and Eliot
Irons and the SecAdmin team. Kyle Mac always gets mad if I don’t include him. There are lot of
people at Knob Hill who deserve thanking, and the like. And I’ll always thank Mark Little and
meek, Pat Dunn, AJ Prowant, and Andy Berkvam. But it’s the people that I don’t thank that always
find me, asking why their name isn’t in this book. With that in mind, I’ll stop here and let them
find me and hope that I write another book where I’ll remember to include them. Just a hint:
Everyone who was thanked here has paid me.

84503ffirs.indd 7 12/16/08 1:09:23 PM
www.it-ebooks.info
84503ffirs.indd 8 12/16/08 1:09:23 PM
www.it-ebooks.info
ix
Introduction xxxv
Part I: Introducing PHP . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1
Chapter 1: Why PHP and MySQL? 3
Chapter 2: Server-Side Scripting Overview 11
Chapter 3: Getting Started with PHP 19
Chapter 4: Learning PHP Syntax and Variables 33
Chapter 5: Learning PHP Control Structures and Functions 59
Chapter 6: Passing Information with PHP 99
Chapter 7: Learning PHP String Handling 113
Chapter 8: Learning Arrays 131
Chapter 9: Learning PHP Number Handling 153
Chapter 10: PHP Gotchas 165
Part II: MySQL Database Integration . . . . . . . . . . . . . . . . . . . . 183
Chapter 11: Introducing Databases and MySQL 185
Chapter 12: Installing MySQL 189
Chapter 13: Learning Structured Query Language (SQL) 193
Chapter 14: Learning Database Administration and Design 207
Chapter 15: Integrating PHP and MySQL 219
Chapter 16: Performing Database Queries 237
Chapter 17: Integrating Web Forms and Databases 253
Chapter 18: Improving Database Efficiency 279
Chapter 19: MySQL Gotchas 295
Part III: More PHP . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 309
Chapter 20: Introducing Object-Oriented PHP 311
Chapter 21: Advanced Array Functions 357

Chapter 22: Examining Regular Expressions 371
Chapter 23: Working with the Filesystem 391
Chapter 24: Working with Cookies and Sessions 409
Chapter 25: Learning PHP Types 433
Chapter 26: Learning PHP Advanced Functions 443
Chapter 27: Performing Math with PHP 455
Chapter 28: Securing PHP 471
Chapter 29: Learning PHP Configuration 483
84503ffirs.indd 9 12/16/08 1:09:23 PM
www.it-ebooks.info
x

Contents at a Glance
Chapter 30: Handing Exceptions with PHP 497
Chapter 31: Debugging PHP Programs 511
Chapter 32: Learning PHP Style 525
Part IV: Other Databases 549
Chapter 33: Connecting PHP and PostgreSQL 551
Chapter 34: Using PEAR DB with PHP 567
Chapter 35: An Overview of Oracle 575
Chapter 36: An Introduction to SQLite 605
Part V: Connections 611
Chapter 37: Sending E-Mail with PHP 613
Chapter 38: Integrating PHP and Java 619
Chapter 39: Integrating PHP and JavaScript 631
Chapter 40: Integrating PHP and XML 647
Chapter 41: Creating and Consuming Web Services with PHP 675
Chapter 42: Creating Graphics with PHP 689
Part VI: Case Studies . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .713
Chapter 43: Developing a Weblog with PHP 715

Chapter 44: A Trivia Game 727
Chapter 45: Data Visualization with Venn Diagrams 771
Appendix A: PHP for C Programmers 795
Appendix B: PHP for Perl Hackers 801
Appendix C: PHP for HTML Coders 809
Appendix D: PHP Resources 817
Appendix E: PEAR 829
Index 841
84503ffirs.indd 10 12/16/08 1:09:23 PM
www.it-ebooks.info
xi
Introduction xxxv
Part I: Introducing PHP 1
Chapter 1: Why PHP and MySQL? 3
What Is PHP? 3
What Is MySQL? 4
Deciding on a Web Application Platform 4
Cost 4
Ease of Use 5
HTML-embeddedness 5
Cross-platform compatibility 7
Stability 7
Many extensions 8
Fast feature development 8
Not proprietary 8
Strong user communities 9
Summary 10
Chapter 2: Server-Side Scripting Overview . . . . . . . . . . . . . . . . . . . . . . . . . . 11
Static HTML 11
Client-Side Technologies 13

Server-Side Scripting 15
What Is Server-Side Scripting Good For? 17
Summary 18
Chapter 3: Getting Started with PHP 19
Installing PHP 19
Installation procedures 20
Installing PHP on CentOS 21
Installing PHP on Debian 22
Installing PHP from source 22
Microsoft Windows and Apache 25
Other web servers 26
Development tools 26
What’s to Come? 27
Your HTML Is Already PHP-Compliant! 27
84503ftoc.indd 11 12/16/08 1:09:40 PM
www.it-ebooks.info
xii

Contents
Escaping from HTML 28
Canonical PHP tags 28
Hello World 28
Jumping in and out of PHP mode 30
Including files 30
Summary 32
Chapter 4: Learning PHP Syntax and Variables . . . . . . . . . . . . . . . . . . . . . . .33
PHP Is Forgiving 33
HTML Is Not PHP 34
PHP’s Syntax Is C-Like 34
PHP is whitespace insensitive 34

PHP is sometimes case sensitive 35
Statements are expressions terminated by semicolons 35
Expressions are combinations of tokens 35
Expressions are evaluated 36
Precedence, associativity, and evaluation order 36
Expressions and types 37
Assignment expressions 37
Reasons for expressions and statements 38
Braces make blocks 38
Comments 39
C-style multiline comments 39
Single-line comments: # and // 39
Variables 40
PHP variables are Perl-like 40
Declaring variables (or not) 40
Assigning variables 41
Reassigning variables 41
Unassigned variables 41
Default values 41
Checking assignment with isset 42
Variable scope 43
Functions and variable scope 43
You can switch modes if you want 43
Constants 44
Types in PHP: Don’t Worry, Be Happy 45
No variable type declarations 45
Automatic type conversion 45
Types assigned by context 45
Type Summary 46
The Simple Types 46

Integers 47
Read formats 47
Range 47
84503ftoc.indd 12 12/16/08 1:09:41 PM
www.it-ebooks.info
xiii
Contents
Doubles 47
Read formats 48
Booleans 49
Boolean constants 49
Interpreting other types as Booleans 49
Examples 50
NULL 50
Strings 51
Singly quoted strings 52
Doubly quoted strings 52
Single versus double quotation marks 53
Variable interpolation 54
Newlines in strings 55
Limits 55
Output 55
Echo and print 55
Echo 56
Print 56
Variables and strings 57
HTML and linebreaks 57
Summary 57
Chapter 5: Learning PHP Control Structures and Functions 59
Boolean Expressions 60

Boolean constants 60
Logical operators 60
Precedence of logical operators 61
Logical operators short-circuit 62
Comparison operators 62
Operator precedence 63
String comparison 63
The ternary operator 65
Branching 65
If-else 65
Else attachment 66
Elseif 67
Switch 69
Looping 71
Bounded loops versus unbounded loops 71
While 71
Do-while 72
For 72
Looping examples 74
A bounded for loop 74
An unbounded while loop 75
Break and continue 76
84503ftoc.indd 13 12/16/08 1:09:41 PM
www.it-ebooks.info
xiv

Contents
A note on infinite loops 79
Alternate Control Syntaxes 79
Terminating Execution 80

Using Functions 83
Return values versus side effects 83
Function Documentation 84
Headers in documentation 85
Finding function documentation 85
Defining Your Own Functions 86
What is a function? 86
Function definition syntax 86
Function definition example 87
Formal parameters versus actual parameters 88
Argument number mismatches 89
Too few arguments 89
Too many arguments 90
Functions and Variable Scope 90
Global versus local 91
Static variables 92
Exceptions 93
Function Scope 95
Include and require 95
Including only once 96
The include path 96
Recursion 96
Summary 98
Chapter 6: Passing Information with PHP . . . . . . . . . . . . . . . . . . . . . . . . . . .99
HTTP Is Stateless 99
GET Arguments 100
A Better Use for GET-Style URLs 102
POST Arguments 104
Formatting Form Variables 106
Consolidating forms and form handlers 109

PHP Superglobal Arrays 110
Summary 111
Chapter 7: Learning PHP String Handling 113
Strings in PHP 113
Interpolation with curly braces 114
Characters and string indexes 115
String operators 115
Concatenation and assignment 116
The heredoc syntax 116
String Functions 117
Inspecting strings 118
84503ftoc.indd 14 12/16/08 1:09:41 PM
www.it-ebooks.info
xv
Contents
Finding characters and substrings 118
Comparison and searching 120
Searching 120
Substring selection 121
String cleanup functions 123
String replacement 124
Case functions 126
strtolower() 126
strtoupper() 127
ucfirst() 127
ucwords() 127
Escaping functions 127
Printing and output 128
Summary 130
Chapter 8: Learning Arrays 131

The Uses of Arrays 131
What Are PHP Arrays? 132
Creating Arrays 134
Direct assignment 134
The array() construct 134
Specifying indices using array() 135
Functions returning arrays 136
Retrieving Values 136
Retrieving by index 136
The list() construct 136
Multidimensional Arrays 137
Inspecting Arrays 139
Deleting from Arrays 140
Iteration 140
Support for iteration 140
Using iteration functions 141
Our favorite iteration method: foreach 142
Iterating with current() and next() 143
Starting over with reset() 145
Reverse order with end() and prev() 146
Extracting keys with key() 147
Empty values and the each() function 147
Walking with array_walk() 149
Summary 151
Chapter 9: Learning PHP Number Handling 153
Numerical Types 153
Mathematical Operators 154
Arithmetic operators 154
Arithmetic operators and types 155
84503ftoc.indd 15 12/16/08 1:09:42 PM

www.it-ebooks.info
xvi

Contents
Incrementing operators 155
Assignment operators 156
Comparison operators 157
Precedence and parentheses 158
Simple Mathematical Functions 158
Randomness 159
Seeding the generator 160
Example: Making a random selection 162
Summary 163
Chapter 10: PHP Gotchas 165
Installation-Related Problems 165
Symptom: Text of file displayed in browser window 166
Symptom: PHP blocks showing up as text under HTTP or browser prompts you to save
file 166
Symptom: Server or host not found/Page cannot be displayed 166
Rendering Problems 166
Symptom: Totally blank page 167
Symptom: PHP code showing up in Web browser 167
Failures to Load Page 168
Symptom: Page cannot be found 168
Symptom: Failed opening [file] for inclusion 169
Parse Errors 169
Symptom: Parse error message 169
The missing semicolon 170
No dollar signs 170
Mode issues 171

Unescaped quotation marks 172
Unterminated strings 172
Other parse error causes 173
Missing Includes 173
Symptom: Include warning 173
Unbound Variables 174
Symptom: Variable not showing up in print string 174
Symptom: Numerical variable unexpectedly zero 174
Causes of unbound variables 174
Case problems 175
Scoping problems 175
Function Problems 176
Symptom: Call to undefined function my_function() 177
Symptom: Call to undefined function () 177
Symptom: Call to undefined function array() 177
Symptom: Cannot redeclare my_function() 177
Symptom: Wrong parameter count 178
84503ftoc.indd 16 12/16/08 1:09:42 PM
www.it-ebooks.info
xvii
Contents
Math Problems 178
Symptom: Division-by-zero warning 178
Symptom: Unexpected arithmetic result 178
Symptom: NaN (or NAN) 178
Timeouts 179
Summary 180
Part II: MySQL Database Integration 183
Chapter 11: Introducing Databases and MySQL 185
What Is a Database? 185

Why a Database? 186
Maintainability and scalability 186
Portability 186
Avoiding awkward programming 187
Searching 187
PHP-Supported Databases 187
Our Focus: MySQL 188
Summary 188
Chapter 12: Installing MySQL 189
Obtaining MySQL 189
Installing MySQL on Linux 189
Installing MySQL Server on Debian and Ubuntu 190
Installing MySQL on Microsoft Windows 191
Installing MySQL on Windows 191
Summary 191
Chapter 13: Learning Structured Query Language (SQL) . . . . . . . . . . . . . . . 193
Relational Databases and SQL 193
SQL Standards 194
The Workhorses of SQL 194
SELECT 195
Selecting Certain Records 195
Joins 196
Subselects 199
INSERT 200
UPDATE 200
DELETE 200
Database Design 201
Privileges and Security 204
Setting database permissions 204
Keep database passwords outside the web area 205

Learn to make backups 206
Summary 206
84503ftoc.indd 17 12/16/08 1:09:42 PM
www.it-ebooks.info
xviii

Contents
Chapter 14: Learning Database Administration and Design 207
Basic MySQL Client Commands 208
MySQL User Administration 209
Local development 211
Standalone web site 211
Shared-hosting web site 211
Backups 212
Replication 214
Recovery 217
myisamchk 217
mysqlcheck 218
Summary 218
Chapter 15: Integrating PHP and MySQL 219
Connecting to MySQL 219
Making MySQL Queries 221
Fetching Data Sets 222
Getting Data about Data 225
Multiple Connections 226
Building in Error Checking 227
Creating MySQL Databases with PHP 229
MySQL data types 230
MySQL Functions 232
Summary 235

Chapter 16: Performing Database Queries 237
HTML Tables and Database Tables 238
One-to-one mapping 238
Example: A single-table displayer 238
The sample tables 240
Improving the displayer 241
Displaying column headers 242
Error checking 242
Cosmetic issues 242
Displaying arbitrary queries 242
Complex Mappings 245
Multiple queries versus complex printing 245
A multiple-query example 246
A complex printing example 248
Creating the Sample Tables 250
Summary 252
Chapter 17: Integrating Web Forms and Databases . . . . . . . . . . . . . . . . . . . 253
HTML Forms 253
Basic Form Submission to a Database 254
84503ftoc.indd 18 12/16/08 1:09:43 PM
www.it-ebooks.info
xix
Contents
Self-Submission 257
Editing Data with an HTML Form 264
TEXT and TEXTAREA 264
CHECKBOX 267
RADIO 269
SELECT 274
Summary 277

Chapter 18: Improving Database Efficiency 279
Connections — Reduce, Reuse, Recycle 279
A bad example: one connection per statement 280
Multiple results don’t need multiple connections 281
Persistent connections 282
Indexing and Table Design 282
Indexing 282
What is an index? 282
Indexing tradeoffs 283
Primary keys 284
Everything including the kitchen sink 285
Other types of indexes 286
Table design 287
Making the Database Work for You 288
It’s probably faster than you are 288
A bad example: looping, not restricting 288
Sorting and aggregating 289
Where possible, use MIN or MAX rather than sorting 289
Creating date and time fields 290
Finding the last inserted row 291
Summary 293
Chapter 19: MySQL Gotchas . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 295
No Connection 295
Problems with Privileges 297
Unescaped Quotes 299
Broken SQL Statements 301
Misspelled names 303
Comma faults 303
Unquoted string arguments 303
Unbound variables 304

Too Little Data, Too Much Data 305
Specific SQL Functions 305
mysql_affected_rows() versus mysql_num_rows() 305
mysql_result() 306
OCI_Fetch() 306
Debugging and Sanity Checking 307
Summary 308
84503ftoc.indd 19 12/16/08 1:09:43 PM
www.it-ebooks.info
xx

Contents
Part III: More PHP 309
Chapter 20: Introducing Object-Oriented PHP . . . . . . . . . . . . . . . . . . . . . . 311
What Is Object-Oriented Programming? 312
The simple idea 312
The procedural approach 312
The object-oriented approach 313
Elaboration: objects as data types 313
Elaboration: Inheritance 315
Elaboration: Encapsulation 315
Elaboration: Constructors and destructors 315
Terminology 316
Basic PHP Constructs for OOP 318
Defining classes 318
Accessing member variables 319
Creating instances 319
Constructor functions 319
Inheritance 320
Overriding functions 322

Chained subclassing 322
Modifying and assigning objects 324
Scoping issues 324
Advanced OOP Features 325
Public, Private, and Protected Members 325
Private members 326
Protected members 326
Interfaces 327
Constants 327
Abstract Classes 328
Simulating class functions 328
Calling parent functions 329
Calling parent constructors 329
Automatic calls to parent constructors 331
Simulating method overloading 331
Serialization 332
Sleeping and waking up 333
Serialization gotchas 334
Introspection Functions 334
Function overview 335
Example: Class genealogy 337
Example: matching variables and DB columns 340
Example: Generalized test methods 342
Extended Example: HTML Forms 346
84503ftoc.indd 20 12/16/08 1:09:43 PM
www.it-ebooks.info
xxi
Contents
Gotchas and Troubleshooting 352
Symptom: Member variable has no value in member function 352

Symptom: Parse error, expecting T_VARIABLE . . . 353
OOP Style in PHP 353
Naming conventions 353
Accessor functions 354
Designing for inheritance 355
Summary 355
Chapter 21: Advanced Array Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . 357
Transformations of Arrays 357
Retrieving keys and values 358
Flipping, reversing, and shuffling 359
Merging, padding, slicing, and splicing 360
Stacks and Queues 363
Translating between Variables and Arrays 365
Sorting 366
Printing Functions for Visualizing Arrays 367
Summary 369
Chapter 22: Examining Regular Expressions 371
Tokenizing and Parsing Functions 371
Why Regular Expressions? 374
Regex in PHP 375
An example of POSIX-style regex 375
Regular expression functions 377
Perl-Compatible Regular Expressions 378
Example: A simple link-scraper 381
The regular expression 381
Using the expression in a function 383
Applying the function 384
Extending the code 384
Advanced String Functions 385
HTML functions 385

Hashing using MD5 386
Strings as character collections 387
String similarity functions 389
Summary 390
Chapter 23: Working with the Filesystem 391
Understanding PHP File Permissions 391
File Reading and Writing Functions 392
File open 393
HTTP fopen 394
FTP fopen 395
84503ftoc.indd 21 12/16/08 1:09:44 PM
www.it-ebooks.info
xxii

Contents
File read 396
Constructing file downloads by using fpassthru() 397
File write 398
File close 399
Filesystem and Directory Functions 400
feof 400
file_exists 400
filesize 400
Network Functions 403
Syslog functions 403
DNS functions 403
Socket functions 404
Date and Time Functions 405
If you don’t know either date or time 405
If you’ve already determined the date/time/timestamp 406

Calendar Conversion Functions 407
Summary 408
Chapter 24: Working with Cookies and Sessions . . . . . . . . . . . . . . . . . . . . .409
What’s a Session? 409
So what’s the problem? 410
Why should you care? 410
Home-grown Alternatives 410
IP address 411
Hidden variables 411
Cookie-based home-grown sessions 412
How Sessions Work in PHP 412
Making PHP aware of your session 413
Propagating session variables 413
The simple approach (using $_SESSION) 413
Where is the data really stored? 414
Sample Session Code 415
Session Functions 419
Configuration Issues 421
Cookies 422
The setcookie() function 422
Examples 423
Deleting cookies 425
Reading cookies 425
Cookie pitfalls 426
Sending something else first 426
Reverse-order interpretation 427
Cookie refusal 427
Sending HTTP Headers 428
Example: Redirection 428
84503ftoc.indd 22 12/16/08 1:09:44 PM

www.it-ebooks.info
xxiii
Contents
Example: HTTP authentication 429
Header gotchas 430
Gotchas and Troubleshooting 430
Summary 431
Chapter 25: Learning PHP Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 433
Type Round-up 433
Resources 434
What are resources? 434
How to handle resources 435
Type Testing 435
Assignment and Coercion 436
Type conversion behavior 436
Explicit conversions 437
Conversion examples 438
Other useful type conversions 440
Integer overflow 441
Finding the largest integer 442
Summary 442
Chapter 26: Learning PHP Advanced Functions 443
Variable Numbers of Arguments 443
Default arguments 444
Arrays as multiple-argument substitutes 445
Multiple arguments in PHP4 and above 446
Call-by-value 447
Call-by-reference 448
Variable function names 450
An extended example 450

Summary 454
Chapter 27: Performing Math with PHP 455
Mathematical Constants 455
Tests on Numbers 456
Base Conversion 457
Exponents and Logarithms 461
Trigonometry 461
Arbitrary Precision (BC) 465
An arbitrary-precision example 466
Converting code to arbitrary-precision 467
Summary 470
Chapter 28: Securing PHP . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 471
Possible Attacks 472
Site defacement 472
Accessing source code 474
84503ftoc.indd 23 12/16/08 1:09:44 PM
www.it-ebooks.info

Tài liệu bạn tìm kiếm đã sẵn sàng tải về

Tải bản đầy đủ ngay
×