1. Trang chủ
  2. » Ngoại Ngữ

PHP MySQL web development3847

1K 30 0

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

THÔNG TIN TÀI LIỆU

Thông tin cơ bản

Định dạng
Số trang 1.009
Dung lượng 12,27 MB

Các công cụ chuyển đổi và chỉnh sửa cho tài liệu này

Nội dung

4 String Manipulation and Regular Expressions 1075 Reusing Code and Writing Functions 133 6 Object-Oriented PHP 159 7 Error and Exception Handling 193 II Using MySQL 8 Designing Your Web

Trang 2

“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 othercomputer-related book I have ever purchased.The text is very easy to follow!”

—Nick Landman

“This book by Welling & Thomson is theonly one which I have found to be indis-pensable.The writing is clear and straightfor-ward but never wastes my time.The book isextremely well laid out.The chapters are theright length and chapter titles quickly takeyou 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 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 It’sobvious 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 can’t put

it 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 express

to you how pleased I have been with this book.”

—Tim Luoma,TnTLuoma.com

“Welling and Thomson’s 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

Trang 3

“This book is absolutely excellent, tosay the least… Luke Welling and LauraThomson give the best in-depth explana-tions I’ve 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 didn’t quite understand….This book jumps right intothe functions and features most commonlyused with PHP, and from there it continues

in describing real-world projects, MySQLintegration, and security issues from a proj-ect manager’s 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 didn’t need a lot of helpwith PHP syntax; after all, it’s very close toC/C++ I don’t 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 have

O’Reilly’s mSQL and MySQL book, and

it’s probably a better pure-SQL reference,but this book has earned a place on my reference shelf…Highly recommended.”

—Paul Robichaux

“One of the best programming guidesI’ve ever read.”

—jackofsometrades from Lahti, Finland

“This is a well-written book for 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.”

learn-—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 I’m 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 can’tput 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 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.”

recom-—Sean C Schertell

Trang 4

PHP and MySQL ®

Web Development

Fourth Edition

Trang 6

PHP and MySQL ®

Web Development

Luke Welling Laura Thomson

Fourth Edition

Upper Saddle River, NJ •Boston •Indianapolis •San FranciscoNew York •Toronto •Montreal •London •Munich •Paris •MadridCape Town •Sydney •Tokyo •Singapore •Mexico City

Trang 7

Library of Congress Cataloging-in-Publication Data Welling, Luke, 1972-

PHP and MySQL Web development / Luke Welling, Laura Thomson 4th ed.

p cm.

ISBN 978-0-672-32916-6 (pbk w/cd)

1 PHP (Computer program language) 2 SQL (Computer program language)

3 MySQL (Electronic resource) 4 Web sites Design I Thomson, Laura II Title

QA76.73.P224W45 2008 005.2'762 dc22

2008036492 Printed in the United States of America

First Printing: September 2009 ISBN-10: 0-672-32916-6 ISBN-13: 978-0-672-32916-6 Trademarks

All terms mentioned in this book that are known to be trademarks or ice marks have been appropriately capitalized Pearson Education, Inc.

serv-cannot attest to the accuracy of this information Use of a term in this book should not be regarded as affecting the validity of any trademark or service mark.

Warning and Disclaimer Every effort has been made to make this book as complete and as accurate

as possible, but no warranty or fitness is implied The information provided

is on an “as is” basis The authors and the publisher shall have neither bility nor responsibility to any person or entity with respect to any loss or damages arising from the information contained in this book or from the use

lia-of the CD-ROM or programs accompanying it.

Bulk Sales Pearson Education, Inc offers excellent discounts on this book when ordered in quantity for bulk purchases or special sales For more informa- tion, please contact

U.S Corporate and Government Sales 1-800-382-3419

corpsales@pearsontechgroup.com

For sales outside the U.S., please contact

International Sales international@pearsoned.com

Trang 8

To our Mums and Dads

Trang 9

4 String Manipulation and Regular Expressions 107

5 Reusing Code and Writing Functions 133

6 Object-Oriented PHP 159

7 Error and Exception Handling 193

II Using MySQL

8 Designing Your Web Database 207

9 Creating Your Web Database 219

10 Working with Your MySQL Database 243

11 Accessing Your MySQL Database from the Web with PHP 267

12 Advanced MySQL Administration 287

13 Advanced MySQL Programming 311

