1. Trang chủ
  2. » Giáo Dục - Đào Tạo

php and mysql web development, second edition

913 450 0
Tài liệu đã được kiểm tra trùng lặp

Đ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

Tiêu đề Php And Mysql Web Development
Tác giả Luke Welling, Laura Thomson
Thể loại sách
Định dạng
Số trang 913
Dung lượng 7,77 MB

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

Nội dung

Opening a File 53File Modes 53Using fopen to Open a File 54Opening Files Through FTP or HTTP 56Problems Opening Files 56Writing to a File 59Parameters for fwrite 59File Formats 59 Closin

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

“…the Sams book by Welling &

Thomson is the only one which I havefound to be indispensable.The writing isclear and straightforward but never wastes

my time.The book is extremely well laidout.The chapters are the right length andchapter titles quickly take you where youwant to go.”

—Wright Sullivan, President, A&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.”

—WebDynamic

“The true PHP/MySQL bible, PHP

and MySQL Web Development by Luke

Welling and Laura Thomson, made merealize that programming and databases arenow available to the commoners Again, Iknow 1/10000th of what there is to know,and already I’m enthralled.”

—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

Sams Publishing, 201 West 103rd Street, Indianapolis, Indiana 46290

DEVELOPER’S LIBRARY

Luke Welling Laura Thompson Second Edition

Trang 5

PHP and MySQL Web Development Second Edition

Copyright  2003 by Sams Publishing

All rights reserved No part of this book shall be reproduced, stored

in a retrieval system, or transmitted by any means, electronic, mechanical, photocopying, recording, or otherwise, without written permission from the publisher No patent liability is assumed with respect to the use of the information contained herein Although every precaution has been taken in the preparation of this book, the publisher and author assume no responsibility for errors or omis- sions Neither is any liability assumed for damages resulting from the use of the information contained herein.

International Standard Book Number: 0-672-32525-X Library of Congress Catalog Card Number: 2002115573 Printed in the United States of America

First Printing: February 2003

06 05 04 03 4 3 2 1

Trademarks

All terms mentioned in this book that are known to be trademarks

or service marks have been appropriately capitalized Sams Publishing 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 infor- mation provided is on an “as is” basis.The authors and the publisher shall have neither liability 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 of the CD-ROM or pro- grams accompanying it.

Indexers

Kelly Castell Mandie Frank

Trang 6

To our Mums and Dads

Trang 7

II Using MySQL

III E-commerce and Security

Trang 8

IV Advanced PHP Techniques

337

V Building Practical PHP and MySQL Projects

473

Trang 9

Table of Contents

I Using PHP

1 PHP Crash Course 11

Using PHP 12Sample Application: Bob’s Auto Parts 12The Order Form 12

Processing the Form 14Embedding PHP in HTML 14Using PHP Tags 16PHP Tag Styles 16PHP Statements 17Whitespace 17Comments 18Adding Dynamic Content 18Calling Functions 19The date() Function 19Accessing Form Variables 20Form Variables 20String Concatenation 22Variables and Literals 23Identifiers 24

User Declared Variables 24Assigning Values to Variables 24Variable Types 25

PHP’s Data Types 25Type Strength 25Type Casting 26Variable Variables 26Constants 26

Trang 10

Variable Scope 27Operators 28Arithmetic Operators 28String Operators 29Assignment Operators 29Comparison Operators 32Logical Operators 33Bitwise Operators 33Other Operators 34Using Operators:Working Out the Form Totals 35Precedence and Associativity: Evaluating Expressions 37Variable Functions 38

Testing and Setting Variable Types 38Testing Variable Status 39

Re-interpreting Variables 39Control Structures 40

Making Decisions with Conditionals 40

if Statements 40Code Blocks 40

A Side Note: Indenting Your Code 41else Statements 41

elseif Statements 42switch Statements 43Comparing the Different Conditionals 44Iteration: Repeating Actions 45

while Loops 46for and foreach Loops 47do while Loops 48Breaking 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

Trang 11

Opening a File 53File Modes 53Using fopen() to Open a File 54Opening Files Through FTP or HTTP 56Problems Opening Files 56

