100% found this document useful (1 vote)
52 views

PHP and MySQL Web development 4th ed Edition Luke Welling pdf download

The document provides information about the book 'PHP and MySQL Web Development, 4th Edition' by Luke Welling and Laura Thomson, including links for purchasing and downloading the ebook. It features a comprehensive guide to using PHP and MySQL for web development, covering topics such as database design, e-commerce, security, and practical projects. The book is praised for its clarity, organization, and practical examples, making it suitable for both beginners and experienced developers.

Uploaded by

boingqongo61
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (1 vote)
52 views

PHP and MySQL Web development 4th ed Edition Luke Welling pdf download

The document provides information about the book 'PHP and MySQL Web Development, 4th Edition' by Luke Welling and Laura Thomson, including links for purchasing and downloading the ebook. It features a comprehensive guide to using PHP and MySQL for web development, covering topics such as database design, e-commerce, security, and practical projects. The book is praised for its clarity, organization, and practical examples, making it suitable for both beginners and experienced developers.

Uploaded by

boingqongo61
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 80

PHP and MySQL Web development 4th ed Edition

Luke Welling pdf download

https://ebookgate.com/product/php-and-mysql-web-development-4th-
ed-edition-luke-welling/

Get Instant Ebook Downloads – Browse at https://ebookgate.com


Instant digital products (PDF, ePub, MOBI) available
Download now and explore formats that suit you...

PHP and MySQL Web Development Luke Welling

https://ebookgate.com/product/php-and-mysql-web-development-luke-
welling/

ebookgate.com

PHP And MySQL Web Development Third Edition Luke Welling

https://ebookgate.com/product/php-and-mysql-web-development-third-
edition-luke-welling/

ebookgate.com

Professional LAMP Linux Apache MySQL and PHP Web


Development 1st Edition Jason Gerner

https://ebookgate.com/product/professional-lamp-linux-apache-mysql-
and-php-web-development-1st-edition-jason-gerner/

ebookgate.com

Learning PHP MySQL and JavaScript 1st ed Edition Robin


Nixon

https://ebookgate.com/product/learning-php-mysql-and-javascript-1st-
ed-edition-robin-nixon/

ebookgate.com
MySQL PHP Database Applications 2nd ed Edition Brad Bulger

https://ebookgate.com/product/mysql-php-database-applications-2nd-ed-
edition-brad-bulger/

ebookgate.com

PHP MySQL For Dummies 3rd ed Edition Janet Valade

https://ebookgate.com/product/php-mysql-for-dummies-3rd-ed-edition-
janet-valade/

ebookgate.com

The PHP Programming with MySQL The Web Technology Series


The Web Technologies Series 2nd Edition Don Gosselin

https://ebookgate.com/product/the-php-programming-with-mysql-the-web-
technology-series-the-web-technologies-series-2nd-edition-don-
gosselin/
ebookgate.com

PHP for the Web Visual QuickStart Guide 4th Edition Larry
Ullman

https://ebookgate.com/product/php-for-the-web-visual-quickstart-
guide-4th-edition-larry-ullman/

ebookgate.com

PHP Mysql For Advanced Learning 3rd Edition Hirdesh


Bhardwaj

https://ebookgate.com/product/php-mysql-for-advanced-learning-3rd-
edition-hirdesh-bhardwaj/

ebookgate.com
00_0672329166_fm.qxd 9/3/08 1:14 PM Page i

“I’ve never purchased a better “I picked up this book two days ago
programming book… This book proved to and I am half way finished. I just can’t put
be the most informative, easiest to follow, it down.The layout and flow is perfect.
and had the best examples of any other Everything is presented in such a way so
computer-related book I have ever that the information is very palatable. I am
purchased.The text is very easy to follow!” able to immediately grasp all the concepts.
—Nick Landman The examples have also been wonderful.
I just had to take some time out to express
“This book by Welling & Thomson is the to you how pleased I have been with
only one which I have found to be indis- this book.”
pensable.The writing is clear and straightfor- —Jason B. Lancaster
ward but never wastes my time.The book is
extremely well laid out.The chapters are the “This book has proven a trusty
right length and chapter titles quickly take companion, with an excellent crash course
you where you want to go.” in PHP and superb coverage of MySQL as
—Wright Sullivan, President, A&E used for Web applications. It also features
Engineering, Inc., Greer South Carolina several complete applications that are great
examples of how to construct modular,
“I just wanted to tell you that I think the scalable applications with PHP.Whether
book PHP and MySQL Web Development you are a PHP newbie or a veteran in
rocks! It’s logically structured, just the right search of a better desk-side reference, this
difficulty level for me (intermediate), one is sure to please!”
interesting and easy to read, and, of course, —WebDynamic
full of valuable information!”
—CodE-E, Austria “The true PHP/MySQL bible, PHP
and MySQL Web Development by Luke
“There are several good introductory Welling and Laura Thomson, made me
books on PHP, but Welling & Thomson is an realize that programming and databases are
excellent handbook for those who wish to now available to the commoners. Again, I
build up complex and reliable systems. It’s know 1/10000th of what there is to know,
obvious that the authors have a strong back- and already I’m enthralled.”
ground in the development of professional —Tim Luoma,TnTLuoma.com
applications and they teach not only
the language itself, but also how to use it “Welling and Thomson’s book is a good
with good software engineering practices.” reference for those who want to get to
—Javier Garcia, senior telecom engineer, grips with practical projects straight off the
Telefonica R&D Labs, Madrid bat. It includes webmail, shopping cart,
session control, and web-forum/weblog
applications as a matter of course, and
begins with a sturdy look at PHP first,
moving to MySQL once the basics
are covered.”
—twilight30 on Slashdot
00_0672329166_fm.qxd 9/3/08 1:14 PM Page ii

“This book is absolutely excellent, to “This is a well-written book for learn-


say the least…. Luke Welling and Laura ing how to build Internet applications with
Thomson give the best in-depth explana- two of the most popular open-source Web
tions I’ve come across on such things as development technologies….The projects
regular expressions, classes and objects, are the real jewel of the book. Not only are
sessions etc. I really feel this book filled in a the projects described and constructed in a
lot of gaps for me with things I didn’t quite logical, component-based manner, but the
understand….This book jumps right into selection of projects represents an excellent
the functions and features most commonly cross-section of common components that
used with PHP, and from there it continues are built into many web sites.”
in describing real-world projects, MySQL —Craig Cecil
integration, and security issues from a proj-
ect manager’s point of view. I found every “The book takes an easy, step-by-step
bit of this book to be well organized and approach to introduce even the clueless
easy to understand.” programmer to the language of PHP. On
—notepad on codewalkers.com top of that, I often find myself referring
back to it in my Web design efforts. I’m still
“A top-notch reference for learning new things about PHP, but this
programmers using PHP and MySQL. book gave me a solid foundation from
Highly recommended.” which to start and continues to help me to
—The Internet Writing Journal this day.”
—Stephen Ward
“This book rocks! I am an experienced
programmer, so I didn’t need a lot of help “This book is one of few that really
with PHP syntax; after all, it’s very close to touched me and made me ‘love’ it. I can’t
C/C++. I don’t know a thing about put it in my bookshelf; I must put it in a
databases, though, so when I wanted to touchable place on my working bench as I
develop a book review engine (among always like to refer from it. Its structure is
other projects) I wanted a solid reference good, wordings are simple and straight for-
to using MySQL with PHP. I have ward, and examples are clear and step by
O’Reilly’s mSQL and MySQL book, and step. Before I read it, I knew nothing of
it’s probably a better pure-SQL reference, PHP and MySQL. After reading it, I have
but this book has earned a place on my the confidence and skill to develop any
reference shelf…Highly recommended.” complicated Web application.”
—Paul Robichaux —Power Wong

“One of the best programming guides “This book is God…. I highly recom-
I’ve ever read.” mend this book to anyone who wants to
—jackofsometrades from Lahti, Finland jump in the deep end with database driven
Web application programming. I wish more
computer books were organized this way.”
—Sean C Schertell
00_0672329166_fm.qxd 9/3/08 1:14 PM Page iii

PHP and MySQL ®

Web Development

Fourth Edition
00_0672329166_fm.qxd 9/3/08 1:14 PM Page iv
00_0672329166_fm.qxd 9/3/08 1:14 PM Page v

PHP and MySQL ®

Web Development
Fourth Edition

Luke Welling
Laura Thomson

Upper Saddle River, NJ • Boston • Indianapolis • San Francisco


New York • Toronto • Montreal • London • Munich • Paris • Madrid
Cape Town • Sydney • Tokyo • Singapore • Mexico City
00_0672329166_fm.qxd 9/3/08 1:14 PM Page vi

PHP and MySQL® Web Development, Fourth Edition Acquisitions Editor


Copyright © 2009 by Pearson Education, Inc. Mark Taber
All rights reserved. No part of this book shall be reproduced, stored in a Development Editor
retrieval system, or transmitted by any means, electronic, mechanical, pho- Michael Thurston
tocopying, recording, or otherwise, without written permission from the pub- Managing Editor
lisher. No patent liability is assumed with respect to the use of the infor- Patrick Kanouse
mation contained herein. Although every precaution has been taken in the
preparation of this book, the publisher and authors assume no responsibil- Project Editor
ity for errors or omissions. Neither is any liability assumed for damages Jennifer Gallant
resulting from the use of the information contained herein. Copy Editor
Library of Congress Cataloging-in-Publication Data Barbara Hacha
Welling, Luke, 1972- Indexer
PHP and MySQL Web development / Luke Welling, Laura Thomson. -- 4th Tim Wright
ed.
Proofreader
p. cm.
Kathy Ruiz
ISBN 978-0-672-32916-6 (pbk. w/cd)
1. PHP (Computer program language) 2. SQL (Computer program language) Technical Editor
3. MySQL (Electronic resource) 4. Web sites--Design. I. Thomson, Tim Boronczyk
Laura. II. Title. Publishing Coordinator
QA76.73.P224W45 2008 Vanessa Evans
005.2'762--dc22 Multimedia Developer
2008036492 Dan Scherf
Printed in the United States of America
Book Designer
First Printing: September 2009 Gary Adair
ISBN-10: 0-672-32916-6 Composition
ISBN-13: 978-0-672-32916-6 Bronkella Publishing
Trademarks
All terms mentioned in this book that are known to be trademarks or serv-
ice marks have been appropriately capitalized. Pearson Education, Inc.
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 lia-
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
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
[email protected]
For sales outside the U.S., please contact
International Sales
[email protected]
00_0672329166_fm.qxd 9/3/08 1:14 PM Page vii


To our Mums and Dads

00_0672329166_fm.qxd 9/3/08 1:14 PM Page viii

Contents at a Glance
Introduction 1

I Using PHP
1 PHP Crash Course 13
2 Storing and Retrieving Data 59
3 Using Arrays 81
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 and
MySQL 391
18 Implementing Secure Transactions with PHP and
MySQL 409
00_0672329166_fm.qxd 9/3/08 1:14 PM Page ix

IV Advanced PHP Techniques


19 Interacting with the File System and the Server
431
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 Personalization
569
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 SOAP
807
34 Building Web 2.0 Applications with Ajax 855