III E-commerce and Security

14 Running an E-commerce Site 327

15 E-commerce Security Issues 341

16 Web Application Security 361

17 Implementing Authentication with PHP andMySQL 391

18 Implementing Secure Transactions with PHP andMySQL 409

Trang 10

IV Advanced PHP Techniques

19 Interacting with the File System and the Server431

20 Using Network and Protocol Functions 451

21 Managing the Date and Time 469

22 Generating Images 483

23 Using Session Control in PHP 509

24 Other Useful Features 525

V Building Practical PHP and MySQL Projects

25 Using PHP and MySQL for Large Projects 535

26 Debugging 551

27 Building User Authentication and Personalization569

28 Building a Shopping Cart 607

29 Building a Web-Based Email Service 651

30 Building a Mailing List Manager 687

31 Building Web Forums 741

32 Generating Personalized PDF Documents 771

33 Connecting to Web Services with XML and SOAP807

34 Building Web 2.0 Applications with Ajax 855

VI Appendixes

A Installing PHP and MySQL 889

B Web Resources 907Index 911

Trang 11

Processing the Form 16Embedding PHP in HTML 17PHP Tags 18

PHP Statements 19Whitespace 20Comments 20Adding Dynamic Content 21Calling Functions 22Using the date() Function 22Accessing Form Variables 23Short, Medium, and Long Variables 23String Concatenation 26

Variables and Literals 27Understanding Identifiers 28Examining Variable Types 29PHP’s Data Types 29Type Strength 29Type Casting 30Variable Variables 30Declaring and Using Constants 31Understanding Variable Scope 31Using Operators 32

Arithmetic Operators 33String Operators 34

Trang 12

Assignment Operators 34Comparison Operators 36Logical Operators 38Bitwise Operators 38Other Operators 39Working Out the Form Totals 41Understanding Precedence and Associativity 42Using Variable Functions 44

Testing and Setting Variable Types 44Testing Variable Status 45

Reinterpreting Variables 46Making Decisions with Conditionals 46

if Statements 46Code Blocks 47else Statements 47elseif Statements 48switch Statements 49Comparing the Different Conditionals 51Repeating Actions Through Iteration 51while Loops 53

for and foreach Loops 54do while Loops 55Breaking Out of a Control Structure or Script 56Employing Alternative Control Structure Syntax 56Using declare 57

Next 57

Saving Data for Later 59Storing and Retrieving Bob’s Orders 60Processing Files 61

Opening a File 61Choosing File Modes 61Using fopen() to Open a File 62Opening Files Through FTP or HTTP 64Addressing Problems Opening Files 65

Trang 13

Writing to a File 67Parameters for fwrite() 68File Formats 68

Closing a File 69Reading from a File 71Opening a File for Reading: fopen() 72Knowing When to Stop: feof() 73Reading a Line at a Time: fgets(), fgetss(), andfgetcsv() 73

Reading the Whole File: readfile(), fpassthru(), andfile() 74

Reading a Character: fgetc() 75Reading an Arbitrary Length: fread() 75Using Other Useful File Functions 76Checking Whether a File Is There:

file_exists() 76Determining How Big a File Is: filesize() 76Deleting a File: unlink() 76

Navigating Inside a File: rewind(), fseek(), andftell() 76

Using Loops to Access the Array 84Arrays with Different Indices 85

Initializing an Array 85Accessing the Array Elements 85Using Loops 85

Trang 14

xiii Contents

Array Operators 87Multidimensional Arrays 88Sorting Arrays 92

Using sort() 92Using asort() and ksort() to Sort Arrays 93Sorting in Reverse 93

Sorting Multidimensional Arrays 93User-Defined Sorts 93Reverse User Sorts 95Reordering Arrays 96Using shuffle() 96Using array_reverse() 97Loading Arrays from Files 98Performing Other Array Manipulations 102Navigating Within an Array: each(), current(),reset(), end(), next(), pos(), and prev() 102Applying Any Function to Each Element in anArray: array_walk() 103

Counting Elements in an Array: count(), sizeof(),and array_count_values() 104

Converting Arrays to Scalar Variables:

extract() 105Further Reading 106Next 106

4 String Manipulation and Regular

Joining and Splitting Strings with String Functions 116

Using explode(), implode(), and join() 116Using strtok() 117

Using substr() 118

Trang 15