Writing to a File 59Parameters for fwrite() 59File Formats 59

Closing a File 60Reading from a File 60Opening a File for Reading: fopen() 62Knowing When to Stop: feof() 62Reading a Line at a Time: fgets(), fgetss(), andfgetcsv() 62

Reading the Whole File: readfile(), fpassthru(),file() 63

Reading a Character: fgetc() 64Reading an Arbitrary Length: fread() 64Other Useful File Functions 65

Checking Whether a File Is There: file_exists()65

Knowing How Big a File Is: filesize() 65Deleting a File: unlink() 65

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

File Locking 66Doing It a Better Way: Database Management Systems68

Problems with Using Flat Files 68How RDBMSs Solve These Problems 69Further Reading 69

Next 69

3 Using Arrays 71

What Is an Array? 71Numerically Indexed Arrays 72Initializing Numerically Indexed Arrays 72Accessing Array Contents 73

Using Loops to Access the Array 74

Trang 12

xi Contents

Associative Arrays 74Initializing an Associative Array 74Accessing the Array Elements 74Using Loops with Associative Arrays 75Multidimensional Arrays 77

Sorting Arrays 80Using sort() 80Using asort() and ksort() to Sort AssociativeArrays 81

Sorting in Reverse 81Sorting Multidimensional Arrays 82User Defined Sorts 82Reverse User Sorts 83Reordering Arrays 84Using shuffle() 84Using array_reverse() 86Loading Arrays from Files 86Other Array Manipulations 89Navigating Within an Array: each(), current(),reset(), end(), next(), pos(), and prev() 90Applying Any Function to Each Element in anArray: array_walk() 90

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

Converting Arrays to Scalar Variables: extract()92

Further Reading 94Next 94

4 String Manipulation and Regular Expressions 95

Example Application: Smart Form Mail 95Formatting Strings 97

Trimming Strings: chop(), ltrim(), and trim()98

Formatting Strings for Presentation 98Formatting Strings for Storage: AddSlashes() andStripSlashes() 101

Trang 13

Joining and Splitting Strings with String Functions103

Using explode(), implode(), and join() 103Using strtok() 104

Using substr() 104Comparing Strings 105String Ordering: strcmp(),strcasecmp(), and str-natcmp() 105

Testing String Length with strlen() 106Matching and Replacing Substrings with StringFunctions 106

Finding Strings in Strings: strstr(), strchr(), rchr(), stristr() 107

Finding the Position of a Substring: strpos(), rpos() 107

str-Replacing Substrings: str_replace(),substr_replace() 108

Introduction to Regular Expressions 109The Basics 110

Character Sets and Classes 110Repetition 112

Subexpressions 112Counted Subexpressions 112Anchoring to the Beginning or End of a String112

Branching 113Matching Literal Special Characters 113Summary of Special Characters 113Putting It All Together for the Smart Form 114Finding Substrings with Regular Expressions 115Replacing Substrings with Regular Expressions 115Splitting Strings with Regular Expressions 116Comparison of String Functions and RegularExpression Functions 116

Further Reading 116Next 116

Trang 14

xiii Contents

5 Reusing Code and Writing Functions 117

Why Reuse Code? 117Cost 118Reliability 118Consistency 118Using require() and include() 118Using require() 119File Name Extensions and require() 120PHP Tags and require() 120

Using require() for Web Site Templates 120Using auto_prepend_file and auto_append_file125

Using include() 126Using Functions in PHP 128Calling Functions 128Call to Undefined Function 130Case and Function Names 130Why Should You Define Your Own Functions? 131Basic Function Structure 131

Naming Your Function 132Parameters 133

Scope 135Pass by Reference Versus Pass by Value 137Returning from Functions 138

Returning Values from Functions 139Code Blocks 140

Recursion 141Further Reading 143Next 143

6 Object-Oriented PHP 145

Object-Oriented Concepts 145Classes and Objects 145Polymorphism 147Inheritance 147Creating Classes, Attributes, Operations in PHP 147Structure of a Class 148

Constructors 148

Trang 15

Instantiation 149Using Class Attributes 150Calling Class Operations 151Implementing Inheritance in PHP 152Overriding 153