VI Appendixes
A Installing PHP and MySQL 889
B Web Resources 907
Index 911
00_0672329166_fm.qxd 9/3/08 1:14 PM Page x

Table of Contents
Introduction 1

I Using PHP

1 PHP Crash Course 13


Before You Begin: Accessing PHP 14
Creating a Sample Application: Bob’s Auto Parts 14
Creating the Order Form 14
Processing the Form 16
Embedding PHP in HTML 17
PHP Tags 18
PHP Statements 19
Whitespace 20
Comments 20
Adding Dynamic Content 21
Calling Functions 22
Using the date() Function 22
Accessing Form Variables 23
Short, Medium, and Long Variables 23
String Concatenation 26
Variables and Literals 27
Understanding Identifiers 28
Examining Variable Types 29
PHP’s Data Types 29
Type Strength 29
Type Casting 30
Variable Variables 30
Declaring and Using Constants 31
Understanding Variable Scope 31
Using Operators 32
Arithmetic Operators 33
String Operators 34
00_0672329166_fm.qxd 9/3/08 1:14 PM Page xi

Assignment Operators 34
Comparison Operators 36
Logical Operators 38
Bitwise Operators 38
Other Operators 39
Working Out the Form Totals 41
Understanding Precedence and Associativity 42
Using Variable Functions 44
Testing and Setting Variable Types 44
Testing Variable Status 45
Reinterpreting Variables 46
Making Decisions with Conditionals 46
if Statements 46
Code Blocks 47
else Statements 47
elseif Statements 48
switch Statements 49
Comparing the Different Conditionals 51
Repeating Actions Through Iteration 51
while Loops 53
for and foreach Loops 54
do...while Loops 55
Breaking Out of a Control Structure or Script 56
Employing Alternative Control Structure Syntax 56
Using declare 57
Next 57

2 Storing and Retrieving Data 59


Saving Data for Later 59
Storing and Retrieving Bob’s Orders 60
Processing Files 61
Opening a File 61
Choosing File Modes 61
Using fopen() to Open a File 62
Opening Files Through FTP or HTTP 64
Addressing Problems Opening Files 65
00_0672329166_fm.qxd 9/3/08 1:14 PM Page xii

xii Contents

Writing to a File 67
Parameters for fwrite() 68
File Formats 68
Closing a File 69
Reading from a File 71
Opening a File for Reading: fopen() 72
Knowing When to Stop: feof() 73
Reading a Line at a Time: fgets(), fgetss(), and
fgetcsv() 73
Reading the Whole File: readfile(), fpassthru(), and
file() 74
Reading a Character: fgetc() 75
Reading an Arbitrary Length: fread() 75
Using Other Useful File Functions 76
Checking Whether a File Is There:
file_exists() 76
Determining How Big a File Is: filesize() 76
Deleting a File: unlink() 76
Navigating Inside a File: rewind(), fseek(), and
ftell() 76
Locking Files 78
A Better Way: Database Management Systems 79
Problems with Using Flat Files 79
How RDBMSs Solve These Problems 80
Further Reading 80
Next 80

3 Using Arrays 81
What Is an Array? 81
Numerically Indexed Arrays 82
Initializing Numerically Indexed Arrays 82
Accessing Array Contents 83
Using Loops to Access the Array 84
Arrays with Different Indices 85
Initializing an Array 85
Accessing the Array Elements 85
Using Loops 85
00_0672329166_fm.qxd 9/3/08 1:14 PM Page xiii

Contents xiii

Array Operators 87
Multidimensional Arrays 88
Sorting Arrays 92
Using sort() 92
Using asort() and ksort() to Sort Arrays 93
Sorting in Reverse 93
Sorting Multidimensional Arrays 93
User-Defined Sorts 93
Reverse User Sorts 95
Reordering Arrays 96
Using shuffle() 96
Using array_reverse() 97
Loading Arrays from Files 98
Performing Other Array Manipulations 102
Navigating Within an Array: each(), current(),
reset(), end(), next(), pos(), and prev() 102
Applying Any Function to Each Element in an
Array: array_walk() 103
Counting Elements in an Array: count(), sizeof(),
and array_count_values() 104
Converting Arrays to Scalar Variables:
extract() 105
Further Reading 106
Next 106

4 String Manipulation and Regular


Expressions 107
Creating a Sample Application: Smart Form Mail 107
Formatting Strings 110
Trimming Strings: chop(), ltrim(), and
trim() 110
Formatting Strings for Presentation 110
Formatting Strings for Storage: addslashes() and
stripslashes() 114
Joining and Splitting Strings with String
Functions 116
Using explode(), implode(), and join() 116
Using strtok() 117
Using substr() 118
00_0672329166_fm.qxd 9/3/08 1:14 PM Page xiv

xiv Contents

Comparing Strings 119


Performing String Ordering: strcmp(),
strcasecmp(), and strnatcmp() 119
Testing String Length with strlen() 120
Matching and Replacing Substrings with String
Functions 120
Finding Strings in Strings: strstr(), strchr(),
strrchr(), and stristr() 120
Finding the Position of a Substring: strpos() and
strrpos() 121
Replacing Substrings: str_replace() and
substr_replace() 122
Introducing Regular Expressions 123
The Basics 124
Character Sets and Classes 124
Repetition 126
Subexpressions 126
Counted Subexpressions 126
Anchoring to the Beginning or End of a
String 126
Branching 127
Matching Literal Special Characters 127
Reviewing the Special Characters 127
Putting It All Together for the Smart Form 128
Finding Substrings with Regular Expressions 129
Replacing Substrings with Regular Expressions 130
Splitting Strings with Regular Expressions 130
Further Reading 131
Next 131

5 Reusing Code and Writing Functions 133


The Advantages of Reusing Code 133
Cost 134
Reliability 134
Consistency 134
Using require() and include() 134
Filename Extensions and require() 135
Using require() for Website Templates 137
00_0672329166_fm.qxd 9/3/08 1:14 PM Page xv

Contents xv

Using auto_prepend_file and


auto_append_file 142
Using Functions in PHP 143
Calling Functions 143
Calling an Undefined Function 145
Understanding Case and Function Names 146
Defining Your Own Functions 146
Examining Basic Function Structure 146
Naming Your Function 147
Using Parameters 148
Understanding Scope 150
Passing by Reference Versus Passing by Value 153
Using the return Keyword 154
Returning Values from Functions 155
Implementing Recursion 156
Namespaces 158
Further Reading 158
Next 158

6 Object-Oriented PHP 159


Understanding Object-Oriented Concepts 160
Classes and Objects 160
Polymorphism 161
Inheritance 162
Creating Classes, Attributes, and Operations in PHP
162
Structure of a Class 162
Constructors 163
Destructors 163
Instantiating Classes 164
Using Class Attributes 164
Controlling Access with private and public 166
Calling Class Operations 167
Implementing Inheritance in PHP 168
Controlling Visibility Through Inheritance with
private and protected 169
00_0672329166_fm.qxd 9/3/08 1:14 PM Page xvi

xvi Contents

Overriding 170
Preventing Inheritance and Overriding with final
172
Understanding Multiple Inheritance 173
Implementing Interfaces 173
Designing Classes 174
Writing the Code for Your Class 175
Understanding Advanced Object-Oriented
Functionality in PHP 183
Using Per-Class Constants 184
Implementing Static Methods 184
Checking Class Type and Type Hinting 184
Late Static Bindings 185
Cloning Objects 186
Using Abstract Classes 186
Overloading Methods with __call() 186
Using __autoload() 187
Implementing Iterators and Iteration 188
Converting Your Classes to Strings 190
Using the Reflection API 190
Next 191

7 Error and Exception Handling 193


Exception Handling Concepts 193
The Exception Class 195
User-Defined Exceptions 196
Exceptions in Bob’s Auto Parts 199
Exceptions and PHP’s Other Error Handling
Mechanisms 202
Further Reading 203
Next 203

II Using MySQL

8 Designing Your Web Database 207


Relational Database Concepts 208
Tables 208
Columns 209
00_0672329166_fm.qxd 9/3/08 1:14 PM Page xvii

Contents xvii

Rows 209
Values 209
Keys 209
Schemas 210
Relationships 211
Designing Your Web Database 211
Think About the Real-World Objects You Are
Modeling 211
Avoid Storing Redundant Data 212
Use Atomic Column Values 214
Choose Sensible Keys 215
Think About What You Want to Ask the
Database 215
Avoid Designs with Many Empty
Attributes 215
Summary of Table Types 216
Web Database Architecture 216
Further Reading 218
Next 218

9 Creating Your Web Database 219


Using the MySQL Monitor 220
Logging In to MySQL 221
Creating Databases and Users 222
Setting Up Users and Privileges 223
Introducing MySQL’s Privilege System 223
Principle of Least Privilege 223
User Setup:The GRANT Command 223
Types and Levels of Privileges 225
The REVOKE Command 227
Examples Using GRANT and REVOKE 227
Setting Up a User for the Web 228
Using the Right Database 229
Creating Database Tables 229
Understanding What the Other Keywords
Mean 231
Understanding the Column Types 232
00_0672329166_fm.qxd 9/3/08 1:14 PM Page xviii

xviii Contents

Looking at the Database with SHOW and


DESCRIBE 233
Creating Indexes 234
Understanding MySQL Identifiers 235
Choosing Column Data Types 236
Numeric Types 236
Date and Time Types 238
String Types 239
Further Reading 241
Next 241

10 Working with Your MySQL Database 243


What Is SQL? 243
Inserting Data into the Database 244
Retrieving Data from the Database 246
Retrieving Data with Specific Criteria 248
Retrieving Data from Multiple Tables 249
Retrieving Data in a Particular Order 255
Grouping and Aggregating Data 256
Choosing Which Rows to Return 258
Using Subqueries 258
Updating Records in the Database 261
Altering Tables After Creation 261
Deleting Records from the Database 264
Dropping Tables 264
Dropping a Whole Database 264
Further Reading 265
Next 265

11 Accessing Your MySQL Database from the


Web with PHP 267
How Web Database Architectures Work 268
Querying a Database from the Web 271
Checking and Filtering Input Data 271
Setting Up a Connection 272
Choosing a Database to Use 274
00_0672329166_fm.qxd 9/3/08 1:14 PM Page xix

Contents xix

Querying the Database 274


Retrieving the Query Results 275
Disconnecting from the Database 276
Putting New Information in the Database 276
Using Prepared Statements 280
Using Other PHP-Database Interfaces 282
Using a Generic Database Interface: PEAR
MDB2 282
Further Reading 285
Next 285

12 Advanced MySQL Administration 287


Understanding the Privilege System in Detail 287
The user Table 289
The db and host Tables 290
The tables_priv, columns_priv, and procs priv
Tables 292
Access Control: How MySQL Uses the Grant
Tables 293
Updating Privileges:When Do Changes Take
Effect? 293
Making Your MySQL Database Secure 294
MySQL from the Operating System’s Point of
View 294
Passwords 295
User Privileges 295
Web Issues 296
Getting More Information About Databases 296
Getting Information with SHOW 296
Getting Information About Columns with
DESCRIBE 299
Understanding How Queries Work with
EXPLAIN 299
Optimizing Your Database 304
Design Optimization 304
Permissions 304
Table Optimization 304
00_0672329166_fm.qxd 9/3/08 1:14 PM Page xx