Comparing Strings 119Performing String Ordering: strcmp(),strcasecmp(), and strnatcmp() 119Testing String Length with strlen() 120Matching and Replacing Substrings with StringFunctions 120

Finding Strings in Strings: strstr(), strchr(),strrchr(), and stristr() 120

Finding the Position of a Substring: strpos() andstrrpos() 121

Replacing Substrings: str_replace() andsubstr_replace() 122

Introducing Regular Expressions 123The Basics 124

Character Sets and Classes 124Repetition 126

Subexpressions 126Counted Subexpressions 126Anchoring to the Beginning or End of a String 126

Branching 127Matching Literal Special Characters 127Reviewing the Special Characters 127Putting It All Together for the Smart Form 128Finding Substrings with Regular Expressions 129Replacing Substrings with Regular Expressions 130Splitting Strings with Regular Expressions 130Further Reading 131

Next 131

The Advantages of Reusing Code 133Cost 134

Reliability 134Consistency 134Using require() and include() 134Filename Extensions and require() 135Using require() for Website Templates 137

Trang 16

xv Contents

Using auto_prepend_file and auto_append_file 142Using Functions in PHP 143Calling Functions 143Calling an Undefined Function 145Understanding Case and Function Names 146Defining Your Own Functions 146

Examining Basic Function Structure 146Naming Your Function 147Using Parameters 148

Understanding Scope 150Passing by Reference Versus Passing by Value 153Using the return Keyword 154

Returning Values from Functions 155Implementing Recursion 156

Namespaces 158Further Reading 158Next 158

Understanding Object-Oriented Concepts 160Classes and Objects 160

Polymorphism 161Inheritance 162Creating Classes, Attributes, and Operations in PHP162

Structure of a Class 162Constructors 163Destructors 163Instantiating Classes 164Using Class Attributes 164Controlling Access with private and public 166Calling Class Operations 167

Implementing Inheritance in PHP 168Controlling Visibility Through Inheritance withprivate and protected 169

Trang 17

Overriding 170Preventing Inheritance and Overriding with final172

Understanding Multiple Inheritance 173Implementing Interfaces 173

Designing Classes 174Writing the Code for Your Class 175Understanding Advanced Object-OrientedFunctionality in PHP 183

Using Per-Class Constants 184Implementing Static Methods 184Checking Class Type and Type Hinting 184Late Static Bindings 185

Cloning Objects 186Using Abstract Classes 186Overloading Methods with call() 186Using autoload() 187

Implementing Iterators and Iteration 188Converting Your Classes to Strings 190Using the Reflection API 190

Next 191

Exception Handling Concepts 193The Exception Class 195

User-Defined Exceptions 196Exceptions in Bob’s Auto Parts 199Exceptions and PHP’s Other Error HandlingMechanisms 202

Further Reading 203Next 203

II Using MySQL

Relational Database Concepts 208Tables 208

Columns 209

Trang 18

xvii Contents

Rows 209Values 209Keys 209Schemas 210Relationships 211Designing Your Web Database 211Think About the Real-World Objects You AreModeling 211

Avoid Storing Redundant Data 212Use Atomic Column Values 214Choose Sensible Keys 215Think About What You Want to Ask the Database 215

Avoid Designs with Many Empty Attributes 215

Summary of Table Types 216Web Database Architecture 216Further Reading 218

Next 218

Using the MySQL Monitor 220Logging In to MySQL 221Creating Databases and Users 222Setting Up Users and Privileges 223Introducing MySQL’s Privilege System 223Principle of Least Privilege 223User Setup:The GRANT Command 223Types and Levels of Privileges 225The REVOKE Command 227Examples Using GRANT and REVOKE 227Setting Up a User for the Web 228

Using the Right Database 229Creating Database Tables 229Understanding What the Other Keywords Mean 231

Understanding the Column Types 232

Trang 19

Looking at the Database with SHOW andDESCRIBE 233

Creating Indexes 234Understanding MySQL Identifiers 235Choosing Column Data Types 236Numeric Types 236

Date and Time Types 238String Types 239

Further Reading 241Next 241

What Is SQL? 243Inserting Data into the Database 244Retrieving Data from the Database 246Retrieving Data with Specific Criteria 248Retrieving Data from Multiple Tables 249Retrieving Data in a Particular Order 255Grouping and Aggregating Data 256Choosing Which Rows to Return 258Using Subqueries 258