Multiple Inheritance 154Designing Classes 155

Writing the Code for Your Class 156Next 165

II Using MySQL

7 Designing Your Web Database 169

Relational Database Concepts 170Tables 170

Columns 170Rows 171Values 171Keys 171Schemas 172Relationships 172How to Design Your Web Database 173Think About the Real World Objects You AreModeling 173

Avoid Storing Redundant Data 173Use Atomic Column Values 175Choose Sensible Keys 176Think About the Questions You Want to Ask theDatabase 176

Avoid Designs with Many Empty Attributes176

Summary of Table Types 177Web Database Architecture 177Architecture 178

Further Reading 179Next 179

Trang 16

xv Contents

8 Creating Your Web Database 181

A Note on Using the MySQL Monitor 182How to Log in to MySQL 183

Creating Databases and Users 184Creating the Database 184Users and Privileges 184Introduction to MySQL’s Privilege System 185Principle of Least Privilege 185

Setting Up Users:The GRANT Command185

Types and Levels of Privilege 186The REVOKE Command 188Examples Using GRANT and REVOKE 189Setting Up a User for the Web 190

Logging Out as root 190Using the Right Database 190Creating Database Tables 191What the Other Keywords Mean 192Understanding the Column Types 193Looking at the Database with SHOW andDESCRIBE 195

MySQL Identifiers 196Column Data Types 197Numeric Types 197Further Reading 201Next 202

9 Working with Your MySQL Database 203

What Is SQL? 203Inserting Data into the Database 204Retrieving Data from the Database 206Retrieving Data with Specific Criteria 207Retrieving Data from Multiple Tables 209Retrieving Data in a Particular Order 214Grouping and Aggregating Data 215Choosing Which Rows to Return 217Updating Records in the Database 217

Trang 17

Altering Tables After Creation 218Deleting Records from the Database 219Dropping Tables 220

Dropping a Whole Database 220Further Reading 220

Checking and Filtering Input Data 227Setting Up a Connection 228

Choosing 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 236Freeing Up Resources 236

Creating and Deleting Databases 236Other PHP-Database Interfaces 236Using a Generic Database Interface: PEAR DB 237Further Reading 240

Updating Privileges:When Do Changes TakeEffect? 246

Making Your MySQL Database Secure 246

Trang 18

xvii Contents

MySQL from the Operating System’s Point ofView 247

Passwords 247User Privileges 248Web Issues 248Getting More Information About Databases 249Getting Information with SHOW 249Getting Information About Columns withDESCRIBE 251

Understanding How Queries Work withEXPLAIN 251

Speeding Up Queries with Indexes 254General Optimization Tips 254

Design Optimization 255Permissions 255

Table Optimization 255Using Indexes 255Use Default Values 255Use Persistent Connections 256Other Tips 256

Different Table Types 256Loading Data from a File 257Backing Up Your MySQL Database 257Restoring Your MySQL Database 257Further Reading 258

Next 258

III E-commerce and Security

12 Running an E-commerce Site 261

What Do You Want to Achieve? 261Types of Commercial Web Sites 261Online Brochures 262Taking Orders for Goods or Services 265Providing Services and Digital Goods 268Adding Value to Goods or Services 268Cutting Costs 269

Trang 19

Risks and Threats 269Crackers 270Failing to Attract Sufficient Business 270Computer Hardware Failure 271Power, Communication, Network, or ShippingFailures 271

Extensive Competition 271Software Errors 271Evolving Governmental Policies and Taxes 272System Capacity Limits 272

Deciding on a Strategy 272Next 272

13 E-commerce Security Issues 273

How Important Is Your Information? 274Security Threats 274

Exposure of Confidential Data 275Loss or Destruction of Data 276Modification of Data 277Denial of Service 278Errors in Software 279Repudiation 280Balancing Usability, Performance, Cost, and Security281

Creating 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

Trang 20

xix Contents

Backing Up Data 290Backing Up General Files 291Backing Up and Restoring Your MySQLDatabase 291

Physical Security 291Next 292

14 Implementing Authentication with PHP and MySQL 293

Identifying Visitors 293Implementing Access Control 294Storing Passwords 297Encrypting Passwords 300Protecting Multiple Pages 301Basic Authentication 302