xx Contents

Using Indexes 305


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

13 Advanced MySQL Programming 311


The LOAD DATA INFILE Statement 311
Storage Engines 312
Transactions 313
Understanding Transaction Definitions 313
Using Transactions with InnoDB 314
Foreign Keys 315
Stored Procedures 316
Basic Example 316
Local Variables 319
Cursors and Control Structures 319
Further Reading 323
Next 323

III E-commerce and Security

14 Running an E-commerce Site 327


Deciding What You Want to Achieve 327
Considering the Types of Commercial Websites 327
Publishing Information Using Online
Brochures 328
Taking Orders for Goods or Services 331
00_0672329166_fm.qxd 9/3/08 1:14 PM Page xxi

Contents xxi

Providing Services and Digital Goods 334


Adding Value to Goods or Services 335
Cutting Costs 335
Understanding Risks and Threats 336
Crackers 337
Failure to Attract Sufficient Business 337
Computer Hardware Failure 337
Power, Communication, Network, or Shipping
Failures 338
Extensive Competition 338
Software Errors 338
Evolving Governmental Policies and Taxes 339
System Capacity Limits 339
Choosing a Strategy 339
Next 339

15 E-commerce Security Issues 341


How Important Is Your Information? 342
Security Threats 342
Exposure of Confidential Data 343
Loss or Destruction of Data 344
Modification of Data 345
Denial of Service 346
Errors in Software 347
Repudiation 348
Usability, Performance, Cost, and Security 349
Creating a Security Policy 349
Authentication Principles 350
Encryption Basics 351
Private Key Encryption 353
Public Key Encryption 353
Digital Signatures 354
Digital Certificates 355
Secure Web Servers 356
Auditing and Logging 357
00_0672329166_fm.qxd 9/3/08 1:14 PM Page xxii

xxii Contents

Firewalls 357
Data Backups 358
Backing Up General Files 358
Backing Up and Restoring Your MySQL
Database 358
Physical Security 359
Next 359

16 Web Application Security 361


Strategies for Dealing with Security 361
Start with the Right Mindset 362
Balancing Security and Usability 362
Monitoring Security 363
Our Basic Approach 363
Identifying the Threats We Face 363
Access to or Modification of Sensitive Data 363
Loss or Destruction of Data 364
Denial of Service 364
Malicious Code Injection 365
Compromised Server 365
Understanding Who We’re Dealing With 365
Crackers 366
Unwitting Users of Infected Machines 366
Disgruntled Employees 366
Hardware Thieves 366
Ourselves 366
Securing Your Code 367
Filtering User Input 367
Escaping Output 371
Code Organization 374
What Goes in Your Code 374
File System Considerations 375
Code Stability and Bugs 376
Execution Quotes and exec 377
Securing Your Web Server and PHP 378
Keep Software Up-to-Date 378
Browse the php.ini file 380
00_0672329166_fm.qxd 9/3/08 1:14 PM Page xxiii

Contents xxiii

Web Server Configuration 380


Commercially Hosted Web Applications 382
Database Server Security 383
Users and the Permissions System 383
Sending Data to the Server 384
Connecting to the Server 384
Running the Server 385
Protecting the Network 385
Install Firewalls 386
Use a DMZ 386
Prepare for DoS and DDoS Attacks 387
Computer and Operating System Security 387
Keep the Operating System Up-to-Date 387
Run Only What Is Necessary 388
Physically Secure the Server 388
Disaster Planning 388
Next 390

17 Implementing Authentication with PHP and


MySQL 391
Identifying Visitors 391
Implementing Access Control 392
Storing Passwords 395
Encrypting Passwords 397
Protecting Multiple Pages 399
Using Basic Authentication 399
Using Basic Authentication in PHP 400
Using Basic Authentication with Apache’s .htaccess
Files 402
Using mod_auth_mysql Authentication 406
Installing mod_auth_mysql 406
Using mod_auth_mysql 407
Creating Your Own Custom Authentication 408
Further Reading 408
Next 408
00_0672329166_fm.qxd 9/3/08 1:14 PM Page xxiv

xxiv Contents

18 Implementing Secure Transactions with


PHP and MySQL 409
Providing Secure Transactions 409
The User’s Machine 410
The Internet 411
Your System 412
Using Secure Sockets Layer (SSL) 413
Screening User Input 417
Providing Secure Storage 417
Storing Credit Card Numbers 419
Using Encryption in PHP 419
Installing GPG 420
Testing GPG 422
Further Reading 427
Next 428

IV Advanced PHP Techniques

19 Interacting with the File System and the


Server 431
Uploading Files 431
HTML for File Upload 433
Writing the PHP to Deal with the File 434
Avoiding Common Upload Problems 438
Using Directory Functions 439
Reading from Directories 439
Getting Information About the Current
Directory 442
Creating and Deleting Directories 443
Interacting with the File System 443
Getting File Information 444
Changing File Properties 446
Creating, Deleting, and Moving Files 447
Using Program Execution Functions 447
00_0672329166_fm.qxd 9/3/08 1:14 PM Page xxv

Contents xxv

Interacting with the Environment: getenv() and


putenv() 450
Further Reading 450
Next 450

20 Using Network and Protocol Functions 451


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

21 Managing the Date and Time 469


Getting the Date and Time from PHP 469
Using the date() Function 469
Dealing with Unix Timestamps 471
Using the getdate() Function 473
Validating Dates with checkdate() 474
Formatting Timestamps 474
Converting Between PHP and MySQL Date
Formats 476
Calculating Dates in PHP 477
Calculating Dates in MySQL 478
Using Microseconds 480
Using the Calendar Functions 480
Further Reading 481
Next 481
00_0672329166_fm.qxd 9/3/08 1:14 PM Page xxvi

xxvi Contents

22 Generating Images 483


Setting Up Image Support in PHP 484
Understanding Image Formats 484
JPEG 485
PNG 485
WBMP 485
GIF 485
Creating Images 486
Creating a Canvas Image 487
Drawing or Printing Text on the Image 487
Outputting the Final Graphic 489
Cleaning Up 490
Using Automatically Generated Images in Other
Pages 490
Using Text and Fonts to Create Images 491
Setting Up the Base Canvas 495
Fitting the Text onto the Button 495
Positioning the Text 498
Writing the Text onto the Button 499
Finishing Up 499
Drawing Figures and Graphing Data 499
Using Other Image Functions 507
Further Reading 507
Next 508

23 Using Session Control in PHP 509


What Is Session Control? 509
Understanding Basic Session Functionality 509
What Is a Cookie? 510
Setting Cookies from PHP 510
Using Cookies with Sessions 511
Storing the Session ID 511
Implementing Simple Sessions 512
Starting a Session 512
Registering Session Variables 513
00_0672329166_fm.qxd 9/3/08 1:14 PM Page xxvii

Contents xxvii

Using Session Variables 513


Unsetting Variables and Destroying the
Session 513
Creating a Simple Session Example 514
Configuring Session Control 516
Implementing Authentication with Session
Control 517
Further Reading 524
Next 524

24 Other Useful Features 525


Evaluating Strings: eval() 525
Terminating Execution: die() and exit() 526
Serializing Variables and Objects 526
Getting Information About the PHP
Environment 528
Finding Out What Extensions Are Loaded 528
Identifying the Script Owner 529
Finding Out When the Script Was
Modified 529
Temporarily Altering the Runtime Environment 529
Highlighting Source Code 530
Using PHP on the Command Line 531
Next 532

V Building Practical PHP and MySQL


Projects

25 Using PHP and MySQL for Large


Projects 535
Applying Software Engineering to Web
Development 536
Planning and Running a Web Application Project 536
Reusing Code 537
Writing Maintainable Code 538
Coding Standards 538
Breaking Up Code 541
00_0672329166_fm.qxd 9/3/08 1:14 PM Page xxviii

xxviii Contents

Using a Standard Directory Structure 542


Documenting and Sharing In-House
Functions 542
Implementing Version Control 542
Choosing a Development Environment 544
Documenting Your Projects 544
Prototyping 545
Separating Logic and Content 546
Optimizing Code 546
Using Simple Optimizations 547
Using Zend Products 547
Testing 548
Further Reading 549
Next 549

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

27 Building User Authentication and


Personalization 569
Solution Components 569
User Identification and Personalization 570
Storing Bookmarks 571
Recommending Bookmarks 571
Solution Overview 571
Implementing the Database 573
00_0672329166_fm.qxd 9/3/08 1:14 PM Page xxix

Contents xxix

Implementing the Basic Site 574


Implementing User Authentication 577
Registering Users 577
Logging In 584
Logging Out 587
Changing Passwords 588
Resetting Forgotten Passwords 591
Implementing Bookmark Storage and Retrieval 596
Adding Bookmarks 596
Displaying Bookmarks 599
Deleting Bookmarks 600
Implementing Recommendations 602
Considering Possible Extensions 606
Next 606

28 Building a Shopping Cart 607


Solution Components 607
Building an Online Catalog 608
Tracking Users’ Purchases While They
Shop 608
Implementing a Payment System 608
Building an Administration Interface 609
Solution Overview 609
Implementing the Database 612
Implementing the Online Catalog 615
Listing Categories 617
Listing Books in a Category 620
Showing Book Details 622
Implementing the Shopping Cart 623
Using the show_cart.php Script 623
Viewing the Cart 627
Adding Items to the Cart 630
Saving the Updated Cart 631
Printing a Header Bar Summary 632
Checking Out 633
00_0672329166_fm.qxd 9/3/08 1:14 PM Page xxx

xxx Contents

Implementing Payment 639


Implementing an Administration Interface 641
Extending the Project 650
Using an Existing System 650
Next 650

29 Building a Web-Based Email Service 651


Solution Components 651
Mail Protocols: POP3 Versus IMAP 651
POP3 and IMAP Support in PHP 652
Solution Overview 654
Setting Up the Database 655
Examining the Script Architecture 657
Logging In and Out 663
Setting Up Accounts 666
Creating a New Account 668
Modifying an Existing Account 670
Deleting an Account 670
Reading Mail 671
Selecting an Account 671
Viewing Mailbox Contents 674
Reading a Mail Message 677
Viewing Message Headers 680
Deleting Mail 681
Sending Mail 682
Sending a New Message 682
Replying To or Forwarding Mail 684
Extending the Project 686
Next 686

30 Building a Mailing List Manager 687


Solution Components 687
Setting Up a Database of Lists and Subscribers
688
Uploading Newsletters 688
Sending Mail with Attachments 689
00_0672329166_fm.qxd 9/3/08 1:14 PM Page xxxi

Contents xxxi

Solution Overview 689


Setting Up the Database 692
Defining the Script Architecture 694
Implementing Login 702
Creating a New Account 702
Logging In 705
Implementing User Functions 708
Viewing Lists 708
Viewing List Information 713
Viewing List Archives 716
Subscribing and Unsubscribing 717
Changing Account Settings 719
Changing Passwords 719
Logging Out 721
Implementing Administrative Functions 721
Creating a New List 722
Uploading a New Newsletter 724
Handling Multiple File Upload 727
Previewing the Newsletter 732
Sending the Message 733
Extending the Project 740
Next 740