Updating Records in the Database 261Altering Tables After Creation 261Deleting Records from the Database 264Dropping Tables 264

Dropping a Whole Database 264Further Reading 265

Choosing a Database to Use 274

Trang 20

xix Contents

Querying the Database 274Retrieving the Query Results 275Disconnecting from the Database 276Putting New Information in the Database 276Using Prepared Statements 280

Using Other PHP-Database Interfaces 282Using a Generic Database Interface: PEARMDB2 282

Further Reading 285Next 285

Understanding the Privilege System in Detail 287The user Table 289

The db and host Tables 290The tables_priv, columns_priv, and procs privTables 292

Access Control: How MySQL Uses the GrantTables 293

Updating Privileges:When Do Changes TakeEffect? 293

Making Your MySQL Database Secure 294MySQL from the Operating System’s Point ofView 294

Passwords 295User Privileges 295Web Issues 296Getting More Information About Databases 296Getting Information with SHOW 296Getting Information About Columns withDESCRIBE 299

Understanding How Queries Work withEXPLAIN 299

Optimizing Your Database 304Design Optimization 304Permissions 304

Table Optimization 304

Trang 21

Using Indexes 305Using Default Values 305Other Tips 305

Backing Up Your MySQL Database 305Restoring Your MySQL Database 306Implementing Replication 306Setting Up the Master 307Performing the Initial Data Transfer 307Setting Up the Slave or Slaves 308Further Reading 309

Next 309

The LOAD DATA INFILE Statement 311Storage Engines 312

Transactions 313Understanding Transaction Definitions 313Using Transactions with InnoDB 314Foreign Keys 315

Stored Procedures 316Basic Example 316Local Variables 319Cursors and Control Structures 319Further Reading 323

Next 323

III E-commerce and Security

Deciding What You Want to Achieve 327Considering the Types of Commercial Websites 327Publishing Information Using Online

Brochures 328Taking Orders for Goods or Services 331

Trang 22

xxi Contents

Providing Services and Digital Goods 334Adding Value to Goods or Services 335Cutting Costs 335

Understanding Risks and Threats 336Crackers 337

Failure to Attract Sufficient Business 337Computer Hardware Failure 337Power, Communication, Network, or ShippingFailures 338

Extensive Competition 338Software Errors 338Evolving Governmental Policies and Taxes 339System Capacity Limits 339

Choosing a Strategy 339Next 339

How Important Is Your Information? 342Security Threats 342

Exposure of Confidential Data 343Loss or Destruction of Data 344Modification of Data 345Denial of Service 346Errors in Software 347Repudiation 348Usability, Performance, Cost, and Security 349Creating a Security Policy 349

Authentication Principles 350Encryption Basics 351Private Key Encryption 353Public Key Encryption 353Digital Signatures 354Digital Certificates 355Secure Web Servers 356Auditing and Logging 357

Trang 23

Firewalls 357Data Backups 358Backing Up General Files 358Backing Up and Restoring Your MySQLDatabase 358

Physical Security 359Next 359

Strategies for Dealing with Security 361Start with the Right Mindset 362Balancing Security and Usability 362Monitoring Security 363

Our Basic Approach 363Identifying the Threats We Face 363Access to or Modification of Sensitive Data 363Loss or Destruction of Data 364

Denial of Service 364Malicious Code Injection 365Compromised Server 365Understanding Who We’re Dealing With 365Crackers 366

Unwitting Users of Infected Machines 366Disgruntled Employees 366

Hardware Thieves 366Ourselves 366Securing Your Code 367Filtering User Input 367Escaping Output 371Code Organization 374What Goes in Your Code 374File System Considerations 375Code Stability and Bugs 376Execution Quotes and exec 377Securing Your Web Server and PHP 378Keep Software Up-to-Date 378Browse the php.ini file 380

Trang 24

xxiii Contents

Web Server Configuration 380Commercially Hosted Web Applications 382Database Server Security 383

Users and the Permissions System 383Sending Data to the Server 384Connecting to the Server 384Running the Server 385Protecting the Network 385Install Firewalls 386Use a DMZ 386Prepare for DoS and DDoS Attacks 387Computer and Operating System Security 387Keep the Operating System Up-to-Date 387Run Only What Is Necessary 388

Physically Secure the Server 388Disaster Planning 388

Next 390

17 Implementing Authentication with PHP and