Using Basic Authentication in PHP 303Using Basic Authentication with Apache’s htaccess Files 305

Using Basic Authentication with IIS 308Using mod_auth_mysql Authentication 310Installing mod_auth_mysql 310Did It Work? 311

Using mod_auth_mysql 311Creating Your Own Custom Authentication 312Further Reading 313

Providing Secure Storage 323Why Are You Storing Credit Card Numbers? 324

Trang 21

Using Encryption in PHP 325Further Reading 333

Using Directory Functions 345Reading from Directories 345Getting Info About the Current Directory 347Creating and Deleting Directories 347Interacting with the File System 348Get File Info 348

Changing File Properties 350Creating, Deleting, and Moving Files 351Using Program Execution Functions 352Interacting with the Environment: getenv() andputenv() 354

Further Reading 355Next 355

17 Using Network and Protocol Functions 357

Overview 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

Trang 22

xxi Contents

Avoiding Timeouts 373Using Other FTP Functions 373Generic Network Communications with cURL 374Further Reading 376

Next 377

18 Managing the Date and Time 379

Getting the Date and Time from PHP 379Using the date() Function 379Dealing with Unix Timestamps 381Using the getdate() Function 382Validating Dates 382

Converting Between PHP and MySQL Date Formats383

Date Calculations 384Using the Calendar Functions 385Further Reading 386

Cleaning Up 394Using Automatically Generated Images in Other Pages395

Using Text and Fonts to Create Images 396Setting Up the Base Canvas 399Fitting the Text onto the Button 399Positioning the Text 402

Trang 23

Writing the Text onto the Button 403Finishing Up 403

Drawing Figures and Graphing Data 404Other Image Functions 412

Further Reading 412Next 412

20 Using Session Control in PHP 413

What Session Control Is 413Basic Session Functionality 414What Is a Cookie? 414Setting Cookies from PHP 414Using Cookies with Sessions 415Storing the Session ID 415Implementing Simple Sessions 416Starting a Session 416Registering Session Variables 416Using Session Variables 417Deregistering Variables and Destroying theSession 418

Simple Session Example 418Configuring Session Control 421Implementing Authentication with Session Control421

Further Reading 427Next 428

21 Other Useful Features 429

Using Magic Quotes 429Evaluating Strings: eval() 430Terminating Execution: die and exit 431Serialization 431

Getting Information About the PHP Environment433

Finding Out What Extensions Are Loaded 433Identifying the Script Owner 433

Finding Out When the Script Was Modified434

Trang 24

xxiii Contents

Loading Extensions Dynamically 434Temporarily Altering the Runtime Environment 434Source Highlighting 435

Implementing Version Control 446Choosing a Development Environment 448Documenting Your Projects 448

Prototyping 449Separating Logic and Content 450Optimizing Code 451

Using Simple Optimizations 451Using Zend Products 452Testing 452

Further Reading 453Next 453

23 Debugging 455

Programming Errors 455Syntax Errors 456Runtime Errors 457Logic Errors 462

Trang 25

Variable Debugging Aid 463Error Reporting Levels 465Altering the Error Reporting Settings 467Triggering Your Own Errors 468

Handling Errors Gracefully 468Next 471

24 Building User Authentication and Personalization 473

The Problem 473Solution Components 474User Identification and Personalization 474Storing Bookmarks 475

Recommending Bookmarks 475Solution Overview 475

Implementing the Database 477Implementing the Basic Site 478Implementing User Authentication 481Registering 481

Logging In 487Logging Out 491Changing Passwords 492Resetting Forgotten Passwords 495Implementing Bookmark Storage and Retrieval 500Adding Bookmarks 500

Displaying Bookmarks 502Deleting Bookmarks 503Implementing Recommendations 506Wrapping Up and Possible Extensions 510Next 510

25 Building a Shopping Cart 511

The Problem 511Solution Components 512Building an Online Catalog 512Tracking a User’s Purchases While She Shops512

Trang 26

xxv Contents

Payment 512Administration Interface 513Solution Overview 513

Implementing the Database 517Implementing the Online Catalog 519Listing Categories 520