31 Building Web Forums 741


Understanding the Process 741
Solution Components 742
Solution Overview 743
Designing the Database 744
Viewing the Tree of Articles 747
Expanding and Collapsing 749
Displaying the Articles 752
Using the treenode Class 753
Viewing Individual Articles 760
Adding New Articles 762
Adding Extensions 769
00_0672329166_fm.qxd 9/3/08 1:14 PM Page xxxii

xxxii Contents

Using an Existing System 770


Next 770

32 Generating Personalized PDF


Documents 771
Project Overview 771
Evaluating Document Formats 772
Solution Components 776
Question and Answer System 776
Document Generation Software 776
Solution Overview 778
Asking the Questions 780
Grading the Answers 782
Generating an RTF Certificate 784
Generating a PDF Certificate from a
Template 788
Generating a PDF Document Using
PDFlib 792
A Hello World Script for PDFlib 792
Generating a Certificate with PDFlib 796
Handling Problems with Headers 804
Extending the Project 805
Next 805

33 Connecting to Web Services with XML and


SOAP 807
Project Overview:Working with XML and Web
Services 807
Understanding XML 808
Understanding Web Services 811
Solution Components 813
Using Amazon’s Web Services Interfaces 813
Parsing XML: REST Responses 814
Using SOAP with PHP 814
Caching 815
00_0672329166_fm.qxd 9/3/08 1:14 PM Page xxxiii

Contents xxxiii

Solution Overview 815


Core Application 820
Showing Books in a Category 826
Getting an AmazonResultSet Class 828
Using REST to Make a Request and Retrieve a
Result 838
Using SOAP to Make a Request and Retrieve a
Result 845
Caching the Data from a Request 846
Building the Shopping Cart 849
Checking Out to Amazon 852
Installing the Project Code 853
Extending the Project 854
Further Reading 854

34 Building Web 2.0 Applications with


Ajax 855
What Is Ajax? 856
HTTP Requests and Responses 856
DHTML and XHTML 857
Cascading Style Sheets (CSS) 858
Client-Side Programming 859
Server-Side Programming 860
XML and XSLT 860
Fundamental Ajax 860
The XMLHTTPRequest Object 860
Communicating with the Server 862
Working with the Server Response 864
Putting It All Together 866
Adding Ajax Elements to Earlier Projects 870
Adding Ajax Elements to PHPbookmark 870
For More Information 884
00_0672329166_fm.qxd 9/3/08 1:14 PM Page xxxiv

xxxiv Contents

Learning More about the Document Object


Model (DOM) 884
JavaScript Libraries for Ajax Applications 884
Ajax Developer Websites 885

Appendixes

A Installing PHP and MySQL 889


Installing Apache, PHP, and MySQL Under Unix 890
Binary Installation 890
Source Installation 891
httpd.conf File: Snippets 896
Is PHP Support Working? 897
Is SSL Working? 898
Installing Apache, PHP, and MySQL Under
Windows 899
Installing MySQL Under Windows 900
Installing Apache Under Windows 901
Installing PHP for Windows 903
Installing PEAR 905
Setting Up Other Configurations 906

B Web Resources 907


PHP Resources 907
MySQL and SQL Specific Resources 909
Apache Resources 909
Web Development 910

Index 911
00_0672329166_fm.qxd 9/3/08 1:14 PM Page xxxv

Lead Authors
Laura Thomson is 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 RMIT
University and the Boston Consulting Group. She holds a Bachelor of Applied Science
(Computer Science) degree and a Bachelor of Engineering (Computer Systems
Engineering) degree with honors. In her spare time she enjoys riding horses, arguing
about free and open source software, and sleeping.

Luke Welling is a web architect at OmniTI and regularly speaks on open source and
web 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 independent
consultant 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. Meloni is the technical director for i2i Interactive (www.i2ii.com), a multime-
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
on web-based programming languages and database topics, including the bestselling Sams
Teach Yourself PHP, MySQL, and Apache All in One.

Adam DeFields is a consultant specializing in web application development, project


management, and instructional design. He lives in Grand Rapids, Michigan where he
runs Emanation Systems, LLC, (www.emanationsystemsllc.com) a company he founded
in 2002. He has been involved with web development projects using several different
technologies, but has developed a strong preference toward PHP/MySQL-based projects.

Marc Wandschneider is a freelance software developer, author, and speaker who travels
the globe working on interesting projects. In recent years, a lot of his attention has
been 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 language
and programming.
00_0672329166_fm.qxd 9/3/08 1:14 PM Page xxxvi

Acknowledgments
We would like to thank the team at Pearson for all their hard work. In particular, we
would like to thank Shelley Johnston, without whose dedication and patience the first
three editions of this book would not have been possible, and Mark Taber, who has taken
over for the fourth edition.
We appreciate immensely the work done by the PHP and MySQL development
teams.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 for
your support to our family members: Julie, Robert, Martin, Lesley, Adam, Paul, Archer,
and Barton.
00_0672329166_fm.qxd 9/3/08 1:14 PM Page xxxvii

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, what
areas you’d like to see us publish in, and any other words of wisdom you’re willing to
pass our way.
You can email or write me directly to let me know what you did or didn’t like about
this 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 your
name and phone or email address. I will carefully review your comments and share them
with the authors and editors who worked on the book.
Email: [email protected]
Mail: Mark Taber
Associate Publisher
Pearson Education, Inc.
800 East 96th Street
Indianapolis, IN 46240 USA

Reader Services
Visit our website and register this book at informit.com/register for convenient access to
any updates, downloads, or errata that might be available for this book.
00_0672329166_fm.qxd 9/3/08 1:14 PM Page xxxviii
01_0672329166_intro.qxd 9/3/08 1:16 PM Page 1

Introduction

W ELCOME TO PHP AND MYSQL WEB DEVELOPMENT. Within its pages, you will find
distilled knowledge from our experiences using PHP and MySQL, two of the hottest
web 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 order
form through to complex, secure e-commerce sites or interactive Web 2.0 sites.What’s
more, 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 and
have done some programming in a modern programming language before but have not
necessarily 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 at
speed.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 web
development 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 books
that were basically function references.These books are useful, but they don’t help when
your boss or client has said, “Go build me a shopping cart.” In this book, we have done
our best to make every example useful.You can use many of the code samples directly in
your website, and you can use many others with only minor modifications.
01_0672329166_intro.qxd 9/3/08 1:16 PM Page 2

2 Introduction

What You Will Learn from This Book


Reading this book will enable you to build real-world, dynamic websites. If you’ve built
websites using plain HTML, you realize the limitations of this approach. Static content
from a pure HTML website is just that—static. It stays the same unless you physically
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 make
your 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 intro-
ductory chapters.We begin by looking at a simple online ordering system and work our
way through the various parts of PHP and MySQL.
We then discuss aspects of electronic commerce and security as they relate to building
a real-world website and show you how to implement these aspects in PHP and MySQL.
In the final part of this book, we describe how to approach real-world projects and
take you through the design, planning, and building of the following projects:
n User authentication and personalization
n Shopping carts
n Web-based email
n Mailing list managers
n Web forums
n PDF document generation
n Web services with XML and SOAP
n Web 2.0 application with Ajax

You should be able to use any of these projects as is, or you can modify them to suit
your needs.We chose them because we believe they represent some the most common
web-based applications built by programmers. If your needs are different, this book
should help you along the way to achieving your goals.

What Is PHP?
PHP is a server-side scripting language designed specifically for the Web.Within an
HTML 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, Rasmus
Lerdorf. It was adopted by other talented people and has gone through four major
rewrites to bring us the broad, mature product we see today. As of November 2007, it
was installed on more than 21 million domains worldwide, and this number is growing
rapidly. You can see the current number at http://www.php.net/usage.php.
01_0672329166_intro.qxd 9/3/08 1:16 PM Page 3

Introduction 3

PHP is an Open Source project, which means you have access to the source code and
can use, alter, 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 5.This version saw a complete rewrite of the
underlying Zend engine and some major improvements to the language.
The home page for PHP is available at http://www.php.net.
The home page for Zend Technologies is http://www.zend.com.

What Is MySQL?
MySQL (pronounced My-Ess-Que-Ell ) is a very fast, robust, relational database management
system (RDBMS). A database enables you to efficiently store, search, sort, and retrieve
data.The MySQL server controls access to your data to ensure that multiple users can
work with it concurrently, to provide fast access to it, and to ensure that only authorized
users can obtain access. Hence, MySQL is a multiuser, multithreaded server. It uses
Structured Query Language (SQL), the standard database query language. MySQL has been
publicly available since 1996 but has a development history going back to 1979. It is the
world’s most popular open source database and has won the Linux Journal Readers’
Choice Award on a number of occasions.
MySQL is available under a dual licensing scheme.You can use it under an open
source license (the GPL) free as long as you are willing to meet the terms of that license.
If you want to distribute a non-GPL application including MySQL, you can buy a com-
mercial license instead.

Why Use PHP and MySQL?


When setting out to build a website, you could use many different products.
You 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 language

Some of these choices are dependent on the others. For example, not all operating
systems run on all hardware, not all web servers support all programming languages, and
so on.
In this book, we do not pay much attention to hardware, operating systems, or web
server software.We don’t need to. One of the best features of both PHP and MySQL is
that they work with any major operating system and many of the minor ones.
01_0672329166_intro.qxd 9/3/08 1:16 PM Page 4

4 Introduction

The majority of PHP code can be written to be portable between operating systems
and web servers.There are some PHP functions that specifically relate to the filesystem
that are operating system dependent, but these are clearly marked as such in the manual
and in this book.
Whatever hardware, operating system, and web server you choose, we believe you
should seriously consider using PHP and MySQL.

Some of PHP’s Strengths


Some of PHP’s main competitors are Perl, Microsoft ASP.NET, Ruby (on Rails or oth-
erwise), JavaServer Pages (JSP), and ColdFusion.
In comparison to these products, PHP has many strengths, including the following:
n Performance
n Scalability
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 Strong object-oriented support
n Portability
n Flexibility of development approach
n Availability of source code
n Availability of support and documentation

A more detailed discussion of these strengths follows.