Identifying Visitors 391Implementing Access Control 392Storing Passwords 395Encrypting Passwords 397Protecting Multiple Pages 399Using Basic Authentication 399Using Basic Authentication in PHP 400Using Basic Authentication with Apache’s htaccessFiles 402

Using mod_auth_mysql Authentication 406Installing mod_auth_mysql 406Using mod_auth_mysql 407Creating Your Own Custom Authentication 408Further Reading 408

Next 408

Trang 25

18 Implementing Secure Transactions with

Providing Secure Transactions 409The User’s Machine 410The Internet 411Your System 412Using Secure Sockets Layer (SSL) 413Screening User Input 417

Providing Secure Storage 417Storing Credit Card Numbers 419Using Encryption in PHP 419Installing GPG 420Testing GPG 422Further Reading 427Next 428

IV Advanced PHP Techniques

19 Interacting with the File System and the

Uploading Files 431HTML for File Upload 433Writing the PHP to Deal with the File 434Avoiding Common Upload Problems 438Using Directory Functions 439

Reading from Directories 439Getting Information About the CurrentDirectory 442

Creating and Deleting Directories 443Interacting with the File System 443Getting File Information 444Changing File Properties 446Creating, Deleting, and Moving Files 447Using Program Execution Functions 447

Trang 26

xxv Contents

Interacting with the Environment: getenv() andputenv() 450

Further Reading 450Next 450

Examining Available Protocols 451Sending and Reading Email 452Using Data from Other Websites 452Using Network Lookup Functions 455Backing Up or Mirroring a File 459Using FTP to Back Up or Mirror a File 459Uploading Files 466

Avoiding Timeouts 467Using Other FTP Functions 467Further Reading 468

Next 468

Getting the Date and Time from PHP 469Using the date() Function 469Dealing with Unix Timestamps 471Using the getdate() Function 473Validating Dates with checkdate() 474Formatting Timestamps 474

Converting Between PHP and MySQL Date Formats 476

Calculating Dates in PHP 477Calculating Dates in MySQL 478Using Microseconds 480

Using the Calendar Functions 480Further Reading 481

Next 481

Trang 27

22 Generating Images 483

Setting Up Image Support in PHP 484Understanding Image Formats 484JPEG 485

PNG 485WBMP 485GIF 485Creating Images 486Creating a Canvas Image 487Drawing or Printing Text on the Image 487Outputting the Final Graphic 489

Cleaning Up 490Using Automatically Generated Images in Other Pages 490

Using Text and Fonts to Create Images 491Setting Up the Base Canvas 495Fitting the Text onto the Button 495Positioning the Text 498

Writing the Text onto the Button 499Finishing Up 499

Drawing Figures and Graphing Data 499Using Other Image Functions 507Further Reading 507

Next 508

What Is Session Control? 509Understanding Basic Session Functionality 509What Is a Cookie? 510

Setting Cookies from PHP 510Using Cookies with Sessions 511Storing the Session ID 511Implementing Simple Sessions 512Starting a Session 512Registering Session Variables 513

Trang 28

xxvii Contents

Using Session Variables 513Unsetting Variables and Destroying the Session 513

Creating a Simple Session Example 514Configuring Session Control 516Implementing Authentication with Session Control 517

Further Reading 524Next 524

Evaluating Strings: eval() 525Terminating Execution: die() and exit() 526Serializing Variables and Objects 526Getting Information About the PHP Environment 528

Finding Out What Extensions Are Loaded 528Identifying the Script Owner 529

Finding Out When the Script Was Modified 529

Temporarily Altering the Runtime Environment 529Highlighting Source Code 530

Using PHP on the Command Line 531Next 532

V Building Practical PHP and MySQL Projects

25 Using PHP and MySQL for Large

Trang 29

Using a Standard Directory Structure 542Documenting and Sharing In-House Functions 542

Implementing Version Control 542Choosing a Development Environment 544Documenting Your Projects 544

Prototyping 545Separating Logic and Content 546Optimizing Code 546

Using Simple Optimizations 547Using Zend Products 547Testing 548

Further Reading 549Next 549

Programming Errors 551Syntax Errors 552Runtime Errors 553Logic Errors 558Variable Debugging Aid 559Error Reporting Levels 562Altering the Error Reporting Settings 563Triggering Your Own Errors 564

Handling Errors Gracefully 565Next 567