Listing Books in a Category 524Showing Book Details 526Implementing the Shopping Cart 527Using the show_cart.php Script 527Viewing the Cart 530

Adding 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 553

Using an Existing System 553Next 554

26 Building a Content Management System 555

The Problem 555Solution Requirements 556Editing Content 556Getting Content into the System 556Databases Versus File Storage 557Document Structure 558Using Metadata 558

Formatting the Output 559Image Manipulation 560Solution Design/Overview 562Designing the Database 563Implementation 565Front End 565Back End 568

Trang 27

Searching 578Editor Screen 581Extending the Project 582Next 583

27 Building a Web-Based Email Service 585

The Problem 585Solution Components 586Solution Overview 587Setting Up the Database 588Script Architecture 590Logging In and Out 597Setting Up Accounts 600Creating a New Account 602Modifying an Existing Account 604Deleting an Account 604

Reading Mail 605Selecting an Account 605Viewing Mailbox Contents 608Reading a Mail Message 611Viewing Message Headers 614Deleting Mail 615

Sending Mail 616Sending a New Message 616Replying to or Forwarding Mail 618Extending the Project 620

Next 620

28 Building a Mailing List Manager 621

The Problem 621Solution Components 622Setting Up a Database of Lists and Subscribers622

File Upload 622Sending Mail with Attachments 623Solution Overview 623

Setting Up the Database 625

Trang 28

xxvii Contents

Script Architecture 627Implementing Login 635Creating a New Account 636Logging In 639

Implementing User Functions 642Viewing Lists 642

Viewing List Information 647Viewing List Archives 649Subscribing and Unsubscribing 650Changing Account Settings 652Changing Passwords 652Logging Out 654Implementing Administrative Functions 655Creating a New List 655

Uploading a New Newsletter 657Handling Multiple File Upload 660Previewing the Newsletter 665Sending the Message 666Extending the Project 673Next 673

29 Building Web Forums 675

The Problem 675Solution Components 676Solution Overview 677Designing the Database 678Viewing the Tree of Articles 681Expanding and Collapsing 683Displaying the Articles 686Using the treenode Class 687Viewing Individual Articles 694Adding New Articles 696Extensions 703

Using an Existing System 704Next 704

Trang 29

30 Generating Personalized Documents in Portable Document Format (PDF) 705

The Problem 705Evaluating Document Formats 706Paper 706

ASCII 706HTML 707Word Processor Formats 707Rich Text Format 708PostScript 708Portable Document Format 709Solution Components 710

Question and Answer System 710Document Generation Software 710Solution Overview 712

Asking the Questions 713Grading the Answers 715Generating an RTF Certificate 718Generating a PDF Certificate from a Template722

Generating a PDF Document Using PDFlib725

A Hello World Script for PDFlib 725Generating Our Certificate with PDFlib 729Problems with Headers 737

Extending the Project 737Further Reading 737

31 Connecting to Web Services with XML and SOAP 739

The Problem 739Understanding XML 740Understanding Web Services 744SOAP 744

WSDL 745

Trang 30

xxix Contents

Solution Components 746Building a Shopping Cart 746Using Amazon’s Web Services Interfaces 746Parsing XML 747

Using SOAP with PHP 747Caching 747

Solution Overview 748Core Application 752Showing Books in a Category 758Getting an AmazonResultSet 760Using XML Over HTTP 770Using SOAP 777

Caching the Data 778Building the Shopping Cart 781Checking Out to Amazon 785Installing the Project Code 785Extending the Project 786Further Reading 786

VI Appendixes

A Installing PHP and MySQL 789

Running PHP as a CGI Interpreter or Module 790Installing Apache, PHP, and MySQL Under Unix790

Binary Installation 790Source Installation 791httpd.conf File—Snippets 798

Is PHP Support Working? 799

Is SSL Working? 799Installing Apache, PHP, and MySQL Under Windows801

Installing MySQL Under Windows 801Installing Apache Under Windows 805Installing PHP for Windows 806PEAR Installation 809

Other Configurations 811

Trang 31

B Web Resources 813

PHP Resources 813MySQL and SQL Specific Resources 815Apache Resources 815

Web Development 815

