Upload
others
View
3
Download
0
Embed Size (px)
Citation preview
Table of Contents
1 Using PHP
1 PHP Crash Course 11Using PHP 12Sample Application: Bob's Auto Parts 12
The Order Form 12Processing the Form 14
Exnbedding PHP in HTML 14
Form Variables 20
Constants 26
String ConcatenationVariables and Literals
2223
Identifiers 24User Declared Variables 24AssigningValues to Variables 24Variable Types 25
PHP's DataTypes 25Type Strength 25Type Casting 26Variable Variables 26
Using PHP Tags 16PHP Tag Styles 16PHP Statements 17Whitespace 17Cornments 18
Adding Dynamic Content 18Calling Functions 19The date( Function 19
Accessing Form Variables 20
Logical Operators 33Bitwise Operators 33Other Operators 34
Using Operators: Working Out the Form Totals 35Precedence and Associativity : Evaluating Expressions 37Variable Functions 38
Testing and Setting Variable Types 38Testing Variable Status 39Re-interpretingVariables 39
Control Structures 40Making Decisions with Conditionals 40
if Statements 40Code Blocks 40A Side Note: IndentingYour Code 41else Statements 41elseif Statements 42switch Statements 43
Breaking Out of a Control Structure or Script 49Next: Saving the Customer's Order 49
2 Storing and Retrieving Data 51
Saving Data for Later 51Storing and Retrieving Bob's Orders 52Overview of File Processing 53
Comparing the Different Conditionals 44Iteration: Repeating Action 45
while Loops 46for and foreach Loops 47do..while Loops 48
Variable Scope 27Operators 28
Arithmetic Operators 28String Operators 29Assigmnent Operators 29Comparison Operators 32
x
Contents
Opening a File 53
File Modes 53
Using fopen( to Open a File 54
Opening Files Through FTP or HTTP 56
Problems Opening Files 56Writing to a File 59
Parameters for fwrite() 59File Formats 59
Closing a File 60Keading from a File 60
Opening a File for Keading : Popen( 62Knowing When to Stop : feof( 62
Keading a Line at a Time: fgetsO, fgetssO, andfgetcsvO 62Keading the Whole File : reaclfileO, fpassthruO,fileO 63Reading a Character : fgetc( 64Reading an Arbitrary Length: fread( 64
Other Useful File Functions 65Checking Whether a File Is There: file_existsO65Knowing How Big a File Is:; filesize() 65Deleting a File : unlinkO 65Navigating Inside a File: rewindO, fseekO, andftell( 65
File Locking 66Doing It a Better Way: Database Management Systems68
Problems with Using Flat Files 68How RDBMSs Solve These Problems 69
Further Reading 69Next 69
3 Using Arrays 71What Is an Array? 71Numerically Indexed Arrays 72
Initializing Numerically Indexed Arrays 72Accessing Array Contents 73Using Loops to Access the Array 74
Associative Arrays 74Initializing an Associative Array, 74Accessing the Array Elements 74Using Loops with Associative Arrays 75
Multidimensional Arrays 77Sorting Arrays 80
Using sort( 80Using asortO and ksortO to Sort AssociativeArrays 81Sorting in Reverse 81
Sorting Multidimensional Arrays 82User Defined Sorts 82Reverse User Sorts 83
Reordering Arrays 84Using shu$le() 84Using array_reverseO 86
Loading Arrays from Files 86Other Array Manipulations 89
Navigating Within an Array : eachO, currentO,resetO, endO, nextO, posO, and prevO 90Applying Any Function to Each Element in anArray: array_walk() 90Counting Elements in an Array: countO, sizeofO,and array_count_values( 92Converting Arrays to Scalar Variables : extractO92
Further Reading 94Next 94
4 String Manipulation and RegularExpressions 95Example Application: Smart Form Mail 95
Formatting Strings 97Trirnniing Strings: chopO, ltrimO, and trim(98Formatting Strings for Presentation 98
Formatting Strings for Storage : AddSlashesO andStripSlashes() 101
Contents
xi
xii
Contents
Joining and Splitting Strings with String Functions'103
Using explodeO, implodeO, and joino 103
Using strtokO 104Using substr() 104
Comparing Strings 105String Ordering : strcmpO,strcasecmpO, and str-natcmp() 105Testing String Length with strlen() 106
Matching and Replacing Substrings with StringFunctions 106
Finding Strings in Strings : strstrO, strchrO, str-rchrO, stristr(
107
Finding the Position of a Substring: strposO, str-.rpos() 107Replacing Substrings: str_replaceO,'substr_replaceO 108
Introduction to Regular Expressions 109The Basics 110
Character Sets and ClassesRepetition 112'
Subexpressions 112Counted Subexpressions 112Anchoring to the Beginning or End of a String112Branching 113Matching Literal Special Characters 113Summary of Special Characters 113Putting It All Together for the Smart Form 114
Finding Substrings with Regular Expressions 115Replacing Substrings with Regular Expressions 115Splitting Strings with Regular Expressions 116Comparison of String Functions and RegularExpression Functions 116Further Reading 116Next 116
110
5 Reusing Code and Writing Functions 117Why Reuse Code? 117
Cost 118Reliability 118Consistency 118
Using requireO and includeOUsing requireO 119File Name Extensions and require()PHP Tags and require() 120
Using requireO for Web Site Templates 120Using auto_prepend file and autoappend_file
Call to Undefined Function 130Case and Function Names 130
Why ShouldYou DefineYour Own Functions? 131Basic Function Structure 131
NamingYour Function 132Parameters 133Scope 135Pass by Reference Versus Pass by Value 137Beturning from Functions 138ReturningValues from Functions 139
Code Blocks 140Recursion 141
Further Reading 143Next 143
118
6 Object-Oriented PHP 145Object-Oriented Concepts 145
Classes and Objects 145Polymorphism 147Inheritance 147
Creating Classes, Attributes, Operations in PHP 147Structure of a Class 148Constructors 148
Contents
xiii
120
125Using includeO' 126
Using Functions in PHP 128Calling Functions 128
xiv
Contents
Instantiation 149Using Class Attributes 150
Calling Class Operations 151
Implementing Inheritance in PHP 152
Overriding 153Multiple Inheritance 154
Designing Classes 155Writing the Code forYour Class 156
Next 165
II Using MySQL
7 DesigningYour Web Database 169
Relational Database Concepts 170
Tables 170
Columns 170Rows 171Values 171Keys 171Schemas 172Relationships 172
How to DesignYourWeb Database 173Think About the RealWorld ObjectsYou AreModeling 173Avoid Storing Redundant Data 173Use Atomic Coluznn Values 175Choose Sensible Keys 176Think About the QuestionsYou Want to Ask theDatabase 176Avoid Designs with Many Empty Attributes176Summary ofTable Types 177
Web Database Architecture 177Architecture 178
Further Keading 179Next 179
8 Creating Your Web Database 181A Note an Using the MySQL Monitor 182How to Log in to MySQL 183Creating Databases and Users 184
Creating the Database 184Users and Privileges 184Introduction to MySQL's Privilege System 185
Principle of Least Privilege - 185
What the Other Keywords Mean 192Understanding the Column Types 193Looking at the Database with SHOW and
Further Reading 201Next 202
9 Working with Your MySQL Database 203
Grouping and Aggregating Data 215Choosing Which Rows to Return 217
Updating Records in the Database 217
Contents
xv
DESCRIBE 195MySQL Identifiers 196Column Data Types 197
Numeric Types 197
Setting Up Users:The GRANT Command185Typ es and Levels of Privilege - 186The REVOKE Cominand 188Examples Using GRANT and REVOKE 189
Setting Up a User for the Web 190Logging Out as root 190
Using the Right Database 190Creating Database Tables 191
What Is SQL? 203Inserting Data into the Database 204Retrieving Data frone the Database 206
Retrieving Data with Specific Criteria 207Retrieving Data from Multiple Tables 209Retrieving Data in a Particular Order 214
xvi
Contents
Altering Tables After Creation 218
Deleting Records from the Database 219
Dropping Tables 220
Dropping a Whole Database 220
Further Reading 220
Next 221
10 AccessingYour MySQL Database from theWeb with PHP 223
How Web Database Architectures Work 224The Basic Steps in Querying a Database from the Web227Checking and Filtering Input Data 227Setting Up a Connection 228Choosing a Database to Use 230Querying the Database 230Retrieving the Query Results 231Disconnecting from the Database 232Putting New Information in the Database 232Other Useful PHP-MySQL Functions 236
Freeing Up Resources 236Creating and Deleting Databases 236
Other PHP-Database Interfaces 236Using a Generis Database Interface : PEAR DB 237Further Reading 240Next 240
11 Advanced MySQL 241Understanding the Privilege System in Detail 241
The user Table 242The db and host Tables 243The tables_priv and columns_priv Tables 244Access Control: How MySQL Uses the G antTables 245
Updating Privileges : When Do Changes TakeEffect? 246
MakingYour MySQL Database Secure 246
Contents xvii
MySQL from the Operating Systems Point ofView 247Passwords 247User Privileges 248Web Issues 248
Getting More Information About Databases 249Getting Information with SHOW 249Getting Information About Columns withDESCRIBE 251Understanding How Queries Work withEXPLAIN 251
Speeding Up Queries with Indexes 254General Optimization Tips 254
Design Optürüzation 255Permissions 255Table Optimization 255Using Indexes 255Use DefaultValues 255Use Persistent Connections 256Other Tips 256
Different Table Types 256Loading Data from a File 257Backing UpYour MySQL Database 257RestoringYour MySQL Database 257
Further Reading 258Next 258
III E-commerce and Security
12 Running an E-commerce Site 261What DoYou Want to Achieve? 261
Types of Commercial Web Sites 261Online Brochures 262Taking Orders for Goods or Services 265Providing Services and Digital Goods 268AddingValue to Goods or ServicesCutting Costs 269
268
xvui
Contents
Risks and Threats 269Crackers 270Failing to Attract Sufficient Business 270
Computer Hardware Failure 271
Power, Communication, Network, or ShippingFailures 271Extensive Competition 271Software Errors 271Evolving Governmental Policies and Taxes 272
System Capacity Limits 272Deciding an a Strategy 272Next 272
13 E-commerce Security Tssues 273How Important IsYour Information? 274SecurityThreats 274
Exposure of Confidential Data 275Loss or Destruction of Data 276Modification of Data 277Denial of Service 278Errors in Software 279Repudiation 280
Balancing Usability, Performance, Cost, and Security281Creating a Security Policy - 281Authentication Principles 282Using Authentication 283Encryption Basics 284Private Key Encryption 285Public Key Encryption 285Digital Signatures 286Digital Certificates 287Secure Web Servers 288Auditing and Logging 289Firewalls 290
Backing Up Data 290
Backing Up General Files 291Backing Up and RestoringYour MySQLDatabase 291
Physical Security 291Next 292
14 Implementing Authentication with PHP andMySQL 293Identifying Visitors 293Implementing Access Control 294
Storing Passwords 297Encrypting Passwords 300Protecting Multiple Pages 301
Basic Authentication 302Using Basic Authentication in PHP 303Using Basic Authentication with Apache's.htaccess Files 305Using Basic Authentication with IIS 308Using mod_auth_mysgl Authentication 310
Installing mod_auth_mysgl 310Did It Work? 311Using mod_authrnysgl 311
CreatingYour Own Custom Authentication 312Further Reading 313Next 313
15 Implementing Secure Transactions withPHP and MySQL 315 .Providing Secure Transactions 315
The User's Machine 316The Internet 317Your System 318
Using Secure Sockets Layer (SSL) 319
Screening User Input 322Providing Secure Storage 323Why AreYou Storing Credit Card Numbers? 324
Contents
xix
xx
Contents
Using Encryption in PHP 325
Further Reading 333
Next 333
IV Advanced PHP Techniques
16 Interacting with the File, System and theServer 337
Introduction to File Upload 337HTML for File Upload 338A Note an Security 339.Writing the PHP to Deal with the File 339Common Problems 344-
Using Directory Functions 345Reading from Directories 345Getting Info About the Current Directory 347Creating and Deleting Directories 347
Interacting with the File System 348Get File Info 348Changing File Properties 350Creating, Deleting, and Moving Files 351
Using Program Execution Functions 352Interacting wich the Environment: getenvO andputenv( 354Further Reading 355
Next 355
17 Using Network and Protocol Functions357Overview of Protocols 357Sending and Reading Email 358Using Other Web Sites 358Using Network Lookup Functions 361Using FTP 365
Using FTP to Back Up or Mirror a File 366Uploading Files 372
Avoiding Timeouts 373Using Other FTP Functions 373
Generic Network Communications with cURL 374
Using the dateO Function 379Dealing with Unix Timestamps 381Using the getdate( Function 382Validating Dates 382
Converting Between PHP and MySQL Date Formats383Date Calculations 384Using the Calendar Functions 385Further Reading 386Next 386
19 Generating Images 387Setting Up Image Support in PHP 387Image Formats 388
JPEG 388PNG 389WBMP 389GIF 389
Creating Images 390Creating a Canvas Image 391Drawing or Printing Text onto the Image 391Outputting the Final Graphic 393
Cleaning Up 394Using Automatically Generated Images in Other Pages395Using Text and Fonts to Create Images 396
Setting Up the Base Canvas 399Fitting the Text onto the Button 399Positioning the Text 402
Further Reading 376Next 377
18 Managing the Date and Time 379Getting the Date and Time frorn PHP 379
xxii
Contents
Writing the Text onto the Button 403
Finishing Up 403Drawing Figures and Graphing Data 404
Other Image Functions 412Further Keading 412Next 412
20 Using Session Control in PHP 413
What Session Control Is 413Basic Session Functionality 414
What Is a Cookie? 414Setting Cookies from PHP 414Using Cookies with Sessions 415Storing the Session ID 415
Implementing Simple Sessions 416Starting a Session 416Registering Session Variables 416Using Session Variables 417DeregisteringVariables and Destroying theSession 418
Simple Session Example - 418Configuring Session Control 421Implementing Authentication with Session Control421Further Reading 427Next 428
21 Other Useful Features 429Using Magie Quotes 429Evaluating Stririgs: eval() 430Terminating Execution: die and exit 431Serialization 431Getting Information About the PHP Environment433
Finding Out What Extensions Are Loaded 433Identifying the Script Owner 433Finding Out When the Script Was Modified434
Loading Extensions Dynamically 434Temporarily Altering the Runtime Environment 434Source Highlighting 435Next 436
V Building Practical PHP and MySQLProjects
22 . Using PHP and MySQL for Large Projects439Applying Software Engineering to Web Development440Planning and Running a Web Application Project
Using Simple Optimizations 451Using Zend Products 452
Testing 452Further Reading 453Next 453
23 Debugging 455Programming Errors 455
Syntax Errors 456
Runtime Errors 457
Logic Errors 462
Contents
xxiii
440Reusing Code 441Writing Maintainable Code 442
Coding Standards 442Breaking Up Code 445Using a Standard Directory Structure 446Documenting and Sharing In-House Functions446
ImplementingVersion Control 446Choosing a Development Environment 448DocumentingYour Projects 448Prototyping 449Separating Logic and Content 450Optimizing Code 451
xxiv
Contents
Variable DebuggingAid 463
Error Reporting Levels 465Altering the Error Reporting Settings 467
TriggeringYour Own Errors 468
Handling Errors Gracefully 468
Next 471
24 Building User Authentication andPersonalization 473The Problem 473Solution Components 474
User Identification and Personalization 474
Storing Bookmarks 475Recommending Bookmarks 475
Solution Overview 475Implementing the Database 477Implementing the Basic Site 478Implementing User Authentication 481
Registering 481Logging In 487Logging Out 491Changing Passwords 492Resetting Forgotten Passwords 495
Implementing Bookmark Storage and Retrieval 500Adding Bookmarks 500Displaying Bookmarks 502Deleting Bookmarks 503
Implementing Recoznmendations 506Wrapping Up and Possible Extensions 510Next 510
25 Building a Shopping Cart 511The Problem 511Solution Components 512
Building an Online Catalog 512Tracking a User's Purchases While She Shops512
Implementing the Shopping Cart 527Using the show_cart.php Script 527Viewing the Cart 530Adding Items to the Cart 533Saving the Updated Cart 535Printing a Header Bar Summary 536Checking Out 536
Implementing Payment 542Implementing an Administration Interface 544Extending the Project 553Using an Existing System 553Next 554
26 Building a Content Management System555The Problem 555Solution Requirements 556Editing Content 556
Getting Content into the System 556Databases Versus File Storage 557Document Structure 558
Using Metadata 558Formatting the Output 559Image Manipulation 560Solution Design/Overview 562Designing the Database 563Implementation 565
Front End 565Back End 568
Contents
xxv
Payment 512Administration Interface 513
Solution Overview 513Implementing the Database 517Implementing the Online Catalog 519
Listing Categories 520Listing Books in a Category 524Showing Bock Details 526
xxvi
Contents
Searching 578Editor Screen 581
Extending the Project 582
Next 583
27 Building a Web-Based Email Service 585
The Problem 585
Solution Components 586Solution Overview 587
Setting Up the Database 588Script Architecture 590Logging In and Out 597Setting Up Accounts 600
Creating a New Account 602Modifying an Existing Account 604Deleting an Account 604
Keading Mail 605
Selecting an Account 605Viewing Mailbox Contents 608
Reading a Mail Message 611Viewing Message Headers 614Deleting Mail 615
Sending Mail 616Sending a New Message 616Replying to or Forwarding Mail 618
Extending the Project 620Next 620
28 Building a Mailing List Manager 621The Problem 621Solution Components 622
Setting Up a Database of Lists and Subscribers622
File Upload 622Sending Mail with Attachments 623
Solution Overview 623Setting Up the Database 625
Expanding and Collapsing 683Displaying the Articles 686Using the treenode Class 687
Viewing Individual Articles 694Adding New Articles 696Extension 703Using an Existing System 704Next 704
Contents
xxvn
Script Architecture 627Implementing Login 635
Creating a New AccountLogging In 639
636
Implementing User Functions 642Viewing Lists 642Viewing List Information 647Viewing List Archives 649Subscribing and Unsubscribing 650Changing Account Settings 652Changing Passwords 652Logging Out 654
Implementing Administrative Functions 655Creating a New List 655Uploading a New Newsletter 657Handling Multiple File Upload 660Previewing the Newsletter 665Sending the Message 666
Extending the Project 673Next 673
29 Building Web Forums 675The Problem 675Solution Components 676Solution Overview 677Designing the Database 678Viewing the Tree ofArticles 681
xxviii
Contents
30 Generating Personalized Documents inPortable Document Format (PDF) 705
Rich Text Format 708PostScript 708Portable Document Format 709
Solution Components 710Question and Answer System 710Document Generation Software 710
Solution Overview 712Asking the Questions 713Grading the Answers 715Genrating an RTF Certificate 718Generating a PDF Certificate from a Template722Generating a PDF Document Using PDFlib725A Hello World Script for PDFlib 725Genrating Out Certificate with PDFlib 729
Problems with Headers 737Extending the Project 737Further Reading 737
31 Connecting to Web Services with XML andSOAP 739The Problem 739Understanding XML 740Understanding Web Services 744
SOAP 744WSDL 745
The Problem 705Evaluating Document Formats 706
Paper 706ASCII 706HTML 707Word Processor Formats 707
Solution Components 746Building a Shopping Cart 746Using Amazon's Web Services Interfaces 746Parsing XML 747Using SOAP with PHP 747Caching 747
Solution Overview 748Core Application 752Showing Books in a Category 758Getting an AmazonResultSet 760Using XML Over HTTP 770Using SOAP 777Caching the Data 778Building the Shopping Cart 781Checking Out to Amazon 785
Installing the Project Code 785Extending the Project 786Further Reading 786
VI Appendixes
A Installing PHP and MySQL 789Running PHP as a CGI Interpreter or Module 790Installing Apache, PHP, and MySQL Under Unix790
Binary Installation 790Source Installation
791
httpd.conf File-Snippets 798Is PHP Support Working? 799Is SSL Working? 799
Installing Apache, PHP, and MySQL Under Windows801
Installing MySQL Under Windows 801Installing Apache Under Windows 805
Installing PHP for Windows 806
PEAR Installation 809Other Configurations 811
Contents
xxix -
B Web Resources 813PHP Resources 813MySQL and SQL Specific Resources 815Apache Resources 815Web Development
Index 817