27 Building User Authentication and

Solution Components 569User Identification and Personalization 570Storing Bookmarks 571

Recommending Bookmarks 571Solution Overview 571

Implementing the Database 573

Trang 30

xxix Contents

Implementing the Basic Site 574Implementing User Authentication 577Registering Users 577

Logging In 584Logging Out 587Changing Passwords 588Resetting Forgotten Passwords 591Implementing Bookmark Storage and Retrieval 596Adding Bookmarks 596

Displaying Bookmarks 599Deleting Bookmarks 600Implementing Recommendations 602Considering Possible Extensions 606Next 606

Solution Components 607Building an Online Catalog 608Tracking Users’ Purchases While They Shop 608

Implementing a Payment System 608Building an Administration Interface 609Solution Overview 609

Implementing the Database 612Implementing the Online Catalog 615Listing Categories 617

Listing Books in a Category 620Showing Book Details 622Implementing the Shopping Cart 623Using the show_cart.php Script 623Viewing the Cart 627

Adding Items to the Cart 630Saving the Updated Cart 631Printing a Header Bar Summary 632Checking Out 633

Trang 31

Implementing Payment 639Implementing an Administration Interface 641Extending the Project 650

Using an Existing System 650Next 650

Solution Components 651Mail Protocols: POP3 Versus IMAP 651POP3 and IMAP Support in PHP 652Solution Overview 654

Setting Up the Database 655Examining the Script Architecture 657Logging In and Out 663

Setting Up Accounts 666Creating a New Account 668Modifying an Existing Account 670Deleting an Account 670

Reading Mail 671Selecting an Account 671Viewing Mailbox Contents 674Reading a Mail Message 677Viewing Message Headers 680Deleting Mail 681

Sending Mail 682Sending a New Message 682Replying To or Forwarding Mail 684Extending the Project 686

Next 686

Solution Components 687Setting Up a Database of Lists and Subscribers688

Uploading Newsletters 688Sending Mail with Attachments 689

Trang 32

xxxi Contents

Solution Overview 689Setting Up the Database 692Defining the Script Architecture 694Implementing Login 702

Creating a New Account 702Logging In 705

Implementing User Functions 708Viewing Lists 708

Viewing List Information 713Viewing List Archives 716Subscribing and Unsubscribing 717Changing Account Settings 719Changing Passwords 719Logging Out 721Implementing Administrative Functions 721Creating a New List 722

Uploading a New Newsletter 724Handling Multiple File Upload 727Previewing the Newsletter 732Sending the Message 733Extending the Project 740Next 740

Understanding the Process 741Solution Components 742Solution Overview 743Designing the Database 744Viewing the Tree of Articles 747Expanding and Collapsing 749Displaying the Articles 752Using the treenode Class 753Viewing Individual Articles 760Adding New Articles 762Adding Extensions 769

Trang 33

Using an Existing System 770Next 770

32 Generating Personalized PDF

Project Overview 771Evaluating Document Formats 772Solution Components 776

Question and Answer System 776Document Generation Software 776Solution Overview 778

Asking the Questions 780Grading the Answers 782Generating an RTF Certificate 784Generating a PDF Certificate from a Template 788

Generating a PDF Document Using PDFlib 792

A Hello World Script for PDFlib 792Generating a Certificate with PDFlib 796Handling Problems with Headers 804

Extending the Project 805Next 805

33 Connecting to Web Services with XML and

Project Overview:Working with XML and WebServices 807

Understanding XML 808Understanding Web Services 811Solution Components 813

Using Amazon’s Web Services Interfaces 813Parsing XML: REST Responses 814Using SOAP with PHP 814Caching 815

Trang 34

xxxiii Contents

Solution Overview 815Core Application 820Showing Books in a Category 826Getting an AmazonResultSet Class 828Using REST to Make a Request and Retrieve aResult 838

Using SOAP to Make a Request and Retrieve aResult 845

Caching the Data from a Request 846Building the Shopping Cart 849Checking Out to Amazon 852Installing the Project Code 853Extending the Project 854Further Reading 854

34 Building Web 2.0 Applications with

What Is Ajax? 856HTTP Requests and Responses 856DHTML and XHTML 857Cascading Style Sheets (CSS) 858Client-Side Programming 859Server-Side Programming 860XML and XSLT 860