Index 817

Trang 32

About the Authors

Laura Thomsonis a lecturer in the School of Computer Science and InformationTechnology at RMIT University in Melbourne, Australia She is also a partner in theaward-winning Web-development firm Tangled Web Design Laura has previouslyworked for Telstra and the Boston Consulting Group She holds a Bachelor of AppliedScience (Computer Science) degree and a Bachelor of Engineering (Computer SystemsEngineering) degree with honors, and is currently completing her Ph.D in AdaptiveWeb Sites In her spare time, she enjoys sleeping Laura can be reached via email atlaura@tangledweb.com.au

Luke Wellingis a lecturer in the School of Computer Science and InformationTechnology at RMIT University in Melbourne, Australia He is also a partner in TangledWeb Design He holds a Bachelor of Applied Science (Computer Science) degree and iscurrently completing a master’s degree in Genetic Algorithms for CommunicationNetwork Design In his spare time, he attempts to perfect his insomnia Luke can bereached via email at luke@tangledweb.com.au

About the Contributors

Israel Denis, Jr.is a freelance consultant working on e-commerce projects throughoutthe world He specializes in integrating ERP packages such as SAP and Lawson withcustom Web solutions.When he is not busy designing software or writing books, Israelenjoys traveling to Italy, a place he considers home Israel obtained a master’s degree inElectrical Engineering from Georgia Tech in Atlanta, Georgia, in 1998 He is the author

of numerous articles about Linux, Apache, PHP, and MySQL He has worked for nies such as GE and Procter & Gamble with mainly Unix-based computer systems Israelcan be reached via email at idenis@ureach.com

compa-Chris Newmanis a consultant programmer specializing in the development of

dynam-ic Internet appldynam-ications He has extensive commercial experience using PHP andMySQL to produce a wide range of applications for an international client base A grad-uate of Keele University, Chris lives in Stoke-on-Trent, England, where he runs

Lightwood Consultancy Ltd., the company he founded in 1999 to further his interest inInternet development Chris became fascinated with the potential of the Internet while

at the university, and is thrilled to be working with cutting-edge technology More mation on Lightwood Consultancy Ltd can be found at http://www.lightwood.net, andChris can be contacted at chris@lightwood.net

infor-Acknowledgments

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

Trang 33

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 antisocial for the better part of a year Specifically, thank you for your port to our family members: Julie, Robert, Martin, Lesley, Adam, Paul, James, Archer, andBarton

Trang 34

sup-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 author as well as yourname and phone or email address I will carefully review your comments and share themwith the author and editors who worked on the book

Email: opensource@samspublishing.com

Associate PublisherSams Publishing

201 West 103rd StreetIndianapolis, IN 46290 USA

Reader Services

For more information about this book or others from Sams Publishing, visit our Web site

at www.samspublishing.com.Type the ISBN (excluding hyphens) or the title of the book

in the Search box to find the book you’re looking for

For a list of known errors and any updates to the book’s source code please checkwww.lukelaura.com

Trang 36

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’ll 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 An overview of the latest features of PHP 4

n How this book is organizedLet’s get started

Why You Should Read This Book

This book will teach you how to create interactive Web sites from the simplest orderform to complex secure e-commerce sites.What’s more, you’ll learn how to do it usingOpen 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 it might take you a littlelonger to digest.We’ve tried not to leave out any basic concepts, but we do cover them

at speed.The typical reader of this book is someone who wants to master PHP andMySQL for the purpose of building a large or commercial Web site.You might already

be working in another Web development language; if so, this book should get you up tospeed quickly

We wrote this book because we were tired of finding books on PHP that were cally a function reference.These books are useful, but they don’t help when your boss orclient has said “Go build me a shopping cart.”We have done our best to make everyexample useful Many of the code samples can be directly used in your Web site, andmany others can be used with minor modifications

Trang 37

basi-What You Will Be Able to Achieve Using This Book

Reading this book will enable you to build real-world, dynamic Web sites If you’ve builtWeb sites using plain HTML, you will realize the limitations of this approach Staticcontent from a pure HTML Web site is just that—static It stays the same unless youphysically update it.Your users can’t interact with the site in any meaningful fashion.Using a language such as PHP and a database such as MySQL allows you to makeyour sites dynamic: to have them be customizable and contain real-time information

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