Performance
PHP is very fast. Using a single inexpensive server, you can serve millions of hits per day.
Benchmarks published by Zend Technologies (http://www.zend.com) show PHP out-
performing its competition.

Scalability
PHP has what Rasmus Lerdorf frequently refers to as a “shared-nothing” architecture.
This means that you can effectively and cheaply implement horizontal scaling with large
numbers of commodity servers.

Database Integration
PHP has native connections available to many database systems. In addition to MySQL,
you can directly connect to PostgreSQL, Oracle, dbm, FilePro, DB2, Hyperwave,
Informix, InterBase, and Sybase databases, among others. PHP 5 also has a built-in SQL
interface to a flat file, called SQLite.
01_0672329166_intro.qxd 9/3/08 1:16 PM Page 5

Introduction 5

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.
In addition to native libraries, PHP comes with a database access abstraction layer
called PHP Database Objects (PDO), which allows consistent access and promotes secure
coding practices.

Built-in Libraries
Because PHP was designed for use on the Web, it has many built-in functions for per-
forming many useful web-related tasks.You can generate images on the fly, connect to
web services and other network services, parse XML, send email, work with cookies, and
generate PDF documents, all with just a few lines of code.

Cost
PHP is free.You can download the latest version at any time from http://www.php.net
for no charge.

Ease of Learning PHP


The syntax of PHP is based on other programming languages, primarily C and Perl. If
you already know C or Perl, or a C-like language such as C++ or Java, you will be pro-
ductive using PHP almost immediately.

Object-Oriented Support
PHP version 5 has well-designed object-oriented features. If you learned to program in
Java or C++, you will find the features (and generally the syntax) that you expect, such
as inheritance, private and protected attributes and methods, abstract classes and methods,
interfaces, constructors, and destructors.You will even find some less common features
such as iterators. Some of this functionality was available in PHP versions 3 and 4, but
the object-oriented support in version 5 is much more complete.

Portability
PHP is available for many different operating systems.You can write PHP code on free
Unix-like operating systems such as Linux and FreeBSD, commercial Unix versions such
as Solaris and IRIX, OS X, or on different versions of Microsoft Windows.
Well-written code will usually work without modification on a different system run-
ning PHP.

Flexibility of Development Approach


PHP allows you to implement simple tasks simply, and equally easily adapts to imple-
menting large applications using a framework based on design patterns such as
Model–View–Controller (MVC).
01_0672329166_intro.qxd 9/3/08 1:16 PM Page 6

6 Introduction

Source Code
You have access to PHP’s source code.With PHP, unlike commercial, closed-source
products, if you want to modify something or add to the language, you are free to do so.
You do not need to wait for the manufacturer to release patches.You also don’t need
to worry about the manufacturer going out of business or deciding to stop supporting a
product.

Availability of Support and Documentation


Zend Technologies (www.zend.com), the company behind the engine that powers PHP,
funds its PHP development by offering support and related software on a commercial
basis.
The PHP documentation and community are mature and rich resources with a
wealth of information to share.

What Is New in PHP 5?


You may have recently moved to PHP 5 from one of the PHP 4.x versions. As you
would expect in a new major version, it has some significant changes.The Zend engine
beneath PHP has been rewritten for this version. Major new features are as follows:
n Better object-oriented support built around a completely new object model (see
Chapter 6, “Object-Oriented PHP”)
n Exceptions for scalable, maintainable error handling (see Chapter 7, “Error and
Exception Handling”)
n SimpleXML for easy handling of XML data (see Chapter 33, “Connecting to Web
Services with XML and SOAP”)

Other changes include moving some extensions out of the default PHP install and into
the PECL library, improving streams support, and adding SQLite.
At the time of writing, PHP 5.2 was the current version, with PHP 5.3 on the near
horizon. PHP 5.2 added a number of useful features including:
n The new input filtering extension for security purposes
n JSON extension for better JavaScript interoperability
n File upload progress tracking
n Better date and time handling
n Many upgraded client libraries, performance improvements (including better
memory management in the Zend Engine), and bug fixes

Key Features of PHP 5.3


You may have heard about a new major release of PHP, called PHP 6. At the time of
this writing, PHP 6 is not in the release candidate stage, and hosting providers won’t be
01_0672329166_intro.qxd 9/3/08 1:16 PM Page 7

Introduction 7

installing it for mass use for quite some time. However, some of the key features planned
in PHP 6 have been back-ported to PHP 5.3, which is a minor version release and clos-
er to passing acceptance testing and thus installation by hosting providers (of course, if
you are your own server’s administrator, you can install any version you like).
Some of the new features in PHP 5.3 are listed below; additional information also
appears throughout this book as appropriate:
n The addition of namespaces; for more information see http://www.php.net/
language.namespaces
n The addition of the intl extension for application internationalization; for more
information see http://www.php.net/manual/en/intro.intl.php
n The addition of the phar extension for creating self-contained PHP application
archives; for more information see http://www.php.net/book.phar
n The addition of the fileinfo extension for enhanced ability to work with files;
for more information see http://www.php.net/manual/en/book.fileinfo.php
n The addition of the sqlite3 extension for working with the SQLite Embeddable
SQL Database Engine; for more information see http://www.php.net/manual/en/
class.sqlite3.php
n The inclusion of support for the MySQLnd driver, a replacement for libmysql; for
more information see http://forge.mysql.com/wiki/PHP_MYSQLND

While the list above contains some of the highly-touted features of PHP 5.3, the release
also includes a significant number of bug fixes and maintenance performed on existing
functionality, such as:
n Removing support for any version of Windows older than Windows 2000 (such as
Windows 98 and NT4)
n Ensuring the PCRE, Reflection, and SPL extensions are always enabled
n Adding a few date and time functions for ease of date calculation and manipula-
tion
n Improving the crypt(), hash(), and md5() functionality, as well as improving the
OpenSSL extension
n Improving php.ini administration and handling, including better error reporting
n Continuing to fine-tune the Zend engine for better PHP runtime speed and
memory usage

Some of MySQLs Strengths


MySQLs main competitors are PostgreSQL, Microsoft SQL Server, and Oracle.
MySQL has many strengths, including the following:
nHigh performance
nLow cost
Another Random Scribd Document
with Unrelated Content
“Can’t tell what?”
“I mean, dear, that Harriet might have some disease that you
oughtn’t to talk to Mr. van Tuiver about.” Aunt Varina hesitated,
then added, in a whisper, “Some ‘bad disease’.”
Whereat Sylvia started in sudden dismay. So that was it! A “bad
disease”!
You must understand how it happened that Sylvia had ideas on
this subject. There was a foreign writer of plays, whose name she had
heard. She had never seen his books, and would not have opened
one, upon peril of her soul; but once, in a magazine picked up in a
train, she had read a casual reference to an Ibsen play, which dealt
with a nameless and dreadful malady. From the context it was made
clear that this malady was a price men paid for evil living—and a
price which was often collected from their innocent wives and
children. Now and then the women of Sylvia’s family spoke in awe-
stricken whispers of this mysterious taint, using the phrase “a bad
disease.” Now, apparently, she was beholding the horror before her
eyes!
§ 25
The problem occupied Sylvia’s mind for several days, to the
exclusion of everything else. It lent a new dread to the thought of
marriage. How could a woman be safe from such a thing?
Beauregard Dabney was not the most perfect specimen of manhood
that one could have selected, but there was nothing especial the
matter with him that could be observed. Yet see what had happened
to his wife and child!
Harriet came again, and this time her husband was with her. He
was just as much in love with her as ever—in fact, Sylvia thought that
she noted a new and pathetic clinging on his part. They had been to
see a great specialist, and still there was nothing definite to be
learned about the malady; the doctor, hearing that the couple had
journeyed up the Nile, suggested that possibly it might be an African
fever, and promised to look up the mysterious symptoms in his
books. Wasn’t it extraordinary, exclaimed Harriet; but Sylvia, who
could not be deceived for very long, noticed that Beauregard was not
so much excited about the African theory as his wife. Suddenly the
thought came to her, Could it be that the doctors really knew what
the disease was, and would not tell Harriet? Could it be that
Beauregard knew, and was helping in the deception? Then—horror
of horrors—could it be that he had known all along, and had upon his
conscience the crime of having brought the woman he loved into this
state?
Sylvia’s relentless mind, once having got hold of this problem,
clung to it like a bull-dog to the throat of an enemy. Of course such a
disease was a loathsome thing; a woman could not very well ask
questions about it—yet, what was she to do? Apparently she was
dependent upon the man’s honor; and could it be that a man’s notion
of honor permitted him, when he was desperately in love, to take
such chances with a woman’s life? Sylvia remembered suddenly that
Beauregard had made love to her. More than once she had actually
permitted him to hold and fondle her hand. The mere thought made
her shrink with horror.
And then came another idea. (How quickly she was putting things
together!) Men got this disease by evil living. Then Beauregard must
have done the sort of thing that Frank Shirley had been accused of
doing! Also Jack Colton had done the same! Also—had not Bates said
that there were some of the “Auburn Street crowd” in that place?
Club-men, gentlemen, the aristocracy of Harvard! There came back
to her the phrase from Harley’s letter: “one of the two or three high-
class houses of prostitution which are especially frequented by
college men!” How much Sylvia knew about this forbidden subject,
when she came to put her mind to it! More, apparently, than her own
parents—for had they not shown themselves willing for her to fall in
love with Beauregard Dabney? More, also, than Mrs. Winthrop—for
had not that lady implied that it was only low and obscure men who
permitted themselves such baseness?
As you may believe, it was not long before Sylvia’s thoughts came
to her own intended husband. What had been his life? What might
be the chances of her being brought to such a fate as Harriet’s?
Apparently nobody had any thought about it. They had been quick to
avail themselves of the appearance of evil on the part of Frank
Shirley; but what had they done to make sure that van Tuiver had
been any better?
For three days Sylvia debated this problem; and then her mind was
made up—she would do something about it. She would talk to
someone. But to whom?
She began with her faithful chaperone, mentioning the African
fever theory, and so bringing up the subject of “bad diseases.” Just
how much did Aunt Varina know about these diseases? Not very
much, it appeared. Was there any way to find out about them? There
was no way that Aunt Varina could conceive—it was not a subject
concerning which a young girl ought to inquire.
“But,” protested Sylvia, “a girl has to marry. And think of taking
such chances! Suppose, for instance, that Mr. van Tuiver—”
“Ssh!” Aunt Varina almost leaped at her niece in her access of
horror. “Sylvia! how can you suggest such a thing?”
“But, Auntie, how can I be sure?”
“You surely know that the man to whom you have given your heart
is a gentleman!”
“Yes, Auntie, but then I knew that Beauregard Dabney was a
gentleman—and so did you. And see what has happened!”
“But, Sylvia dear! You don’t know that it’s that!”
“I very nearly know it. And if Beauregard was willing to marry
when he—”
“But he may not have known it, Sylvia!”
“Well, don’t you see, Aunt Varina? That makes it all the more
serious! If Mr. van Tuiver himself can be ignorant, how can I feel
safe?”
“But, Sylvia, what could you do?”
“Why, I should think he ought to go to some one who knows—a
doctor—and make sure.”
The poor old lady was almost speechless with horror. What was
the world coming to? “How can you say such a thing?” she
exclaimed. “You, a pure girl! Who could suggest such a thing to Mr.
van Tuiver?”
“Couldn’t Papa do it?”
“And pray, who is to suggest it to your father? Surely you
couldn’t!”
“Why no,” said Sylvia, “perhaps not. But couldn’t Mamma?”
“Your mother would die first!” And Sylvia, remembering her “talk”
with “Miss Margaret,” had to admit that this was probably true.
But still she could not give up her idea that something ought to be
done. She took a couple of days more to think, and then made up her
mind to write to her Uncle Basil. The family had sent him to talk with
her about Frank’s misconduct, thus apparently indicating him as her
proper adviser in delicate matters.
So she wrote, at some length—using most carefully veiled
language, and tearing up many pages which contained words she
could not endure seeing on paper. But she made her meaning clear—
that she thought someone should approach her future husband on
the subject.
Sylvia waited the necessary period for the Bishop’s reply, and read
it with trembling fingers and flaming cheeks—although its language
was even more carefully veiled than her own. The substance of it was
that van Tuiver was a Christian gentleman, and this must be Sylvia’s
guarantee that he would not bring any harm to the woman he so
deeply revered. Surely, if Sylvia respected him enough to marry him,
she could trust him in a matter like this! To approach him upon it
would be to offer him a deadly insult.
Whereupon Sylvia took several days more to worry and wonder.
She was not satisfied at all, and finally summoned her courage and
wrote to the Bishop again. It was not merely a question of honor; if
that were true, she would have to say that Beauregard Dabney was a
scoundrel and she did not believe that. Might it not possibly be
knowledge that was lacking? She begged her uncle to do her the
favor of his life by writing to van Tuiver; and she intimated further
that if he would not do it, she would have to put the matter before
her father.
So there was another wait, and then came a letter from the Bishop,
saying that he was writing as requested. Then, after a third wait, a
letter with van Tuiver’s reply. He had taken the inquiry very
magnanimously; he could understand, he said, how Sylvia had been
upset by the sight of her friend’s illness. As to her own case, she
might rest assured that there could be no such possibility. And so at
last Sylvia’s fears were allayed, and she was free to be unhappy about
other matters.
§ 26
You must not imagine that Sylvia was spending these days in
moping; all her thinking had to be done in the odd moments of a
strenuous career. Day and night she had to meet new people, and
new people were always an irresistible stimulus to her curiosity. Not
all of them were hall-boys and shop-clerks, falling instant victims to
her charms; on the contrary, they were Knickerbocker “society”—
people not infrequently as wealthy as her future husband, and having
an equally great notion of their own importance. The tidings that
Douglas van Tuiver had picked up a country girl had not thrilled
them with sympathetic emotions. The details of the newspaper
romance inspired them only with contempt. There had to be many a
flash of Sylvia’s rapier-wit, and many a flash of Sylvia’s red-brown
eyes, before these patrician plutocrats had been brought to
acknowledge her an equal.
A few of these acquaintances were kindly people, whom she could
imagine making into friends, if only there had been time. But she
wondered how anybody ever found time for friendship in this
restless and expensive and highly ornamental life. Such a whirl of
dinner-parties and supper-parties, dances and luncheons and teas!
Such august and imposing splendor, such dignified and even sombre
dissipation! The Major had provided abundant credit for this last
splurge; and van Tuiver’s aunt was also on hand, conspiring with her
nephew to smother Sylvia under loads of gifts. The girl wondered
sometimes, was it that van Tuiver had suspicions of her wavering,
and sought to bind her by forcing these luxuries upon her? Or would
she be expected always to live this kind of Arabian Nights’ existence?
There came old friends, to bask in the sunlight of her success. Miss
Abercrombie came, effulgent with delight, assured of a lifetime’s
prosperity by this demonstration of her system. With her came
Celeste, playing her difficult part with bitter pride. Harley Chilton
ran down from Boston, bringing the tidings that he had made the
“Dickey” and saw his way clear to the top of the Harvard pyramid.
Last of all, two or three days before the wedding came “Queen
Isabella,” distributing her largess of blessings to all concerned.
First she met “Miss Margaret” and the Major, and addressed them
with such mystical eloquence that the agitated pair had not a dry eye
between them. After which she sought the prospective bride and
bridegroom; and not even the most reverend millionaire bishop who
was to perform the ceremony could have been more pontifical and
impressive than our great lady in this solemn hour. We live in a
cynical world, which affords but poor soil for the nurture of the finer
flowers of the spirit. But Mrs. Winthrop was one really capable of
experiencing the more exalted emotions, and of giving them
ungrudging utterance. She was thrilled now by the vistas which she
saw unfolding; not since the day of her espousal of the celebrated
railroad-builder had the wings of the seraphim rustled so loudly
about her head. She might have been compared to a creative artist
who labors for long in solitude, and who at last, when he reveals his
masterpiece, is startled by the clamor of the world’s applause.
“Sylvia,” she said, and put both her hands upon the girl’s—“Sylvia,
you have before you a great career, a career of service. You will be
happy—I know you must be happy, dear, when once you have come
to realize what an inspiration you are to others. Such fortune as
yours falls but rarely to a woman, but you will be worthy of it—I
believe you will be worthy of everything that has come to you.”
“I hope so, Mrs. Winthrop,” answered Sylvia, humbly.
And then, as van Tuiver discreetly moved away, the other went on,
in a low and deeply-moved voice: “Don’t imagine, dear girl, that I fail
to realize all your doubts and perplexities. I know just how you feel,
for I had to go through with it myself. Every woman does—but
believe me, such tremors are as nothing compared to all the rest of
one’s life. We learn to subordinate our personal feelings, our
personal preferences. That is one of the duties of those who have
greatness as their lot—who have to live what one might call public
lives.”
Now, Sylvia might have her doubts as to the soundness of this
doctrine, but she had none as to the genuineness of the speaker’s
feelings; so she was a trifle shocked when Mrs. Winthrop went away,
and she discovered that her future husband was laughing.
“What is it?” she asked.
“Nothing,” he said, “it’s all right—only when you are Mrs. Douglas
van Tuiver, you will receive Isabella’s ecstasies with a trifle more
reserve. You will realize that she has her own axes to grind.”
“Axes—what do you mean?”
“Social axes. You’ll understand my world bye-and-bye, Sylvia.
Isabella’s trying to make an impression beyond her income, and she’s
seeking alliances. What you must remember is that the need is on
her side.”
There was a pause, while Sylvia sat thinking. “Tell me,” she said, at
last, “why did Mrs. Winthrop change so suddenly, and begin urging
me to marry you?”
“It’s the same thing,” he answered. “She couldn’t afford to
displease me. When she found that I was determined to have my
way, she tried to make it seem her work. Naturally, she’d want as
much of the prestige of this wedding as she could get.”
Again Sylvia pondered. “Hasn’t Mrs. Winthrop’s husband enough
money?” she asked.
“He has enough, but he won’t spend it. The tragedy of Isabella’s
life is that her husband is really interested in railroads.”
“But I thought he adored her!” Sylvia remembered a pathetic stout
gentleman she had seen wandering about on the outskirts of a throng
of the great lady’s admirers.
“Oh, yes,” replied van Tuiver, with laughter. “I never saw a woman
who had a man more completely bluffed. But the trouble is that he
offers himself, and what she wants is his money.”
There followed a long silence. Van Tuiver had pleasant things to
meditate upon; but suddenly he chanced to look at Sylvia, and
exclaimed, “Why, what’s the matter?”
“Nothing,” she said, and turned away her head to conceal the tears
she had failed to repress.
“But what is it?” he demanded, not without a touch of annoyance.
“There’s no use talking about it,” was Sylvia’s reply. “It’s just that
you promised you would try not to think so much about money.
Sometimes I can’t help being frightened, when I realize that you
don’t ever believe in people—but only in money.”
She saw the old worried look come back to his face. “You know
that I believe in you!” he exclaimed.
“You told me,” she answered, “that the only way I was able to make
an impression upon you was by refusing to marry you. And now I
have given up that prestige—so aren’t you afraid that you may come
to feel about me as you do about Mrs. Winthrop?”
§ 27
Major and Mrs. Castleman arrived next morning, and after that
there were busy times for Sylvia. There was the wedding-gown to be
shown, and the trousseau and the presents; there were plans for the
future to be told of, and many blessings to be received. “Miss
Margaret” was in a “state” most of the time—tears of joy and tears of
sorrow pursuing each other down her generous cheeks. “Sylvia,” she
exclaimed, in one breath, “I know you will be happy!” And then, in
the next breath, “Sylvia, I hope you will be happy!” And then, in a
third breath, “Sylvia, how will we ever get on without you? Who will
dare to spank the baby?”
It was with her father that she had the really trying ordeal; her
father took her into a room alone, and held her hands in his and tried
to read her soul. “Tell me, my child, are you going to be happy?”
“I think so, Papa,” she answered; and had to make herself look into
his eyes.
“I want you to understand me, dear Sylvia—even now, at this last
hour, don’t take the step unless you believe with your best judgment
that you will be happy.”
There was a moment of madness, when she had the impulse to
fling herself into his arms and cry, “I love Frank Shirley!” But instead
of that she hurried on, “I believe he loves me deeply, Papa.”
Said the Major, in a trembling voice, “There is no more solemn
moment in a father’s life than when he sees his dearly loved daughter
taking this irrevocable step. I want you to know, my darling, that I
have prayed earnestly, I have done my best to judge what is right for
you.”
“Yes, Papa,” she said, “I know that.”
“I want you to know that if ever I have seemed to be stern, it has
been because I believed my daughter’s welfare required it.”
“Yes, Papa,” she said, again.
“I am sure, this man loves you, Sylvia; and I believe he’s a good
man—he ought to make you happy. But I want you to know that if by
any chance my prayers are denied—if you find that you are not happy
—then your father’s home will always be open to you, his arms will
always be stretched wide to clasp you.”
“Dear old Daddy!” whispered the girl. She felt the arms about her
now, and she began to sob softly, with a mixture of emotions. Oh, if
only she might stay for the balance of her life in the shelter of those
arms, that were so strong and so dependable! If only there were not
the dreadful thing called marriage—which drove her out into another
pair of arms, from which she shrunk with such unconquerable
aversion!
This was the heart of her difficulty—her inability to conquer her
physical shrinking from the man to whom she was betrothed. Here
she was, upon the very eve of her wedding, and she had made no
progress whatever. Mentally and spiritually she had probed him, and
felt that she knew him intimately; but physically he was still an utter
stranger to her—as much so as any man she might have met upon the
street. She would sit talking with him, trying to forget herself and her
fears for a while; and gradually she would be conscious of his gaze
upon her, his eyes traveling over her form, devouring her in thought,
longing for her. Then she would go almost beside herself—she would
have to spring up and break the chain of his thoughts. It seemed to
her that she was like the prey of some wild beast—or a beast that was
just tame enough to wait patiently, knowing that at a certain time the
prey would be in its grasp.
On the evening before the wedding van Tuiver was to attend a
“stag-dinner” with his friends; but he called in to see her for a few
minutes, and the family discreetly left them alone. In a sudden access
of longing, he clasped her in his arms, and she forced herself to
submit. Then he began to kiss her, to press passionate kisses upon
her cheek and throat. His breath was hot, and utterly horrible to her;
she could not endure it, and cried out to him to stop, and struggled
and pushed him away. Still holding her, and gazing at her with desire
blazing in his eyes, he whispered, “Not yet?”
“Oh, how could you?” she cried.
“Is it not time you were beginning to learn?” he demanded; and
then, wholly beside himself, “Sylvia, how much longer am I to endure
this? Can’t you understand what you make me suffer? I love you—I
love you to distraction, and I get nothing from you—nothing! I dare
not even tell you that I love you!”
The passion in his voice made her shudder; and yet, too, she pitied
him. She was ashamed of herself for the way she treated him. “What
can I do?” she cried. “I can’t help it—as God is my witness, I can’t
control my feelings. I ask myself, ought I to marry you so?”
“It seems to me it’s rather late to bring up that question,” he
responded.
“I know, I know! I have nothing to say for myself—except that I
didn’t know, I couldn’t realize. It’s something I must tell you—how I
have come to feel—that I ought not to marry you, that you ought not
to want me to marry you, while things are like this. You must know
this, so that if I marry you, the responsibility will be yours!”
“And you think that is fair of you?” he demanded, his voice grown
suddenly hard.
He meant to rebuke her, and she felt that he had a right to rebuke
her; but the wave of emotion which swept her along was not to be
controlled by her reason. “Oh, you are going to be angry about it!”
she cried. “How horrible of you!”
He exclaimed, “Sylvia! Can you expect me not to be hurt?”
“I told you that I couldn’t help it! I told you in the very beginning
that you would have to take me as I was, and be satisfied if I did my
best! I told you that again and again—that I loved another man, that
I love him still—”
She stopped. A spasm of pain crossed his face—followed by a look
of fear. He hesitated, and then, his voice low and trembling, he
began, “Sylvia, forgive me. I know that you are right—that you are
trying to do your best. I will be patient. You must be patient with me
also.”
She stood, her head bowed, ashamed of what she had said. Yet—
she felt that he ought to have heard it. “I hate to seem unfair,” she
whispered, her voice almost breaking. “I don’t want to give you pain,
but I can’t help these feelings, and I know it’s my duty to tell you of
them. I don’t see how you can go on—I should think you would be
afraid to marry me!”
For answer he caught her hands, exclaiming, “I will take my
chances! I love you, and I will never rest until you love me!”
§ 28
So far I have put together this story from the memories of Sylvia
and Frank Shirley. But now I have come to the point where you may
watch the events through my own eyes. I will take a paragraph or two
to give you an idea of the quality of these eyes, and then proceed
without further delay.
Mary Abbott, the teller of this tale, was at the age of forty a crude
farmer’s wife upon a lonely pioneer homestead in Manitoba. In
winter in that part of the world it begins to grow dark at three o’clock
in the afternoon, and it is not fully light until nine o’clock in the
morning. We were a mile from the nearest neighbor, and had often
three feet of snow upon the ground, with fifty degrees below zero and
a sweeping wind. I had a husband whom I feared and despised, and
for whom I cooked and washed and sewed, whether I was well or ill.
Under these circumstances I had raised three children to maturity. I
had moved to town and seen them through high-school; and now,
the girl being married, and the two boys in college, I found myself
suddenly free to see the world.
You must not think of me as altogether ignorant. I had fought
desperately for books, and had grown up with my children.
Discovering in the town the perpetual miracle of a circulating library,
I had read wildly, acquiring a strange assortment of new ideas. But
that, I am ashamed to say, made very little difference when I reached
the East. It is one thing to read up in the theory of Socialism, and say
that you have freed yourself from bourgeois ideals; it is quite another
to come from a raw pioneer community, and be suddenly hit between
the eyes by all the marvels of the great New Nineveh!
I forgot my principles; I wandered about, breathless with
excitement. Everything that I had ever read about, in Sunday
supplements and cheap magazines—here it was before my eyes! I got
myself a hall-room in a “Greenwich Village” boarding-house, and for
days I went, thrusting my inquisitive country face into everything
that was cheap enough. The huge shops with their amazing treasures
of silks and jewels; the great hotels with their gold and stucco
splendors; the dizzy, tower-like office-buildings; the newspaper
offices with their whirling presses; the theatres, the museums, the
parks; the Brooklyn Bridge and the Statue of Liberty, Grant’s Tomb
and the Bowery—I was the very soul of that thing which the New
Yorker derisively calls the “rubber-neck wagon!” I took my place in
one of these moving grand-stands, and listened to all that came out
of the megaphone. Here was the home of the steel-king, which had
cost three millions of dollars! Here was the home where a fifty
thousand dollar chef was employed! Here was the old van Tuiver
mansion, where the millionaire-baby had been brought up! Here was
the Palace Hotel, where Miss Sylvia Castleman was staying!
It was the day before the wedding; and I, like all the rest of the city,
was thrilling over the Romance, knowing more about the
preparations than the bride herself. I had read all the papers—
morning papers and afternoon papers; I had read descriptions of the
wedding-gown, the trousseau, the rooms full of gift-treasures with
detectives on guard. I had stared at the outside of the church, and
imagined the inside. Last of all, I had wandered up to the Palace
Hotel and peered about in the lobby, amusing myself by imagining
that each gorgeous female creature who floated by and disappeared
into a motor-car might possibly be the Princess herself!
At the boarding-house we discussed the possibility of seeing the
wedding-cortege, and everybody said that I could not come within a
block of the church. “I’ll fight my way,” I declared; to which the reply
was that I would find out something about New York policemen that
would cure me of my fighting impulses. The result of the discussion
was that I set out immediately after breakfast, fired with the spirit of
the discoverers of Pike’s Peak.
I must get at least a glimpse, I told myself. What a tale to be able to
tell at the Women’s Club receptions at home! To say: “I saw her! She
was the loveliest thing! And oh, her dress! It was cream-white satin,
with four graduated flounces of exquisite point-lace!” Of course I
could have got all that from the newspapers; but I wanted to be able
to say it truly.
The wedding-hour was noon, but at nine there was already a
respectable crowd. I established myself upon the steps of a nearby
house, with a newspaper to sit on and a pair of borrowed opera-
glasses in my hand-bag. In the meantime I entertained myself talking
with the other watchers, who were a new type to me, well-dressed
women, kept in luxury, whether legal or otherwise, who fed their
empty minds upon fashion sheets and “society notes,” and had no
idea in the world beyond the decking of their persons and the playing
of their little part in the great game of Splurge. We talked about the
van Tuiver family, its history and its present status; we talked with
awe about the bride; we talked about the presents, the decorations,
the costumes—there was so much to talk about!
Shortly after ten o’clock a calamity befell us—the police began to
clear the steps, driving the crowd far back from the church-entrance.
What agonies, what expostulations! How outrageous—when we had
waited there an hour already! Sometimes the steps were our own
steps, sometimes they were the steps of friends; but even that made
no difference. “I’m sorry, lady, the orders are to clear everything.”
They were as gentle about it as they could be, but that was none too
gentle; we had the butt-ends of clubs, pressing into our stomachs,
and back we went, arguing, scolding, threatening, sometimes
weeping or fainting.
I was tremendously disappointed. To have to go back to the
boarding-house, and admit defeat to the milliner’s assistant who sat
next to me at meals! To hear “I told you so” from the “floor-walker”
who sat across the way! “I won’t do it!” I said to myself.
And then suddenly came my chance. Behind me there was a
commotion, angry protests—“Officer, let us through here! We have
cards!” Cards—how our souls thrilled as we heard the word! Here,
right close to us, were some of the chosen ones! Let us see them at
least—a bit of Royalty at second hand!
They pushed their way through—three women and two men. As
they neared me, I saw the engraved invitations in their hands, and it
flashed over me that in my hand-bag was a milliner’s advertisement
of nearly the same size and shape. I dived in, and fished it out with
trembling fingers, and fell in behind the party, and pushed through
the crowd past the line of police. There before me was the open space
in front of the church!
I had acted on impulse, with no idea what to do next. I could
scarcely hope to get in to the wedding on a milliner’s card. But
fortunately my problem solved itself, for there were always the guests
pushing into the entrance, and everybody was perfectly willing to
push ahead of me. All I had to do was to “mark time,” and I was free
to stay, inhaling delicious perfumes and feasting my ears upon scraps
of the conversation of the élite. I foresaw that the banner of the great
Northwest would wave triumphantly in “Greenwich Village” that
night!
§ 29
I will not stop to detail the separate thrills of this adventure.
Carriage after carriage, motor after motor drew up, and released new
revelations of grace and elegance. The time for the ceremony drew
near, and from the stir in the throng about me I knew that the guests
from the wedding-breakfast were passing. How I longed to talk to
someone—to ask who was this and that and the other one! Then I
might have been able to tell you how “Miss Margaret” wept, and how
Aunt Varina trembled, and what “Queen Isabella” was wearing! But
the only persons I could be sure of were the five lovely bridesmaids,
and the bride, leaning upon the arm of a stately old white-haired
gentleman. How we craned our necks, and what rapture transported
us! We heard the thunder of the organ and the orchestra within, and
it corresponded to the state of our souls.
There was still quite a throng at either side of the entrance—
newspaper reporters, people who had come out of houses nearby,
people who, like myself, had got by the police-lines upon one pretext
or another. Down the street we could see a solid line of bluecoats,
and behind them people crowded upon steps, leaning out of
windows, clinging to railings and lamp-posts. We were in fear lest at
any time we might be ordered to join this throng, so we stayed silent
and very decorous, careful not to crowd or to make ourselves
conspicuous.
You might have expected, perhaps, that when all the protagonists
of the drama had entered the church, the crowd would have
dispersed; but not a soul went. We stood, listening to the faint music,
and imagining the glories that were hid from our eyes. We pictured
the procession up the aisle, with the guests standing on the seats in
order to get a glimpse of it. We pictured the sacred ceremony. (There
were some who had prayer-books in their hands, the better to aid
their imaginations.) We pictured the bride, kneeling upon a white
silk cushion embroidered with gold, receiving the blessings of the
millionaire bishop. We heard the wild burst of chimes which told us
that the two were made one, and our pulses leaped with excitement.
All this took perhaps half an hour; and I think that about half that
time had passed when I first noticed Claire. I never knew how she got
there; but fate, or providence, or what you will, had set her next to
me, and that strange intuition which sometimes comes to me, and
puts me inside the soul of another person in less time than it takes
for my eye to look them over, gave me the warning of danger from
her presence.
She was a tall and striking woman, beautifully gowned, with high
color and bold black eyes—a woman you would have noticed in any
gathering. You would have thought at once that she was a foreigner,
but you might have been puzzled as to her country, for she had none
of the characteristic French traits, and her English was quite perfect.
I glanced at her once, and thereafter I forgot everything else—the
crowd, the ceremony, all. What was the matter with this woman?
What first made me turn was a quick motion, as of a nervous
spasm. Then I saw that her hands were clenched tightly, and drawn
up in front of her as if she were struggling with someone. Her lips
were moving, yet I heard no sound; she was staring in front of her
fixedly, but at nothing.
I must explain that it did not occur to me that she had been
drinking. My country imagination was not equal to that flight. To be
sure, since my arrival I had learned that the women of the New
Nineveh did drink; I had peered into the “orange room,” and the
“palm room,” and several other strange rooms, and had seen
gorgeous peacock-creatures with little glasses of highly-colored
liquids before them. But I had not got so far as to imagine any
consequences; I had never thought of connecting the high color in
women’s cheeks, the sparkle in women’s eyes, the animation of
women’s chatter with the little glasses of highly-colored liquids. They
had so many other reasons for being animated, these fortunate,
victorious ones!
No, I only knew that this woman was excited; and I began
forthwith to imagine most desperate and romantic things. You must
remember what I said when I was first telling about Sylvia—that my
ideas of the grand monde had been derived from cheap fiction in
“Farm” and “Home” and “Fireside” publications. You all know the
old story of the beautiful heroine who marries the dissolute duke;
how the duke’s cast-off mistress attends the wedding, and does
something melodramatic and thrilling—perhaps shoots at the duke,
perhaps throws vitriol at the bride, perhaps hands her a letter which
is worse than vitriol to her innocent young soul. I smile when I think
how instantly I understood this situation, and with what desperate
seriousness I made ready to play my part—watching the woman like
a cat, ready to spring and seize her at the first hostile move. And yet,
after all, it was no joke, for Claire was really quite capable of a
murderous impulse when she was in her present condition.
Other people had begun to notice her peculiar behavior; I saw one
or two women edging away from her, but I stayed all the closer. The
time came when we heard the music of the Mendelssohn March, and
the excitement in the crowd told us what was coming. Suddenly the
doors of the church swung open—and there, in her radiant loveliness
—the bride!
Her veil was thrown back, but her eyes were cast down, and she
clung to the arm of her husband. Oh, what a vision she was, and what
a thrill went about! For myself, however, I scarcely saw her. My eyes
were on the strange woman.
She looked like a mad creature; quivering in every nerve, her
fingers twisting and untwisting themselves like writhing snakes. She
had crouched, as if ready to spring; and I had my hands within a foot
of hers, ready to stop her. The procession moved through the passage
kept clear by the police, and I literally held my breath while they
passed—held it until the bride had stepped into a limousine, and the
bridegroom had followed, and the door had slammed. Then suddenly
the strange woman drew herself up and turned upon me, her face
glaring into mine. I saw her wild eyes—and also I got a whiff of her
breath. She laughed, a hysterical, hateful laugh, and muttered: “She’ll
pay for what she gets!”
I whispered “Hush!” But the woman cried again, so that several
people heard her: “She’ll pay for everything she gets from him!” She
added a phrase in French, the meaning and import of which I
learned to understand long afterwards—“Le cadeau de noce que la
maitresse laisse dans la corbeille de la jeune fille!” Then suddenly I
saw her sway, and I caught her and steadied her, as I know how to
steady people with my big strong arms.
And that, reader, was the strange way of my coming into the life of
Sylvia Castleman!
NEW BOOKS YOU OUGHT TO READ

WRITTEN IN THE SAND. By G. R. DUVAL


This is a romance, perhaps it would be truer to say THE romance,
of the Sahara. For the desert, ever changing, ever mysterious, is less a
setting for than an actor in this dramatic story of love and adventure,
wherein the eternal word of all romance is written in the sand by a
beautiful English girl as her answer to a French captain of spahees.
Cloth, 335 pages. Decorated Jacket and Frontispiece by
George Gibbs. Price, $1.20 net. Postage, 14 cents.

THE RELUCTANT LOVER. By STEPHEN McKENNA


The Reluctant Lover is the most modern of modern young men,
and still more advanced is the determined girl who sets out to
capture his cool, chaste heart. In portraying her and her preference
for an unwilling rather than a willing lover, Mr. Stephen McKenna
strikes a note of refreshing unconventionality and shows a profound
knowledge of modern feminine psychology that will especially
delight his women readers.
Cloth, 340 pages. Decorated Jacket. Price, $1.20 net.
Postage, 14 cts.

THE MYSTERY OF 31, NEW INN. By R. AUSTIN


FREEMAN
The fact that Jeffrey Blackmore made two wills, seemingly alike yet
cunningly different, caused John Thorndyke, master-mind, to
suspect a tragedy. With the logic and cool analysis of a lawyer and
scientist he works out and proves his theory in the most startling
manner, bringing the work to an amazing but thoroughly logical
conclusion. In John Thorndyke, Mr. Freeman has created one of the
most fascinating characters of recent fiction.
Cloth, 340 pages. Price, $1.20 net. Postage, 14 cents.

A LIVING LEGACY. By RUTH UNDERWOOD


This is the story of a marvelous girl—with strong, clear views of life
and duty—always sane but sometimes startling. The man is a big,
broadminded, open-hearted man who does big things in a big way.
Around the two is woven a love story which grips and carries you
almost breathlessly through to the climax.
Cloth, 438 pages. Price, $1.35 net. Postage, 14 cents.

THE GULF BETWEEN. By ANNA COSTANTINI


The romantic story of a beautiful American girl who does not find
in her marriage to an Italian Count the undivided devotion she
expects, and who does not readily adapt herself to the idle social life
of the Italian nobility. This revelation by one “on the inside” is sure
to appeal to a large circle of readers.
Cloth, 320 pages. Price, $1.20 net. Postage, 12 cents.

The John C. Winston Company


WINSTON BUILDING PHILADELPHIA
TRANSCRIBER’S NOTES
1. Silently corrected typographical errors and variations in
spelling.
2. Archaic, non-standard, and uncertain spellings retained as
printed.
*** END OF THE PROJECT GUTENBERG EBOOK SYLVIA: A NOVEL
***

Updated editions will replace the previous one—the old editions


will be renamed.

Creating the works from print editions not protected by U.S.


copyright law means that no one owns a United States
copyright in these works, so the Foundation (and you!) can copy
and distribute it in the United States without permission and
without paying copyright royalties. Special rules, set forth in the
General Terms of Use part of this license, apply to copying and
distributing Project Gutenberg™ electronic works to protect the
PROJECT GUTENBERG™ concept and trademark. Project
Gutenberg is a registered trademark, and may not be used if
you charge for an eBook, except by following the terms of the
trademark license, including paying royalties for use of the
Project Gutenberg trademark. If you do not charge anything for
copies of this eBook, complying with the trademark license is
very easy. You may use this eBook for nearly any purpose such
as creation of derivative works, reports, performances and
research. Project Gutenberg eBooks may be modified and
printed and given away—you may do practically ANYTHING in
the United States with eBooks not protected by U.S. copyright
law. Redistribution is subject to the trademark license, especially
commercial redistribution.

START: FULL LICENSE


THE FULL PROJECT GUTENBERG LICENSE
PLEASE READ THIS BEFORE YOU DISTRIBUTE OR USE THIS WORK

To protect the Project Gutenberg™ mission of promoting the


free distribution of electronic works, by using or distributing this
work (or any other work associated in any way with the phrase
“Project Gutenberg”), you agree to comply with all the terms of
the Full Project Gutenberg™ License available with this file or
online at www.gutenberg.org/license.

Section 1. General Terms of Use and


Redistributing Project Gutenberg™
electronic works
1.A. By reading or using any part of this Project Gutenberg™
electronic work, you indicate that you have read, understand,
agree to and accept all the terms of this license and intellectual
property (trademark/copyright) agreement. If you do not agree
to abide by all the terms of this agreement, you must cease
using and return or destroy all copies of Project Gutenberg™
electronic works in your possession. If you paid a fee for
obtaining a copy of or access to a Project Gutenberg™
electronic work and you do not agree to be bound by the terms
of this agreement, you may obtain a refund from the person or
entity to whom you paid the fee as set forth in paragraph 1.E.8.

1.B. “Project Gutenberg” is a registered trademark. It may only


be used on or associated in any way with an electronic work by
people who agree to be bound by the terms of this agreement.
There are a few things that you can do with most Project
Gutenberg™ electronic works even without complying with the
full terms of this agreement. See paragraph 1.C below. There
are a lot of things you can do with Project Gutenberg™
electronic works if you follow the terms of this agreement and
help preserve free future access to Project Gutenberg™
electronic works. See paragraph 1.E below.
1.C. The Project Gutenberg Literary Archive Foundation (“the
Foundation” or PGLAF), owns a compilation copyright in the
collection of Project Gutenberg™ electronic works. Nearly all the
individual works in the collection are in the public domain in the
United States. If an individual work is unprotected by copyright
law in the United States and you are located in the United
States, we do not claim a right to prevent you from copying,
distributing, performing, displaying or creating derivative works
based on the work as long as all references to Project
Gutenberg are removed. Of course, we hope that you will
support the Project Gutenberg™ mission of promoting free
access to electronic works by freely sharing Project Gutenberg™
works in compliance with the terms of this agreement for
keeping the Project Gutenberg™ name associated with the
work. You can easily comply with the terms of this agreement
by keeping this work in the same format with its attached full
Project Gutenberg™ License when you share it without charge
with others.

1.D. The copyright laws of the place where you are located also
govern what you can do with this work. Copyright laws in most
countries are in a constant state of change. If you are outside
the United States, check the laws of your country in addition to
the terms of this agreement before downloading, copying,
displaying, performing, distributing or creating derivative works
based on this work or any other Project Gutenberg™ work. The
Foundation makes no representations concerning the copyright
status of any work in any country other than the United States.

1.E. Unless you have removed all references to Project


Gutenberg:

1.E.1. The following sentence, with active links to, or other


immediate access to, the full Project Gutenberg™ License must
appear prominently whenever any copy of a Project
Gutenberg™ work (any work on which the phrase “Project
Gutenberg” appears, or with which the phrase “Project
Gutenberg” is associated) is accessed, displayed, performed,
viewed, copied or distributed:

This eBook is for the use of anyone anywhere in the United


States and most other parts of the world at no cost and
with almost no restrictions whatsoever. You may copy it,
give it away or re-use it under the terms of the Project
Gutenberg License included with this eBook or online at
www.gutenberg.org. If you are not located in the United
States, you will have to check the laws of the country
where you are located before using this eBook.

1.E.2. If an individual Project Gutenberg™ electronic work is


derived from texts not protected by U.S. copyright law (does not
contain a notice indicating that it is posted with permission of
the copyright holder), the work can be copied and distributed to
anyone in the United States without paying any fees or charges.
If you are redistributing or providing access to a work with the
phrase “Project Gutenberg” associated with or appearing on the
work, you must comply either with the requirements of
paragraphs 1.E.1 through 1.E.7 or obtain permission for the use
of the work and the Project Gutenberg™ trademark as set forth
in paragraphs 1.E.8 or 1.E.9.

1.E.3. If an individual Project Gutenberg™ electronic work is


posted with the permission of the copyright holder, your use and
distribution must comply with both paragraphs 1.E.1 through
1.E.7 and any additional terms imposed by the copyright holder.
Additional terms will be linked to the Project Gutenberg™
License for all works posted with the permission of the copyright
holder found at the beginning of this work.

1.E.4. Do not unlink or detach or remove the full Project


Gutenberg™ License terms from this work, or any files
Welcome to Our Bookstore - The Ultimate Destination for Book Lovers
Are you passionate about books and eager to explore new worlds of
knowledge? At our website, we offer a vast collection of books that
cater to every interest and age group. From classic literature to
specialized publications, self-help books, and children’s stories, we
have it all! Each book is a gateway to new adventures, helping you
expand your knowledge and nourish your soul
Experience Convenient and Enjoyable Book Shopping Our website is more
than just an online bookstore—it’s a bridge connecting readers to the
timeless values of culture and wisdom. With a sleek and user-friendly
interface and a smart search system, you can find your favorite books
quickly and easily. Enjoy special promotions, fast home delivery, and
a seamless shopping experience that saves you time and enhances your
love for reading.
Let us accompany you on the journey of exploring knowledge and
personal growth!

ebookgate.com

You might also like