Fundamental Ajax 860The XMLHTTPRequest Object 860Communicating with the Server 862Working with the Server Response 864Putting It All Together 866

Adding Ajax Elements to Earlier Projects 870Adding Ajax Elements to PHPbookmark 870For More Information 884

Trang 35

Learning More about the Document ObjectModel (DOM) 884

JavaScript Libraries for Ajax Applications 884Ajax Developer Websites 885

Appendixes

Installing Apache, PHP, and MySQL Under Unix 890Binary Installation 890

Source Installation 891httpd.conf File: Snippets 896

Is PHP Support Working? 897

Is SSL Working? 898Installing Apache, PHP, and MySQL Under Windows 899

Installing MySQL Under Windows 900Installing Apache Under Windows 901Installing PHP for Windows 903Installing PEAR 905

Setting Up Other Configurations 906

PHP Resources 907MySQL and SQL Specific Resources 909Apache Resources 909

Web Development 910

Trang 36

Lead Authors

Laura Thomsonis a senior software engineer at Mozilla Corporation She was

former-ly a principal at both OmniTI and Tangled Web Design, and she has worked for RMITUniversity 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 In her spare time she enjoys riding horses, arguingabout free and open source software, and sleeping

Luke Wellingis a web architect at OmniTI and regularly speaks on open source andweb development topics at conferences such as OSCON, ZendCon, MySQLUC,PHPCon, OSDC, and LinuxTag Prior to joining OmniTI, he worked for the web ana-lytics company Hitwise.com, at the database vendor MySQL AB, and as an independentconsultant at Tangled Web Design He has taught computer science at RMIT University

in Melbourne, Australia, and holds a Bachelor of Applied Science (Computer Science)degree In his spare time, he attempts to perfect his insomnia

Contributing Authors

Julie C Meloniis the technical director for i2i Interactive (www.i2ii.com), a dia company located in Los Altos, California She has been developing web-based applications since the Web first saw the light of day and remembers the excitement surrounding the first GUI web browser She has authored numerous books and articles

multime-on web-based programming languages and database topics, including the bestselling Sams

Teach Yourself PHP, MySQL, and Apache All in One.

Adam DeFieldsis a consultant specializing in web application development, projectmanagement, and instructional design He lives in Grand Rapids, Michigan where heruns Emanation Systems, LLC, (www.emanationsystemsllc.com) a company he founded

in 2002 He has been involved with web development projects using several differenttechnologies, but has developed a strong preference toward PHP/MySQL-based projects

Marc Wandschneideris a freelance software developer, author, and speaker who travelsthe globe working on interesting projects In recent years, a lot of his attention hasbeen focused on writing robust and scalable web applications, and in 2005 he wrote a

book called Core Web Application Programming with PHP and MySQL He was was

previ-ously the main developer of the SWiK (http://swik.net) open source community site.Marc currently lives in Beijing where he spends his time mangling the Chinese languageand programming

Trang 37

We would like to thank the team at Pearson for all their hard work In particular, wewould like to thank Shelley Johnston, without whose dedication and patience the firstthree editions of this book would not have been possible, and Mark Taber, who has takenover for the fourth edition

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 to

do 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 while

we 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

Trang 38

We Want to Hear from You!

As the reader of this book, you are our most important critic and commentator.We value

your opinion and want to know what we’re doing right, what we could do better, whatareas you’d like to see us publish in, and any other words of wisdom you’re willing topass our way

You can email or write me directly to let me know what you did or didn’t like aboutthis book—as 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, and that 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 book’s 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: feedback@developers-library.info

Associate PublisherPearson Education, Inc

800 East 96th StreetIndianapolis, IN 46240 USA

Reader Services

Visit our website and register this book at informit.com/register for convenient access toany updates, downloads, or errata that might be available for this book

Trang 40

WELCOME TOPHP AND M Y SQL W EB D EVELOPMENT 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 cover

n Why you should read this book

n What you will be able to achieve using this book

n What PHP and MySQL are and why they’re great

n What’s changed in the latest versions of PHP and MySQL

n How this book is organized

Let’s get started

Why You Should Read This Book

This book will teach you how to create interactive websites from the simplest orderform through to complex, secure e-commerce sites or interactive Web 2.0 sites.What’smore, you’ll learn how to do it 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.We’ve 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 purpose

of 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 don’t 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

Ngày đăng: 05/10/2018, 15:27