intro-We will then discuss aspects of electronic commerce and security as they relate tobuilding a real-world Web site, and show you how to implement these aspects in PHPand MySQL

In the final section of this book, we will talk about how to approach real-world projects, and take you through the design, planning, and building of the following eightprojects:

n User authentication and personalization

What Is PHP?

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

PHP was conceived in 1994 and was originally the work of one man, RasmusLerdorf It was adopted by other talented people and has gone through three major

Trang 38

3 Introduction

rewrites to bring us the broad, mature product we see today As of October 2002, it was

in use on more than nine million domains worldwide, and this number is growing ly.You can see the current number at http://www.php.net/usage.php

rapid-PHP is an Open Source product.You have access to the source code.You can use it,alter it, and redistribute it all without charge

PHP originally stood for Personal Home Page, but was changed in line with the GNU recursive naming convention (GNU = Gnu’s Not Unix) and now stands for PHP Hypertext Preprocessor.

The current major version of PHP is 4.This version has seen some major ments to the language, discussed in the next section

improve-The home page for PHP is available at http://www.php.net

The home page for Zend—the company whose founders designed PHP4—is athttp://www.zend.com

What’s New in PHP Version 4.3?

If you have used PHP before, you will notice a few important improvements in version 4.3

n Most I/O functions now use a unified stream approach, meaning they can easilyopen files, as well as HTTP, HTTPS and FTP connections

n PEAR is out of beta and has a user-friendly installer

n The GD graphic library is now bundled with PHP

n Apache 2 support is still considered experimental, but is getting better all the time

n An executable intended for use with command line scripts is now built by defaultwhen you install PHP

SQL (Structured Query Language), the standard database query language worldwide.

MySQL has been publicly available since 1996, but has a development history going

back to 1979 It has now won the Linux Journal Readers’ Choice Award on a number of

occasions

MySQL is now available under an Open Source license, but commercial licenses arealso available if required

Trang 39

Why Use PHP and MySQL?

When setting out to build an e-commerce site, there are many different products thatyou could use

You will need to choose the following:

n Hardware for the Web server

n An operating system

n Web server software

n A database management system

n A programming or scripting languageSome of these choices will be dependent on the others For example, not all operatingsystems will run on all hardware, not all scripting languages can connect to all databases,and so on

In this book, we do not pay much attention to your hardware, operating system, orWeb server software.We don’t need to One of the nice features of PHP is that it is avail-able for Microsoft Windows, for many versions of Unix, and with any fully functionalWeb server MySQL is similarly versatile

To demonstrate this, the examples in this book have been written and tested on twopopular setups:

n Linux using the Apache Web server

n Microsoft Windows 2000 using Microsoft Internet Information Server (IIS)Whatever hardware, operating system, and Web server you choose, we believe you shouldseriously consider using PHP and MySQL

n Interfaces to many different database systems

n Built-in libraries for many common Web tasks

n Low cost

n Ease of learning and use

n Portability

n Availability of source code

A more detailed discussion of these strengths follows

Trang 40

5 Introduction

Performance

PHP is very efficient Using a single inexpensive server, you can serve millions of hits perday Benchmarks published by Zend Technologies (http://www.zend.com) show PHPoutperforming its competition

Database Integration

PHP has native connections available to many database systems In addition to MySQL,you can directly connect to PostgreSQL, mSQL, Oracle, dbm, filePro, Hyperwave,Informix, InterBase, and Sybase databases, among others

Using the Open Database Connectivity Standard (ODBC), you can connect to any

data-base that provides an ODBC driver.This includes Microsoft products, and many others

Portability

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

Your code will usually work without modification on a different system ning PHP

run-Source Code

You have access to the source code of PHP Unlike commercial, closed-source products,

if there is something you want modified or added to the language, you are free to dothis

You do not need to wait for the manufacturer to release patches.You don’t need toworry about the manufacturer going out of business or deciding to stop supporting aproduct

Ngày đăng: 01/06/2014, 11:06

TỪ KHÓA LIÊN QUAN

w