0% found this document useful (0 votes)
8 views

Core web application development with PHP and MySQL 1. printing Edition Wandschneider all chapter instant download

Core

Uploaded by

brasecooke51
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views

Core web application development with PHP and MySQL 1. printing Edition Wandschneider all chapter instant download

Core

Uploaded by

brasecooke51
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 67

Visit https://ebookfinal.

com to download the full version and


explore more ebook

Core web application development with PHP and MySQL


1. printing Edition Wandschneider

_____ Click the link below to download _____


https://ebookfinal.com/download/core-web-application-
development-with-php-and-mysql-1-printing-edition-
wandschneider/

Explore and download more ebook at ebookfinal.com


Here are some recommended products that might interest you.
You can download now and explore!

PHP and MySQL Web development fourth edition Thomson

https://ebookfinal.com/download/php-and-mysql-web-development-fourth-
edition-thomson/

ebookfinal.com

PHP and MySQL Web Development Second Edition Welling L.

https://ebookfinal.com/download/php-and-mysql-web-development-second-
edition-welling-l/

ebookfinal.com

Web Application Development with Yii and PHP 2nd Revised


ed. Edition Jeffrey Winesett

https://ebookfinal.com/download/web-application-development-with-yii-
and-php-2nd-revised-ed-edition-jeffrey-winesett/

ebookfinal.com

Build Your Own Database Driven Web Site Using PHP MySQL
4th Edition Kevin Yank

https://ebookfinal.com/download/build-your-own-database-driven-web-
site-using-php-mysql-4th-edition-kevin-yank/

ebookfinal.com
Learning PHP MySQL JavaScript and CSS 2nd Edition Robin
Nixon

https://ebookfinal.com/download/learning-php-mysql-javascript-and-
css-2nd-edition-robin-nixon/

ebookfinal.com

Learning PHP MySQL Step by Step Guide to Creating Database


Driven Web Sites Second Edition Michele E. Davis

https://ebookfinal.com/download/learning-php-mysql-step-by-step-guide-
to-creating-database-driven-web-sites-second-edition-michele-e-davis/

ebookfinal.com

Learning PHP MySQL JavaScript With jQuery CSS HTML5 Early


Release 5th 5th Edition Robin Nixon

https://ebookfinal.com/download/learning-php-mysql-javascript-with-
jquery-css-html5-early-release-5th-5th-edition-robin-nixon/

ebookfinal.com

PHP MySQL The Missing Manual Second Edition Brett


Mclaughlin

https://ebookfinal.com/download/php-mysql-the-missing-manual-second-
edition-brett-mclaughlin/

ebookfinal.com

Learning Joomla 1 5 Extension Development Creating Modules


Components and Plugins with PHP 1st Edition Joseph L.
Leblanc
https://ebookfinal.com/download/learning-joomla-1-5-extension-
development-creating-modules-components-and-plugins-with-php-1st-
edition-joseph-l-leblanc/
ebookfinal.com
Core web application development with PHP and
MySQL 1. printing Edition Wandschneider Digital
Instant Download
Author(s): Wandschneider, Marc
ISBN(s): 9780131867161, 0131867164
Edition: 1. printing
File Details: PDF, 9.63 MB
Year: 2005
Language: english
core
WEB APPLICATION
DEVELOPMENT
WITH PHP AND
MYSQL
core
WEB APPLICATION
DEVELOPMENT
WITH PHP AND
MYSQL

MARC WANDSCHNEIDER

Prentice Hall Professional Technical Reference

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

New York • Toronto • Montreal • London • Munich • Paris • Madrid

Capetown • Sydney • Tokyo • Singapore • Mexico City


Many of the designations used by manufacturers and sellers to distinguish their products are
claimed as trademarks. Where those designations appear in this book, and the publisher was aware
of a trademark claim, the designations have been printed with initial capital letters or in all capitals.
The author and publisher have taken care in the preparation of this book, but make no expressed or
implied warranty of any kind and assume no responsibility for errors or omissions. No liability is
assumed for incidental or consequential damages in connection with or arising out of the use of the
information or programs contained herein.
The publisher offers excellent discounts on this book when ordered in quantity for bulk purchases or
special sales, which may include electronic versions and/or custom covers and content particular to
your business, training goals, marketing focus, and branding interests. For more information, please
contact:
U. S. Corporate and Government Sales
(800) 382-3419
corpsales@pearsontechgroup.com
For sales outside the U. S., please contact:
International Sales
international@pearsoned.com

This Book Is Safari Enabled


The Safari Enabled icon on the cover of your favorite technology book means the
book is available through Safari Bookshelf. When you buy this book, you get free
access to the online edition for 45 days. Safari Bookshelf is an electronic reference
library that lets you easily search thousands of technical books, find code samples, download chap-
ters, and access technical information whenever and wherever you need it.
To gain 45-day Safari Enabled access to this book:
Go to http://www.phptr.com/safarienabled
Complete the brief registration form
Enter the coupon code [SE coupon code to come]
If you have difficulty registering on Safari Bookshelf or accessing the online edition, please e-mail
customer-service@safaribooksonline.com.

Visit us on the Web: www.phptr.com


Library of Congress Cataloging-in-Publication Data:
Wandschneider, Marc
Core Web application development with PHP and MySQL / Marc Wanddschneider.
p. cm.
Includes index.
ISBN 0-13-186716-4
1. Web site development. 2. PHP (Computer program language) 3. MySQL (Elecronic
resource ) 4. Application software—Development. I. Title.
TK5105.888.W36116 2005
005.2’762—dc22
2005014955
Copyright © 2006 Pearson Education, Inc.
All rights reserved. Printed in the United States of America. This publication is protected by copy-
right, and permission must be obtained from the publisher prior to any prohibited reproduction,
storage in a retrieval system, or transmission in any form or by any means, electronic, mechanical,
photocopying, recording, or likewise. For information regarding permissions, write to:
Pearson Education, Inc.
Rights and Contracts Department
One Lake Street
Upper Saddle River, NJ 07458

ISBN 0-13-186716-4
Text printed in the United States on recycled paper at R.R. Donnelly in Crawfordsville, IN.
First printing, September 2006
Contents

Introduction xxiii
Target Audience xxiii
About PHP xxiv
Layout xxiv
Before You Begin xxv
Acknowledgments xxv
In Closing xxvi

■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■

PART I The Basics of PHP


■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■

Chapter 1 Getting Started with PHP 3


Your First PHP Programs 3
Entering PHP Scripts 6
Marking Sections of PHP Code 6
Mixing PHP and HTML 6
Statements and Comments 8
How to Store Data 9
Entering Basic Types in PHP 10
Numbers 10
Strings 12
Booleans 15
Some Very Useful Functions 16
nl2br 16
var_dump 17
print_r 17
var_export 18
Summary 18

V
Contents
vi

Chapter 2 The PHP Language 19


More on Entering Strings 19
More on Data Types 21
Arrays 21
Objects 22
Special Types and Values 23
Type Conversions 24
Basics 24
Specific Type Conversions 25
Useful Type Conversion Functions 28
Variables and Constants 30
Defining Constants 30
By Value and by Reference Variables 30
Variable Scope 32
Variable Lifetime 32
Predefined Variables 33
Expressions and Operators 33
Operators: Combining Expressions 33
Combining Expressions and Operator Precedence 40
Control Structures 42
if Statements 42
switch Statement 42
while/do…while Loops 44
for Loops 45
foreach Loops 46
Interrupting Loops 46
Summary 47

Chapter 3 Code Organization and Reuse 49


Basic Code Reuse: Functions 49
Defining and Calling Functions 50
Passing Parameters to Functions 52
Returning Values from a Function 57
Variable Scope Inside of Functions 59
Function Scope and Availability 62
Functions as Variables 64
Intermediate Code Reuse: Using and Including Files 65
Organizing Code into Files 65
Choosing Filenames and Locations 67
Including Your Library Files in Script 69
Using Inclusion for Page Templating 75
Summary 76
Contents
vii

Chapter 4 Object-Oriented Programming 77


Moving Beyond Libraries 77
Object-Oriented Programming 81
Some Basic Terminology 81
The Basics of Objects in PHP 82
Initializing and Cleaning Up Objects 86
Visibility: Controlling Who Sees Things 88
Adding Static Data to Classes 91
Extending Objects 95
Extending Existing Classes 95
Visibility Revisited 96
Reimplementing Methods from Our Base Class 97
Making Classes Act the Same: Polymorphism 98
Other Features 107
Comparing Objects 107
Cloning Objects 107
User-Friendly Output 108
Type Hinting 109
Autoloading 110
Summary 111

Chapter 5 Working with Arrays 113


Arrays Revisited 113
Creating Arrays and Adding Data 114
Accessing Elements in Arrays 117
Deleting Elements and Entire Arrays 119
Counting Elements in an Array 120
Iterating Over Elements in an Array 120
foreach Loops 120
Regular Loops 121
Internal Loop Counters and each, next, prev, pos, and reset 122
The array_walk Method 124
Multi-Dimensional Arrays 125
Operations on Arrays 127
Sorting Arrays 127
Other Array Operations 130
Summary 132

Chapter 6 Strings and Characters of the World 133


Strings and PHP 133
How PHP Interprets Strings 134
Character Sets and Unicode 134
ASCII 134
The ISO 8859 Character Sets 134
Far Eastern Character Sets 135
Contents
viii

Unicode 135
Unicode Encodings 136
Making Sense of It All in PHP 136
Working with Other Character Sets 136
Trouble Rears Its Ugly Head 138
How We Will Work with Characters 139
Configuring PHP for Unicode 140
Installation and Configuration of mbstring and mbregex 140
Function Overloading 141
Operating on Strings 141
Getting Information 141
Cleaning Up Strings 143
Searching and Comparing 144
Extraction 148
Case Manipulation 149
Character Encoding Conversions 150
Summary 150

Chapter 7 Interacting with the Server: Forms 151


An Example of Forms 151
Working with HTML Forms 154
Adding a Form to Your Page 154
How Data Is Submitted 157
Accessing the Form Data Within Script 159
Character Sets and Forms 161
Working with the Server 162
Server Considerations 162
Server Variables 162
Environment Variables 167
Redirecting the User 168
Summary 170

■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■

PART II Database Basics


■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■

Chapter 8 Introduction to Databases 173


What Are We Talking About? 173
The Basics 174
Relational Databases 175
Motivations for Using a DBMS 175
The Case Against Simple Files or Spreadsheets 176
Database Servers 176
Major Database Servers 177
MySQL 177
PostgreSQL 178
Oracle Database 178
Contents
ix

Microsoft SQL Server 178


Other Servers 178
How to Select a Database Server 179
Thinking About Your Data 179
Capabilities 179
Performance 179
Accessibility from Within PHP 180
Cost 180
Our Choice 180
Common Interfaces 181
Summary 181

Chapter 9 Designing and Creating Your Database 183


What to Put into the Database 183
Organizing Your Data 185
Primary Keys 185
Choosing Data Types 186
Organizing Your Data into Tables 189
Indexes for Faster Searching 191
An Introduction to SQL 192
Creating Databases 193
Talking to the Database Server 193
Connecting and Authenticating 194
Creating the Database 194
Setting User Permissions 196
Preparing to Create Users 197
Creating a User 198
Deleting Users or Removing Privileges 199
Creating Tables 199
SQL Data Types 199
The Database Server Client Lifecycle 203
Creating the Table 204
Table Storage Engines 206
Creating Indexes 207
Foreign Keys and Cascading Deletes 207
Deleting Tables and Databases 209
Summary 210

Chapter 10 Using Databases: Storing and Retrieving Data 211


Before We Begin 211
Inserting Data into Our Tables 212
The INSERT INTO Statement 212
Bulk Data Insertion 213
Data Type Entry 215
Contents
x

Retrieving Data from Tables 216


Basic Syntax 217
Combining Table Data Upon Retrieval 220
Sorting Retrieved Data 223
Fetching a Few Rows at a Time 224
Modifying Data in Your Tables 225
Deleting Data from Tables 226
Summary 227

Chapter 11 Using Databases: Advanced Data Access 229


Transactions 229
The Problem 230
The Solution 231
Writing Transactions 232
A More Complicated Problem 232
More Advanced Queries 235
Combining Expressions 235
Specifying Sets and Ranges of Values 236
Fetching Unique Values 237
SQL Functions in Queries 238
Grouping Aggregate Function Data 243
Modifying Table Schemas 244
Summary 245

Chapter 12 PHP and Data Access 247


Getting Ready 247
Connecting and Authenticating 249
Sequence of Events 249
Making the Connection 250
Setting the Connection Character Set 252
Executing Queries 252
Retrieving Data 252
Validating User Input 255
Inserting, Deleting, and Updating Data 257
Transactions 259
Errors from mysqli 260
Queries a Go-Go 262
Bound Parameters 263
Bound Results 264
Old-School Interfaces 265
The Basics of Procedural Database Interfaces 265
Persistent Connections 268
Summary 268
Contents
xi

■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■

PART III Planning Web Applications


■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■

Chapter 13 Web Applications and the Internet 273


A Closer Look at the World Wide Web 273
The Internet: It’s Less Complicated Than You Think 274
Computers Talking to Computers 274
The Hypertext Transfer Protocol 276
MIME Types 279
Secure Sockets Layer (SSL) 279
Other Important Protocols 282
Designing Web Applications 282
Terminology 282
Basic Layout 283
User Interface 284
Business Logic 285
Back End/Server 289
n-Tier Architectures 289
Performance and Stability 290
Summary 291

Chapter 14 Implementing a User Interface 293


User Interface Considerations 293
Understanding Your User Interface 294
Planning a User Interface 295
Helping Users in Trouble 298
Design Tips and Strategies 299
Implementing Your User Interface 299
Cascading Style Sheets (CSS) 300
Including Files 302
Code Libraries for User Interface Generation 305
Implementing a User Interface Driver 309
Summary 310

Chapter 15 User Management 313


How Users Connect to Our Application 313
Visitors Versus Known Users 316
Validating Users 317
Partial Versus Full Logins 317
Where to Store User Information 318
What to Store and What Not to Store 318
Summary 320
Contents
xii

Chapter 16 Securing Your Web Applications: 321


Planning and Code Security
Strategies for Dealing with Security 321
The Most Important Thing 322
Balancing Security and Usability 322
After Development Finishes 323
Our Basic Approach 323
Identifying the Threats 323
The Threats 323
The Forces of Evil 326
Securing Your Code 327
A Golden Rule 327
Filtering Input 327
Code Organization 334
What Goes in Your Code 334
File System Considerations 335
Code Stability and Bugs 336
Execution Quotes and Exec 336
Summary 337

Chapter 17 Securing Your Web Applications: 339


Software and Hardware Security
Securing Your Web Server and PHP 339
Keep the Software Up-to-Date 340
php.ini 341
Web Server Configuration 341
Virtual Servers 342
Commercially Hosted Web Applications 344
Secure Sockets Layer (SSL) 345
Using SSL in PHP 345
Database Security 346
Users and the Permissions System 346
Sending Data to the Server 347
Connecting to the Server 347
Running the Server 348
Protecting the Network 348
Firewalls 348
DMZs 349
Educate Yourself About Network DoS and DDoS Attacks 349
Computer and Operating System Security 350
Keep the Operating System Up-to-Date 350
Run Only What Is Necessary 350
Physically Secure the Server 350
Disaster Planning 351
Summary 351
Contents
xiii

■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■

PART IV Implementing Your Web Application


■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■

Chapter 18 Error Handling and Debugging 355


How Errors Are Born 355
Errors from PHP 356
Bugs in Our Code 357
External Errors 358
How PHP Manages Errors 359
How PHP Displays Errors 359
Which Errors PHP Generates 360
Working with Errors 361
Configuring PHP Error Handling 367
Exceptions 367
Exception Basics 368
Working with Exceptions 370
Unhandled Exceptions 373
Extending Exceptions 374
Debugging 377
Instrumenting Your Code 377
Source Code Debuggers 379
Summary 380

Chapter 19 Cookies and Sessions 381


Cookies: Tasty and Useful 381
Basic Operation 382
How Cookies Work 385
Controlling Cookie Validity 386
Deleting Cookies 387
Cookie Arrays 387
What to Place into Cookies 388
Weight Watchers 388
Sessions 389
Basic Usage 390
Configuring PHP for Sessions 392
How the Session ID Is Transmitted 393
Storing Data with the Session 394
Page Caching 397
Destroying Sessions 399
How Session Storage Works 400
Session Security 405
Obtaining the Session ID 405
Limiting Damage from a Compromised Session ID 406
Summary 408
Contents
xiv

Chapter 20 User Authentication 409


Planning for Members 409
Web Server-Provided Authentication 412
Basic HTTP Authentication 412
Microsoft Windows Authentication Schemes 417
Implementing Our Own Authentication 419
Configuring the Database to Handle Logins 419
Adding New Users 420
Logging In Users 430
Updating Pages That Require a Logged In User 437
Logging Out Users 441
Deleting Users 443
Summary 444

Chapter 21 Advanced Output and Output Buffering 447


Globalization and Locales 447
Locales and Their Properties 448
Learning the User’s Locale 448
Setting the Locale of the Current Page (Unix) 450
Setting the Locale of the Current Page (Windows) 451
Learning About the Current Locale 453
Formatted Output 454
Formatting Numbers 455
Currencies 455
Other Formatting Functions 458
Output Buffering 461
How it Works 461
Using Output Buffering 462
Writing Your Own Handler 463
Summary 464

Chapter 22 Data Validation with Regular Expressions 467


Using Regular Expressions 467
What Are Regular Expressions? 468
Setup 468
Testing It 469
Basic Searches 470
Character Classes 471
Boundaries 472
The Dot 473
Repeating Patterns 474
Grouping and Choice 475
Tricks and Traps 475
Contents
xv

Data Validation with Regular Expressions 476


Validating Usernames 476
Matching Phone Numbers 477
Matching Postal Codes 477
Matching E-Mail Addresses 478
Other Regular Expression Functions 479
ereg_replace 479
Split 481
Summary 482

Chapter 23 XML and XHTML 483


XML 483
What Is XML? 484
Why Use XML? 485
Basic Terminology 486
The Structure of XML Documents 486
Namespaces 491
Validating XML 493
Related Technologies 495
Working with XML in PHP 496
Using SAX or DOM 497
Using the DOM 497
XHTML 510
Why XHTML? 511
How to Work with XHTML 511
Converting to XHTML 513
Summary 514

Chapter 24 Files and Directories 515


Accessing Files 515
Opening Files 515
Closing Files 518
Reading Files 518
Writing to Files 521
File Permissions and Other Information 523
Deleting and Renaming Files 525
Accessing Directories 525
Path Manipulation 526
Using Classes to Browse Directory Contents 527
Using Functions to Browse Directory Contents 528
Changing the Current Directory 528
Creating and Removing Directories 528
Security Considerations 529
File Access Considerations 529
Summary 531
Contents
xvi

Chapter 25 File Uploading 533


Uploading User Files 533
How File Uploading Works 534
Configuring PHP for Uploading 534
The Client Form 535
The Server Code 537
Limiting Uploaded File Size 540
Handling Multiple Files 541
A File-Uploading Example 543
Setting Up 543
The New Account Form 544
Creating the New Account 544
Viewing the User Data 548
Fetching the Image from the Database 550
Security Considerations 552
Trusted Users Only 552
Denial of Service 552
File Validation 552
Malicious Filenames 553
Summary 553

Chapter 26 Working with Dates and Times 555


Sources of Dates and Times 555
PHP 556
The Operating System 556
The Database Server 556
Web Pages and Users 557
Dates and Times in PHP 558
Timestamps in PHP 558
Getting the Date and Time 559
Validating Date and Time 563
Comparing Dates and Times 564
Outputting Formatted Dates and Times 567
A Problem with Timestamps 571
More Dates and Times in Database Servers 572
Date and Time Ranges in Common Database Servers 572
Adding or Subtracting Intervals 572
Parsing Dates in the Database 573
MySQL and Timestamps 573
Summary 574
Contents
xvii

Chapter 27 XML Web Services and SOAP 575


XML Web Services 575
Setting the Stage 576
Enter XML Web Services 576
Finding Web Services 577
How Web Services Work 578
SOAP 578
WSDL 579
HTTP 586
XML-RPC 587
Using Web Services in PHP 587
Selecting a Web Service 587
Configuring PHP 589
Working with the Service 589
Sample: Working with the Google APIs 594
Setting Up to Use the Google APIs 594
Learning More About the Service 594
How the Search Works 596
Searching for Keywords 597
Summary 602

Chapter 28 Using PEAR 603


Introduction to PEAR 603
Library of Code 604
PEAR Foundation Classes 604
Support Community 604
PECL 604
Installation and Configuration 604
Unix Users 605
Windows Users 605
Basic Commands 607
Getting Help 607
Listing Packages 608
Downloading and Installing Packages 609
Getting Information 610
Upgrading Existing Packages 611
Uninstalling Packages 612
Configuration Options for PEAR 612
Example: Using the Date Class 613
Installation 613
Basic Use 613
Further Examples 614
Summary 616
Contents
xviii

Chapter 29 Development and Deployment 617


Coding Standards 617
Worrying About Style 617
Developing a Coding Standards Document 619
Holy Wars 622
Other Considerations 623
Source Code Control 624
What’s My Motivation? 624
How They Work 624
Choosing a Source Code Control System 628
Working with Source Code Control 629
Testing 631
Why Bother to Test? 631
Unit Testing 632
Performance and Load Testing 635
Pest Control 637
Deployment 638
Test Servers 638
Scripting and Automating the Process 639
Deploying to the Live Server 639
Summary 640

■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■

PART V Sample Projects and Further Ideas


■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■

Chapter 30 Strategies for Successful Web Applications 643


Singleton Objects 643
Session Management 646
Configuration 646
Security 647
Putting It All Together 648
A Holistic Approach to Error Handling 650
User Versus Application Errors 650
Replacing the Default Handlers 653
Displaying Errors to Users 657
Creating New Exception Classes 659
Database Connection Management 660
A Better Approach 662
The Best Approach 664
A New and Improved String Escaping Function 666
PHP Configuration Settings 667
General Settings 667
Multiple-Byte String Settings 667
Error Settings 668
Database Settings 668
Summary 668
Contents
xix

Chapter 31 An Appointment Manager 671


Overview 671
Installing and Running the Sample 673
Structure and Page Progression 673
Page Structure 674
Database Layout 676
UI Strategy 678
Complete File Listing 680
Code Walkthrough 681
The AppointmentManager Class 682
Handling Dates and Times 687
Processing Forms and Page Progression 690
Showing a Week and a Month 697
Suggestions/Exercises 701
Change the Daily and Weekly Views 702
Monday–Sunday Weeks 702
Delete or Move Appointments 702
Convert to PEAR Date Class 703
Allow Overlapping Appointments 703
Make System Multiuser 703
Summary 703

Chapter 32 A Blogging Engine 705


Overview 705
Installing and Running the Sample 707
Structure and Page Progression 708
Page Layout 708
Database Structure and Notes 710
UI Strategy 712
Complete File Listing 713
Code Walkthrough 715
User Interface Generation 715
User Management 719
Tracking Logged In Users 726
Managing Entries and Comments 732
Suggestions/Exercises 741
Improve User Listing on Home Page 741
Allow Anonymous Comments 741
Hierarchical Comments 741
Have User Creation Use Transactions 742
Implement a New strip_tags Function 742
Summary 743
Contents
xx

Chapter 33 An Ecommerce Application 745


Overview 745
Installing and Running the Sample 747
Structure and Page Progression 748
Core Structure of the Sample 749
Page Layout
750
Database Structure 752
UI Strategy 756
Complete File Listing 758
Code Walkthrough 760
Browsing Products 760
Implementing the Shopping Cart 763
Progressing Through Checkout 767
Submitting Orders 778
Security 786
Payment Processing 786
Suggestions/Exercises 786
Skip Shipping Info 787
Post Order Processing 787
Admin Pages 787
Order Status/Cancel Order 787
Summary 787

■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■

PART VI Appendixes
■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■

Appendix A Installation/Configuration 791


Installation 791
Web Server 791
Database Server 797
PHP 803
Configuration 812
Web Server 812
Database Server 813
PHP 814
Summary 815

Appendix B Database Function Equivalents 817


Working with Databases 817
Listing Available Databases 817
Listing Tables in a Database 818
Describing a Table 818
Data Description and Creation 818
Creating Databases to Work with UTF-8 818
Setting the Connection to UTF-8 819
Contents
xxi

Auto-Incrementing Fields 819


Date/Time Column Types 819
Binary Column Types 820
Large Text Column Types 820
Bulk Data Insertion 820
Other Functions and Interesting Notes 821
Substring Extraction 821
String Concatenation 821
NOW 821
Date Functions 821
Formatting of Date/Time Output 822
The LIMIT Clause 822
Summary 822

Appendix C Recommended Reading 823

Index 825
This page intentionally left blank
Introduction

T his is the book I wish I had a couple years ago when I sat down and decided to
learn something about web applications. The transition from programming standard
window-system GUI applications to writing dynamic web applications was surprisingly
complicated. Extremely productive languages, such as Personal Home Page (PHP), make
the transition easier, but the learning curve remains steep.
With that in mind, I sat down to write this book and explain how to use the various tech-
nologies that go into writing web applications. I have made every mistake possible while
learning about PHP and databases, and have therefore tried to incorporate as much of
what I learned into this book. Far too many books published these days are merely a
reprint of existing documentation or Unix man pages, and I truly wanted to see something
different in print.
The technologies, however, are only half the battle. Without strategies or systematic
approaches to design and implementation, applications are doomed to an expensive
and messy existence at best—or failure at worst. Therefore, this book focuses on a lot of
things you might not see covered to the same extent in other books—design, testing, and
security.

Target Audience
This book is targeted at people who need or want to write a web application. You might
be a corporate developer looking to build an intranet application for your company or an

xxiii
Core Web Application Development with PHP and MySQL
xxiv

Internet web application for customers. You might be a consultant helping a small busi-
ness develop a web store, or just a hobbyist looking to learn more about web applications
and write one of your own.
The assumption is that you have at least a passing familiarity with programming,
although this book by no means expects you to be an expert. An understanding of basic
programming constructs, such as variables and functions, and a basic understanding of
HTML should be more than sufficient.
Because I knew next to nothing about databases when I started learning about web appli-
cation programming, I likewise expect no more of the reader. This book covers databases
from basic terminology and design to basic and advanced queries, with an appropriate
balance between clear-and-simple instruction and interesting examples to help you in
your development.

About PHP
PHP began in 1994 as a series of scripts called PHP/FI (Personal Home Page/Forms
Interpreter), and it was written by a fellow named Rasmus Lerdorf to help him manage
documents on his web site. Over the years, PHP grew into something more serious. In
1997, a second version of the system came out with additional functionality.
In late 1998, PHP 3.0 was released, leading to a major rewrite of the code and the involve-
ment of two new developers—Zeev Suraski and Andi Gutmans. The goal was to support
progressively broader and more complex applications on the web. In early 2000, version
4.0 was released. Based on a new language engine called the Zend Engine, this version
had much better performance and increased code modularity. By late 2004, the much-
evolved version 5.0 was released. It included many new features, such as new language
constructs, broader web server support, sessions, and additional third-party extensions.
Among the new language features was a significantly improved and expanded object-
oriented programming model, which this book uses extensively. Somewhere along the
way, PHP ceased to refer to “Personal Home Page” and came to mean “PHP Hypertext
Preprocessor,” a so-called recursive acronym. (The acronym actually forms part of the
term it defines!)
PHP is a remarkably productive language—you can sit down and crank out (yes, that’s
the technical term) large amounts of code in a short period of time, and this productivity
is what drew me to it some years back. With PHP, I was able to put together surprisingly
robust and dynamic travelogues of my journeys to various countries with relatively little
code.
The one possible “fly in the ointment” is that the language can be quirky compared to
other programming languages—especially if you, like me, come from a background of
languages more similar to C/C++, Java, or Visual BASIC. In fact, many of the things cov-
ered in this book are the result of my sitting around and scratching my head for a couple
of hours. However, after you become comfortable with it, the language proves fun to
write and is surprisingly powerful.

Layout
This book is divided into six parts, which represents the logical progression of writing
web applications.
Part I, “The Basics of PHP,” covers the PHP language itself, starting with descriptions
and discussions of the most basic types of language. Part I then moves on to functions,
Introduction • Acknowledgments
xv

code structure, and object-oriented programming—before finishing off with a discussion


of arrays and strings.
Part II, “Database Basics,” covers databases, starting with terminology and progressing
through design and data definition. Part II finishes by describing the use of databases and
tables, ranging from the most basic queries to transactions and functions.
Part III, “Planning Web Applications,” takes a step back from coding to discuss the
design of your web applications. Many people get so involved in writing their code that
they forget to sit down and actually think about it in advance. These chapters (hopefully)
give you something to think about as you begin. This part also focuses heavily on secur-
ing your applications, as it is not something to be taken lightly.
Part IV, “Implementing Your Web Application,” discusses the more advanced language
features and concepts required to move beyond simple PHP and databases into writing
web applications, covering topics such as errors, sessions, and XML—including plenty of
sample code.
Part V, “Sample Projects and Further Ideas,” presents three full web application samples
that start with a simple appointment management system, progress through a web log
system, and finish with an ecommerce store. These samples incorporate much of what the
book has covered and are designed to be robust. Instead of killing large numbers of trees
and listing all the code for the samples, you can download and run them. The book
shows you only the most salient sections of the code and leaves you to download and run
them in completion.
Part VI, “Appendixes,” discusses the installation of the necessary software to run your
web applications and how to perform various database actions on different database
engines, and suggests some additional reading material.

Before You Begin


Before you begin reading the meat of this book, please take a moment to open the CD
that accompanies this book and copy the source code to your computer. The phpwasrc/
directory contains the initial files you need.
In addition to the full source code (and installation instructions) for the three large sam-
ples from Part V of the book, there are also small snippets of code to accompany many of
the chapters in the book. You can run these, debug them, or change and play with them
to further help you learn how the language works.
Beyond the sample sources, the CD contains versions of PHP, the Apache HTTP Server,
and MySQL that you can use to install the software on your local machine. Instructions
are included on the CD.

Acknowledgments
I would like to thank the Academy for all the wonderful…gosh…I mean…what a rush!
Oh wait, wrong speech.
In all seriousness, no book can be written without a lot of help, and this is no exception.
Prentice Hall and my editor Mark Taub both deserve a huge amount of thanks for help-
ing me realize a dream and working with me on this book. The freedom and opportunity
to write the book I wanted to write were never threatened, and they have been amazing
at answering questions as I sent them.
Core Web Application Development with PHP and MySQL
xxvi

The technical review team of Kristine Kuch, Matthew Leingang, and Kimberly Jenson are
owed a huge debt of thanks. Never afraid to call me on stupid mistakes or bad writing or
short with praise and compliments, these people have taught me tons and have helped
me grow as both a web applications programmer and author over the past six months.
Finally, none of this would be possible without the support of my wife Samantha, who
encouraged me repeatedly to do more writing in the first place and lovingly nudged me
on those evenings when I swore I would never look at another computer again and was
sick of typing.

In Closing
I hope that you enjoy reading this book. I certainly hope that it helps you in your web
application programming endeavours and also provides at least some reading enjoyment.
I am a terribly chatty person, and always love to hear from people; therefore, if you have
any comments on the book or suggestions of things to add or treat differently, I’d be
delighted to hear from you at marcwan@chipmunkninja.com.
PART I
The Basics
of PHP
This page intentionally left blank
1
Getting Started
with PHP

B y now, you have managed to get PHP running on your server or workstation and
are ready to start writing scripts in PHP. If you have not, or you are still having problems,
please see Appendix A, “Installation/Configuration,” for more details. In this chapter, we
are going to write our first programs using Personal Home Page (PHP), and learn about the
basics of working with the language.
Over the course of this chapter we will
• Write a few basic PHP programs and learn how to enter and process PHP scripts
• See the basics of how the language is structured and how to comment your code
• Learn about some of the more common and basic data types in PHP
• Learn about some useful functions that we will use throughout this book

Your First PHP Programs


PHP is an interpreted scripting language, meaning that the language engine simply runs the
scripts you have written with no necessary intermediate steps to compile or convert them
into binary formats. Most of the scripts that will make up your web applications go in the
same place as your HTML content files. Files containing PHP script will typically have a
.php extension, although many people still use the older extensions—.php3 and .phtml.
Where you place these files will depend on how you have configured your web site and
what extension the web server will use to pass the file to the PHP interpreter. We will
refer to this location as the document root.

3
Core Web Application Development with PHP and MySQL
4

When the web server receives a request for an appropriately named file, it passes this to
the PHP engine, which then processes the file one line at a time. For lines that do not
contain PHP code (typically, lines containing HTML markup), the server emits them
untouched and executes any PHP script code as it is seen. With this in mind, we write
our first program, which is a mixture of PHP and HTML.
<html>
<head>
<title>My First PHP Program</title>
</head>
<body>

<?php
echo "Hello Everybody!";
?>
</body>
</html>

If we type this into a file called firstprogram.php and put it in our document root directory,
we can then type the URL for the path to this file (for example, http://localhost/
gettingstarted/firstprogram.php). We should then see something similar to Figure 1-1.

Figure 1-1: Your first PHP program in action.

If you have problems getting the script to run correctly, here are a few things you should
investigate:
• Make sure you entered the URL to the script file correctly, making sure that the server
name is valid.
Do not forget that the path gettingstarted is relative to the document root directory
for the web site. So, if our web site’s root directory were c:\inetpub\wwwroot or
/home/samplesite/www, then our directory in the preceding example would be
c:\inetpub\wwwroot\gettingstarted or /home/httpd/www/gettingstarted.
1 • Your First PHP Programs
5

• If you see just the code of your script printed onscreen, chances are that your web
server has not been configured to recognize .php files as needing to be sent to the PHP
interpreter.
• If you get an error saying that the host could not be found, then you should make sure
that the web server is actually running. See Appendix A for more information.
Most of the file is simply HTML text. As we have said, the PHP language engine outputs
any text it sees and looks for PHP code sections. In the preceding file, the PHP code is
demarcated by the tags
<?php
...
?>

When the PHP language engine sees these two tags, it processes the script and takes any
appropriate actions. When the script portion ends, it resumes output of HTML.
To learn more about our PHP installation, we will write a small script in our next program
that uses a helpful little tool. This function, called phpinfo, is used as follows:
<?php
phpinfo();
?>

This script produces output similar to that seen in Figure 1-2. (We did not have to use
HTML headers or markup since the phpinfo function emits these for us.)

Figure 1-2: Learning about our PHP interpreter with the phpinfo() function.
Core Web Application Development with PHP and MySQL
6

Entering PHP Scripts


Before we delve too deeply in to the PHP language, we will look at how to enter scripts
and how code interacts with HTML markup.

Marking Sections of PHP Code


There are a few ways to indicate that a section of the input file contains PHP script. The
most common way is as follows:
<?php
echo "Hello Everybody!";
?>

This method is safe for both XHTML and XML files; therefore, it is the method we will use
throughout this book.
Another way to demarcate PHP script is as follows:
<?
echo "Bonjour tout le monde!";
?>

This is called using short tags. Short tags are available only if the short_open_tag setting
is enabled in your php.ini configuration file (see Appendix A). The use of this style is gen-
erally discouraged, as it does not save you much in typing and can create problems as you
move your code from server to server, where one of them might not have short tags
enabled.
A third way of entering script is
<script language="php">
echo "Ciao a tutti!";
</script>

This method does not buy us very much and is generally used much less than the first
style.
One final style of inputting script exists to support some older graphical HTML editing
programs that are unable to understand script directives very well and would move script
around when they generated HTML for user input. However, some of these editors could
support tags by marking code as ASP script. To let users continue to use these editors, you
can mark PHP script using these ASP tags:
<%
echo "Guten Tag alle!";
%>

ASP tags can only be used if the asp_tags setting is enabled in the php.ini configuration
file.
Even though we will use the first style of tags, we have shown you all the possible types
to prepare you for other codes you may encounter.

Mixing PHP and HTML


There is nothing that requires large blocks of PHP code when writing HTML and PHP:
You are completely free to mix the markup and script as much as you wish. For example,
1 • Entering PHP Scripts
7

you might want to personalize a greeting message ($userName is a variable, which we will
introduce more formally soon):
<?php
$userName = "Chippy the Chipmunk";
?>

<p align='left'>
Hello there, <b><?php echo $userName; ?></b>
</p>

A shortcut exists for this particular usage. It involves the short tags discussed in the previ-
ous section along with an equals sign (=):
<?= $userName ?>
This is the same as typing
<?php echo expression; ?>

This can be a handy way to save a bit of typing when you are injecting several expressions
into your HTML. However, we will continue to avoid using short tags and stick with the
normal syntax.
The flexibility available when mixing PHP and HTML allows us to be creative when we
get into more advanced language constructs. (These concepts will be introduced in
Chapter 2, “The PHP Language.”)
<?php

if ($file_received_successfully === TRUE)


{
?>
<p align='center'> Thank for your contribution </p>
<?php
}
else
{
?>
<p align='left'>
<font color='red'>
<b>Error: The file was not correctly received.</b>
</font>
</p>
<?php
}

?>

This, like some other things we will encounter as we learn about web application pro-
gramming with PHP—while perfectly valid in PHP—is probably something we should
Core Web Application Development with PHP and MySQL
8

use sparingly. We should write code that is legible and easily maintainable whenever
possible.

Statements and Comments


Statements in PHP are separated by a semicolon (;). Statements can be grouped together
by wrapping them in brackets ({}), which is sometimes called a block of code. Any num-
ber of statements can be placed on one line. Individual items (or tokens) within a state-
ment can be separated by arbitrary amounts of whitespace (space, newline characters, or
tabs). Statements can even span more than one line.
<?php

$x = 123; $y = 456; $z = "hello there"; $a = "moo";

{
echo "This is a group of statements";
$m = "oink";
}

$userName
=
"Chippy the Chipmunk"

;
?>

Just because one can do this, however, does not mean it is recommended. Programmers
are always encouraged to make their code legible.
The end of a section of PHP script is also a valid way to terminate a statement:
<?php echo "Semi-colon not necessary here!" ?>

There are three basic styles for entering comments in PHP:


<?php
/*
* This is our first style of comment.
*/
echo "Style 1";

//
// This is our second style of comment. It is "single line"
//
echo "Style 2";

#
# This third style is also "single line."
1 • How to Store Data
9

#
echo "Style 3";
?>

The first two styles are very common in higher-level programming languages, such as
C/C++, Java, and C#, while the latter style will be familiar to programmers of Perl and
shell scripts.
The first style of comments beginning with “/*” causes the PHP processor to ignore all
text until it sees a closing “*/” sequence. This can cause problems if you try to nest
comments.
<?php
/*
/**
* this is a comment.
*/
echo "This is some code";
*/
?>

Because of the nested comment, the processor stops treating the code as comment text at
the first “*/” token and reports and error at the second, because it no longer believes itself
to be processing comments.
The two types of single-line comments cause the PHP language processor to ignore all
code until the end of the current line or current PHP script section.
<?php
// all of this line is ignored.
echo "But this line prints just fine.";
?>

<?php #Comment!! ?><b>This prints</b><?php echo "this prints" ?>

How to Store Data


At some point, you will want to hold on to and manipulate data of varying sorts. This is
done in PHP by using variables. Variables are a place to store data for later use. They are
valid for the duration of the currently executing script.
PHP is different from many other languages, in that variables do not need to be declared
before they are used—to declare one, you simply assign it a value. Variable names in PHP
are represented by a dollar sign ($) followed by an identifier that begins with either a let-
ter or underscore, which in turn can be followed by any number of underscores, numbers,
or letters. Included in the set of letters permitted for variable names are some extended
characters, such as accented Latin letters. Other extended characters, however, such as
many Chinese characters seen in Japanese and Chinese alphabets, are not permitted.
<?php
$varname = "moo"; // ok
$var______Name = "oink"; // ok
$__12345var = 12345; // ok
Core Web Application Development with PHP and MySQL
10

$12345__var = 12345; // NOT ok - starts w/ number


$école = "Rue St. Jacques"; // ok - é is an extended char
$ = "car"; // NOT ok - has invalid chars
?>

In versions of PHP prior to version 4, variables would be declared at their first use instead
of their first assignment, which often proved tricky when debugging code.
<?php

$cieling = "roof"; // whoops misspelled it!

echo "$ceiling"; // prints an empty string.

?>

Fortunately, PHP 5 prints a warning saying that, for instance, "$ceiling” has not been
assigned a value.

Entering Basic Types in PHP


Many programmers with experience in other languages find working with types in PHP
a slightly different and occasionally quirky experience. PHP is a richly typed language,
where each piece of data has a type associated with it, but variables are not declared as
having a particular type—the language engine determines the type to use based on a set
of rules ( leading some people to call it dynamically typed instead). We will now introduce
the most basic types and discuss how they are used.

Numbers
There are two basic types of numbers in the language: integer (int ) and float (float).
While many languages distinguish between single and double-precision floating-point
numbers, PHP does not—they are all 64-bit floating-point numbers with approximately 14
digits of precision. PHP does, however, support the keyword double in addition to float
for compatibility.
Integers are specified in code in octal (base-8), decimal (base-10), or hexadecimal (base-16)
notations.
<?php

$abc = 123; // decimal


$def = -123;
$ghi = 0173; // octal, value is 123 in decimal
$jkl = -0173; // octal, value is -123 in decimal
$mno = 0x7b; // hexadecimal, 123
$pqr = -0x7B; // hexadecimal, -123

?>
1 • Entering Basic Types in PHP
11

Integer precision varies largely by the underlying operating system, but 32 bits is com-
mon. There are no unsigned integers in PHP, so the maximum value for an integer is
typically larger than 2 billion. However, unlike other languages that overflow large
positive integers into large negative integers, PHP actually overflows integers to floating-
point numbers.
<?php
$large = 2147483647;

var_dump($large);

$large = $large + 1;

var_dump($large)
?>

The output of this script is


int(2147483647) float(2147483648)

In the previous snippet of code, we introduce the var_dump function, a powerful debug-
ging tool used to see both the type and value of a variable in PHP. We will return to this
later in the chapter in the section titled “Some Very Useful Functions.”
Even though we will discuss arithmetic operators such as addition, multiplication, and
subtraction in Chapter 2, in the section titled “Expressions and Operators,” we will take
time now to note that there is no integer division in PHP. Unlike some other languages,
for which the expression
5 / 2

would yield an integer result with the value 2, PHP would return the value 2.5, typed as
float. If you want the integer value result of a division operation, you need to cast the
value to an integer (see the section “Type Conversions” in Chapter 2) or use the round
function, which you can learn about via the PHP Online Manual.
Floating-point variables can be input in a few different ways:
<?php
$floatvar1 = 7.555;
$floatvar2 = 6.43e2; // same as 643.0
$floatvar3 = 1.3e+4; // same as 13000.0;
$floatvar4 = 5.555e-4; // same as 0.0005555;
$floatvar5 = 1000000000000; // too big for int ==> float
?>

One caution with floating-point numbers: Remember that they are only approximate val-
ues. Because of their limited precision, they are very close to the intended value but are
not always the value you would like.
Core Web Application Development with PHP and MySQL
12

For example, the value 2.5 will often be represented internally as 2.4999999999, or some-
thing similar. Thus, the following code will often prove problematic:
<?php

if (0.7 + 0.1 >= 0.8)


echo "Hoooray!";
else
echo "What???";

?>

Code snippets such as these often print "What???", depending on the exact implementa-
tion of floating-point numbers.
The recommendation is to avoid comparing specific floating-point values. Instead, you
should round them to the nearest integer value using round, or compare them against the
ranges of values.

Strings
A string is a sequence of characters. In PHP, these characters are 8-bit values. This is con-
venient for many Western languages but proves a bit problematic when trying to work
with systems using more complicated alphabets, such as Chinese. We will cover solutions
for this in more detail in Chapter 6, “Strings and Characters of the World.”
There are three ways to specify a string value.
Single Quoted
Single-quoted strings are sequences of characters that begin and end with a single quote (').
<?php echo 'This is a single-quoted string.'; ?>

To include a single quote within a string, you simply put a backslash in front of it. This is
called escaping the character.
<?php echo 'This is a single-quoted (\') string.'; ?>

If you actually want to print \' as output or if you want to end a string with a backslash
character, then you need to escape the backslash one more time.
<?php

echo 'This is a single-quoted string.';


echo '<br/>';
echo 'This is how to print a single quote: \' in a string.';
echo '<br/>';
echo 'And now to show a backslash in the output: [ \\\' ]';
echo '<br/>';
echo '\And now to terminate a string with a backslash\\';
echo '<br/>';

?>
1 • Entering Basic Types in PHP
13

The previous script produces the following output:


This is a single-quoted string.
This is how to print a single quote: ' in a string.
And now to show a backslash in the output: [ \' ]
\And now to terminate a string with a backslash\

No other escaping or expansion is supported. Therefore, in the previous code, \A just


prints out the two characters.
Double Quoted
Double-quoted strings are similar to single-quoted strings, except that the PHP language
processor actually dissects them to find and replace special escape sequences and
variables.
<?php echo "This is a double-quoted string."; ?>
In addition to the escape sequence \" required to insert a double quote within a double-
quoted string, PHP understands the following escape sequences:

Escape Output
\n Linefeed character (0x0a/10 in ASCII)
\r Carriage return character (0x0d/13 in ASCII)
\t Tab character
\\ Backslash
\$ Dollar sign character
\0octal-number A character identified by its value in the range 0–255,
specified in octal notation.
\xhexadecimal-number A character identified by its value on the range 0–255,
specified in hexadecimal notation.

No other escape sequences are supported, and (in the case of single-quoted strings) non-
matching sequences will simply print the backslash and the other character.
<?php
echo "This is a rich \"\$\$\" double-quoted string.";
echo "<br/>\n";
echo "This is a rich \042\x24\x24\042 double-quoted string.";
echo "<br/>\n";
echo "This won't quite do what \n\n you expect it to!";
echo "<br/>\n";
echo "Neither likely
will
this.";
echo "<br/>\n";
echo "\\ + A isn't a valid escape, so this will print \A";
?>
Exploring the Variety of Random
Documents with Different Content
“But ladies are more apt to be at home early in the morning,” urged
Molly, who was anxious to have the adventure begin. “Besides, it’s
getting hot, and we’re all thirsty. What are you going to do about a
reference? I’ve heard Grandma say she would never engage a girl
who didn’t have a good reference.”
Dulcie looked a little startled. She had not thought of the necessity of
references. But just then Maud put in an anxious question.
“Suppose nobody wants us, and night comes, where are we going to
sleep?”
“Don’t talk about night when it’s only just about breakfast time,”
reproved Molly. “We’ll be sure to find a place long before dinner-time,
and I don’t believe, when the people know who we are, they’ll make
us eat in the kitchen. I think we shall be kind of lady helps, like
Phœbe in ‘Eight Cousins.’ Phœbe did the cooking, but she had
lovely times, too, don’t you remember?”
“But Dulcie says we mustn’t let people know our real names,” Maud
reminded her, “so I don’t see how they can find out who we are.”
“Well, it’s going to be fun, anyhow,” maintained Molly, cheerfully. “I
wouldn’t go home again for anything, after coming so far, and
spending all that money, would you, Dulcie?”
“Of course not,” said Dulcie, “and I suppose, after all, we might as
well begin with this house as any other. But you mustn’t be
disappointed if we have to try a good many places before we find
any one who wants us. And—and there’s another thing; I don’t
believe we’d better all go in together. They might get discouraged if
they saw there were so many of us.”
“But they’ll have to know as soon as they engage us,” objected
Daisy.
“Of course they will, but they needn’t find out the very first minute. I
think the best way will be for you and me to go first, and then, if the
people seem kind, and want us to stay, we can explain about the
others. Molly and Maud can wait for us right here, under that big
tree. We won’t be gone long.”
Daisy still looked very doubtful, and Maud began to object to being
left behind, but Dulcie was firm, and Molly also proved equal to the
occasion. So the question was settled, and the two younger children
comfortably ensconced under a big apple-tree, while Dulcie and
Daisy walked up the wide gravelled path to the house. It was not a
large house, but a very pretty one. There was a lawn, with flower
beds in front, and the children caught glimpses of a stable and other
outbuildings in the rear. There was no one to be seen, but as they
approached the house, the sound of a piano could be distinctly
heard.
“Somebody’s practising exercises,” whispered Dulcie. “Perhaps it’s
the lady of the house.”
“There’s a doll’s carriage on the piazza,” said Daisy, “so there must
be a little girl.”
“I’m glad,” said Dulcie, with a great effort to speak cheerfully. “If the
people have a little girl of their own, it may make them kinder to other
little girls. I’ve been thinking about our names. I don’t want to change
them any more than I can help; it doesn’t seem quite honest. I don’t
see how I can very well change Dulcie into anything but Delia, but
you can be Margaret, which is your real name, anyhow, and Molly
can be Mary. I’ll have to decide about Maud later, but I think our last
name had better be Smith. When people in books change their
names, they nearly always call themselves Smith or Brown.”
Daisy opened her lips to protest, but at that moment the sound of the
piano ceased, and in another moment the front door opened, and a
very pretty little girl of eight or nine came out onto the piazza. She
was so pretty that Dulcie and Daisy stopped short in the path, and
stood gazing at her in undisguised admiration. She had big brown
eyes, and long golden curls, and she was dressed in white, and wore
a string of gold beads round her neck. Altogether, she looked so
much like the picture of a little princess in one of their fairy books
that Dulcie and Daisy fairly gasped.
As for the stranger herself, she did not seem in the least surprised,
but smiled a bright, welcoming smile, and came running down the
steps to greet the visitors.
“Oh, I’m so glad you’ve come,” she cried, joyfully. “Mamma said she
thought you might come to-day, but I didn’t expect you quite so early.
It’s all right, though; I’ve finished my practicing. I did a whole half-
hour since breakfast. Mamma says that’s quite enough in summer.
Won’t you come up on the piazza?”
To say that the two little Winslows were surprised at the cordiality of
this greeting would be but a poor way of expressing their feelings.
Indeed, they were so much astonished as to be, for the first moment,
quite deprived of the power of speech. Then Dulcie found her voice,
and managed to gasp out:
“You—you were expecting us!”
“I wasn’t exactly expecting you,” the stranger explained, “because
your mother didn’t positively tell Mamma you would come to-day, but
I hoped you would, because I don’t know any of the children here
yet, and I’m so anxious to have somebody to play with.”
“I think you must be making a mistake about us,” said Daisy, who
was beginning to grasp the situation. “Who do you think we are?”
“Why, aren’t you the two little Baxter girls? Mrs. Baxter came to call
on Mamma yesterday, and she said she would send her two little
girls over to play with me, so when I saw you, of course I thought I
knew who you were. It doesn’t really make any difference, though,
for I’ve never seen the Baxters, and I shall probably like you just as
much. You see, Papa has only taken this house for the summer, and
we didn’t come till last Monday, so I don’t know any of the children
who live here. What are your names, and which house do you live
in?”
Daisy was silent, and Dulcie flushed a little as she answered.
“Our name is Smith. I’m Delia Smith, and this is my sister Margaret.
We don’t live here, and we—we didn’t exactly come to see you. We’d
like to speak to your mother.”
The little girl’s face fell.
“I’m very sorry,” she said, “I hoped you had come to play with me.
Mamma has gone to the station with Papa, but she won’t be gone
very long. I hope you can wait.”
“We can wait,” said Dulcie. She had taken a fancy to the pretty little
girl, and was hoping that her mother might prove as friendly as
herself.
The child looked pleased.
“All right,” she said, hospitably, “and while you’re waiting, perhaps
you’d like to come and see the rabbits. They’re very cunning, and it’s
about time I gave them their breakfast.”
The prospect of feeding rabbits was very alluring, but Dulcie was
mindful of the importance of maintaining her dignity. People looking
for situations ought not to waste their time on anything so trivial as
rabbits.
“I think perhaps we’d better wait here,” she said. “Do you happen to
know whether your mother needs any help?”
“Help,” repeated the little girl, rather vaguely, “what kind of help?”
“Oh, help in the house, or—or in the garden. Any kind that little girls
could do. I thought she might want some one to wash the dishes, or
make the beds, or——”
“Oh, you mean a maid,” interrupted her new acquaintance, with
sudden comprehension. “No, I’m sure Mamma doesn’t need any
one. I heard her tell Papa all the servants were very satisfactory.
What made you want to know?”
“Because we—oh, it doesn’t matter. I’m afraid there isn’t any use of
our waiting to see your mother, after all.”
“Oh, please don’t go so soon,” pleaded the little girl, clasping her
hands imploringly. “You’ve only just come, and I do want somebody
to play with so much. Wait and see Mamma; you’ll love her, and
perhaps she knows some lady who wants a maid. I suppose your
mother wants to find a place for one, just as Mamma did when we
went to Europe last year. Don’t you really think you’d like to come
and see the rabbits?”
“I’m sorry, but I’m afraid we can’t,” interposed Daisy, firmly. “We’ve
left our—some people waiting for us on the road, and they might get
worried if we stay away too long.”
“It will only take a few minutes to see the rabbits,” their new friend
urged, “and Mamma will be back very soon. Do you think those
people would mind waiting just a little longer?”
Dulcie wavered. The little girl was so cordial; it seemed almost rude
to refuse her invitation. She glanced appealingly at Daisy.
“I think we might stay just a few minutes,” Daisy agreed. She loved
pets, and to possess rabbits had long been an unfulfilled dream.
So the question was settled, and five minutes later three very eager
little girls were bending lovingly over a family of soft, wriggling baby
rabbits.
“They’re the cunningest things I ever saw,” declared Daisy, pressing
one downy mite to her cheek. “I do wish Molly and Maud could see
them.”
“Who are Molly and Maud?” inquired her new friend, with interest.
Daisy started and flushed. In the interest of the moment she had
quite forgotten the rôle of Margaret Smith.
“They are our two sisters,” she explained, with an apologetic glance
at Dulcie. “We all love rabbits, but Grandma will never let us have
any pets.”
“You must bring them to see my rabbits,” her hostess said politely.
“I’ve got so many, I’d like to give you some, if your grandma would let
you have them.”
“You are very kind,” said Dulcie, “but I’m afraid we couldn’t take
them. You see, we don’t expect to live at home any longer.”
The brown eyes opened very wide, and their new acquaintance
inquired in a tone of the utmost astonishment:
“Where are you going to live, then?”
“We don’t know,” said Dulcie; “that’s what we wanted to speak to
your mother about. We are looking for a situation.”
Their new friend gasped.
“But you’re not grown up; you’re only little girls,” she faltered. “Little
girls only work if their mothers are very poor. You don’t look a bit like
poor people.”
“We’re not exactly poor,” Dulcie explained, “but there are—reasons
why we don’t want to live at home any more, so we’ve come away to
try to find a situation. We don’t mind working hard, and there are
really a good many things we can do. We’ve made our own beds
and dusted our rooms ever since Liz—I mean for quite a long time,
and we can wash dishes, and cook a little, too. If we could have a
cook-book, I think we would manage very well.”
The look in the little stranger’s eyes had changed from astonishment
to admiration.
“I think you are very clever,” she said. “I wish I could do useful things
like that, but I shouldn’t like to leave my home. I think I should die if I
had to go away from Mamma and Papa.”
“I’m sure you will never have to do it,” Dulcie reassured her. “You
see, it’s quite different with us. Our mamma is dead, and our papa—
oh, well, we’d rather not talk about it, but it’s all very sad, and we
don’t want to be burdens any longer. Let’s talk some more about the
rabbits.”
Their new friend nodded comprehendingly.
“I know how you feel,” she said. “I hate talking about sad things, too.
I don’t like sad stories, either. Once Mamma read me about little Paul
Dombey, and I cried so much I had a headache.”
“I wish we had a mamma,” said Daisy, with a sigh. “Children are
never burdens to their mothers. I think yours must be nice; you talk
so much about her.”
“She’s the loveliest lady in the world. She’s so good that everybody
loves her. Haven’t you ever heard about her?”
“No, I don’t think we have,” Daisy admitted reluctantly. “You see, we
don’t know very many people. What’s your mamma’s name?”
“Mrs. Richard B. Thorne, and I am Barbara Muriel Thorne.”
“Oh, what a beautiful name!” cried Dulcie. “I’ve read about Barbaras,
but I never met one before. I wish my name was Barbara, or else
Gladys. Muriel is quite a book name, too.”
“Yes, they are pretty names,” Barbara Muriel answered, with some
pride. “But Delia is rather a nice name, too,” she added, politely.
“I think it’s about the ugliest name I ever heard,” said Dulcie. “I can’t
think what made me choose it.”
Barbara looked rather puzzled.
“I didn’t know people ever chose their own names,” she said. “Are
you Baptists?”
“Oh, no,” said Dulcie, blushing; “we are Episcopalians. What made
you think we were Baptists?”
“Because Hannah said Baptists weren’t baptized till they were grown
up, and I thought perhaps they chose their own names, instead of
having them given to them, when they were babies.”
Dulcie was beginning to feel rather uncomfortable, but fortunately, at
that moment, Daisy came to her rescue.
“Hark!” she exclaimed, eagerly; “I think I hear a carriage. Perhaps it’s
Barbara’s mother.”
Barbara ran to look, and returned in a moment with the joyful
intelligence that it was Mamma coming home.
“She’s just driving round to the front door,” she said. “I’ll run ahead,
and tell her about you.” And away she flew, followed more slowly by
her two companions.
“I—I feel just like running away,” faltered Daisy. “Oh, Dulcie, let’s go.
It all seems so very—queer.”
“We can’t run away now,” said Dulcie, and her tone was decided,
though her teeth were beginning to chatter. “It wouldn’t be polite, and
besides, I think perhaps Barbara’s mother may understand, and be
kind to us.”
CHAPTER XVII
STEPMOTHERS

AS the children approached the house they saw that a pony phaeton
was standing by the front steps, out of which a lady had just alighted.
She was speaking to the groom, who had run up from the stable to
take the horse, but at the sound of Barbara’s voice she turned to
greet her little daughter, and even at that first glimpse Dulcie and
Daisy could see that she had a very sweet face.
“Mamma,” cried Barbara, reaching her mother’s side in a rather
breathless condition, “here are two little girls who want to see you.
Their names are Delia and Margaret Smith. The biggest one is Delia;
she chose her name herself, and the littlest one is Margaret.”
Mrs. Thorne greeted the visitors very kindly.
“I am glad Barbara has found some little friends,” she said. “Suppose
we all come into the house. It is rather warm, and I would like to take
off my hat before doing anything else.”
“We’re—we’re looking for a situation.”—Page 259.
Her voice was so kind and cordial, and her smile so pleasant, that
Dulcie and Daisy were both conscious of a sensation of decided
relief. Still, the situation remained an embarrassing one, for it was
quite evident that Mrs. Thorne supposed them to be some little
neighbors come to make a morning call. However, there was nothing
to be done but to follow Barbara and her mother into the house, and
then they found themselves in a cool, flower-scented room, and Mrs.
Thorne was saying in her bright, friendly voice:
“I am sorry you had such a hot morning for your walk. I hope you did
not have far to come.”
“We—we don’t live here,” stammered Dulcie, her cheeks growing
suddenly very hot. “We came in the train, and walked up from the
station.”
“You came on the train?” Mrs. Thorne repeated, incredulously. “You
don’t mean by yourselves?”
“Oh, yes,” said Dulcie. “You see, we had to. We’re—we’re looking for
a situation.”
Mrs. Thorne gazed in growing bewilderment from one serious little
face to the other.
“A situation,” she gasped. “Why, you are only children.”
“I’m twelve,” said Dulcie, rather tremulously, “and Dais—I mean
Margaret, is eleven. Of course we wouldn’t expect to be paid very
much at first.”
“But I don’t understand. Why do you want to work at all? You are not
poor children.”
That was just what Barbara had said, and Dulcie felt her heart sink.
How could they ever explain the situation without telling the whole
story?
“We’ve gone away, because we don’t want to be burdens to our
stepmother,” put in Daisy, coming to her sister’s relief.
A shadow crossed Mrs. Thorne’s sweet face, and as if instinctively,
she slipped an arm round Barbara, who was standing by her side.
“Don’t you love your stepmother?” she asked, gently. “Isn’t she kind
to you?”
“We’ve never seen her,” Daisy explained. “She’s only coming to-day.
Papa married her in California, and we never knew anything about it
till yesterday. We are sure she won’t want us, and we are very tired
of being burdens to people, so we came away to earn our own
livings.”
Daisy paused abruptly, and two big tears rolled slowly down her
cheeks.
Mrs. Thorne was really wonderful. She seemed to understand the
whole situation at once, without asking another question.
“You poor little chicks,” she said, and her voice was so kind that,
instead of checking Daisy’s tears, it caused her to cry all the more.
And then somehow, they were all on the sofa together, and Mrs.
Thorne had one arm round Daisy, and the other round Dulcie—who
had also begun to cry—and Barbara was looking on, with tears of
sympathy in her own eyes.
“We love our papa very much indeed,” sobbed Dulcie, “but we think
perhaps he will be glad to have us go away, on account of the
stepmother, you know. I promised Mamma before she died that I
would always take care of the others, and stepmothers are so very
cruel sometimes.”
“There, there, dear,” soothed Mrs. Thorne, “don’t try to talk any more
till you feel better. I think I understand everything. You have made a
foolish mistake, but it’s going to be all right.”
There was something wonderfully reassuring in that kind, cheerful
voice, and in a few minutes the two little girls had dried their tears,
and were beginning to feel almost cheerful themselves. But now a
new difficulty arose; something that neither of them had ever thought
of. In their absorption they had quite failed to notice that the hot
sunshine had been suddenly obscured by a dark cloud, until
suddenly the rumble of distant thunder fell upon their ears. Daisy
was on her feet in a moment.
“There’s going to be a thunder-storm!” she exclaimed. “We must go
right after Molly and Maud. Maud hates thunder.”
“Who are Molly and Maud?” inquired Mrs. Thorne, and, as if in
answer to her question, there was a sound of little feet on the piazza,
and through the open window came an anxious voice.
“Dulcie, Daisy, where are you? There’s a horrid thunder-storm
coming up.”
“They are our two little sisters,” explained Dulcie. “We left them out
on the road. We were afraid people wouldn’t take us if they saw how
many there were. Would you mind very much if they came in, just till
the shower is over? Maud is so afraid of thunder-storms.”
“Certainly not,” said Mrs. Thorne, who was beginning to look very
much amused. “Run and bring the little girls in, Barbara.”
Away flew hospitable Barbara, closely followed by Dulcie and Daisy,
and in another moment they were back again, accompanied by Molly
and Maud, who both looked very red and uncomfortable.
“It was all Maud’s fault,” Molly was whispering apologetically to
Dulcie. “I wanted to wait, but the minute she heard the thunder she
was frightened, and she cried so hard I had to let her come to find
you.”
“It was beginning to thunder,” Maud was at the same moment
explaining to the sympathetic Barbara. “Dulcie and Daisy stayed
away so long, and I was so thirsty. I thought I was going to like cake
for breakfast, but I didn’t; it left such a funny taste afterwards.”
“Dulcie and Daisy,” repeated Barbara; “why, I thought their names
were Delia and Margaret.”
Maud looked blank, and Dulcie, blushing furiously, but still with a
desperate attempt to keep up their assumed characters, hastened to
explain.
“Dulcie and Daisy are our home names,” she said. “Daisy’s real
name is Margaret.”
“And your real name is Delia, I suppose,” said Mrs. Thorne, smiling;
“Delia Smith, I think you said.”
Dulcie was silent. She was a truthful child, and not even for the
honor of the Winslow family could she bring herself to tell a
deliberate lie. Mrs. Thorne seemed to understand, for she smiled
again, and her voice was very kind.
“Barbara darling,” she said, “suppose you take Molly and Maud into
the dining-room, and get them each a glass of milk. Maud says she
is thirsty, and cake is hardly a substantial breakfast. Ask Jane to boil
some eggs, and warm some oatmeal, and we will all come in a few
minutes. Now, my dear little girls,” she added in a graver tone, when
the three younger children had left the room, “I want you to tell me
your real names, and where you live. I must let your family know
where you are as soon as possible. They are probably frightened to
death about you already.”
Dulcie clasped her hands in despair, as she saw the last hope of
carrying out her wonderful plan of independence fading from her
grasp. But there was an air of gentle determination about Mrs.
Thorne that convinced her of the uselessness of a refusal. She
answered meekly:
“My name is Dulcie Winslow and my sister is really Margaret, but
every one calls her Daisy. We live at Tarrytown with our
grandmother, and——”
“You don’t mean to tell me you are old Dr. Winslow’s grandchildren!”
interrupted Mrs. Thorne, in a tone of genuine astonishment.
Dulcie nodded, and Daisy asked timidly:
“Did you know our grandfather?”
“I used to see him often when I was a little girl. We were neighbors in
New York, and his son Jim was a great friend of mine.”
“Why, that’s our papa!” cried Dulcie, shame and disappointment alike
forgotten in the excitement of this discovery. “How wonderful to think
you knew Papa. Perhaps you knew Mamma, too.”
“No, I never saw your father after he went to college, but we were
great friends as children. He was a very nice boy.”
“He’s the loveliest man in the world,” declared Daisy, with shining
eyes.
Mrs. Thorne smiled.
“Is he indeed?” she said. “One would hardly think you were so fond
of him when you have been trying to run away from him.”
“Oh, we weren’t running away from Papa,” cried Dulcie, quite
horrified at the suggestion. “We love him better than any one else in
the world, and we were so happy when we knew he was coming
home from China, but then we heard about the stepmother, and I
thought—I was afraid——” Dulcie paused in hopeless confusion.
“We didn’t want to be incumbrances,” said Daisy. “Aunt Julia Chester
said we were incumbrances to Grandma. Dulcie looked up the word
in the dictionary, and it means the same thing as being a burden.
Dulcie thought we might be able to work for our living, even if we
were only little girls, and so——”
“And so you ran away, like two very foolish children, and took your
younger sisters with you. I suppose it never occurred to you how
unhappy you would make your father.”
At this awful suggestion both little girls began to cry.
“I—I thought he would be proud of us,” sobbed Dulcie. “I wouldn’t
make Papa unhappy for the whole world.”
“There, there, dear, don’t cry; I knew you wouldn’t.” And Mrs. Thorne
put a kind arm round the trembling child. “You thought you were
doing something very fine, and now you are going to do something
much finer, by going home again, and showing your papa that you
trust him, and feel sure he would not do anything to make you
unhappy. As for the stepmother; all stepmothers are not wicked.
There are many who love their stepchildren dearly. Perhaps your
stepmother is longing to know you, and to make you love her. I doubt
very much that she has ever thought of you as incumbrances. Now I
think breakfast must be ready, so dry your eyes, and we will join the
others in the dining-room.”
That was a wonderful morning; the children never forgot it. To Molly
and Maud it was a morning of pure delight, and even their elder
sisters, in spite of several causes for anxiety, could not help enjoying
themselves, whenever they forgot to think about the future. Mrs.
Thorne was very kind to them all, and Barbara proved a delightful
little hostess. The shower was a very slight one, and by the time they
had finished breakfast, the sun was shining once more. Mrs. Thorne
went out in the pony phaeton again, and Dulcie and Daisy had an
uncomfortable conviction that her errand was in some way
connected with their affairs. Nothing, however, was said about their
going home at once, and Barbara took them all out to inspect the
rabbits. When it grew too hot in the sun, they came indoors again,
and Barbara took them up to her nursery—a room so full of beautiful
toys that Molly and Maud felt as if suddenly transported to fairyland.
“What do you suppose is going to happen?” Daisy whispered to
Dulcie, on the way up-stairs. “Are we to stay here till somebody
comes to take us home?”
“I don’t know,” Dulcie answered mournfully; “Mrs. Thorne is attending
to everything, and I don’t like to ask her any questions. The thing I’m
most afraid of is that Grandma may come for us herself. It would be
dreadful to have to go all the way home in the train with Grandma.”
At one o’clock Mrs. Thorne called them all down to luncheon, and it
was just as they were finishing that meal that the telegram arrived.
The waitress brought it in on a tray, and handed it to Mrs. Thorne,
who opened it, and read aloud:
“Please send children home by next train. They will be met
at the station.”
There was a moment of dead silence, and then Mrs. Thorne said
quietly:
“The telegram is from your grandmother, in answer to one I sent her
this morning.”
“We thought it was,” said Dulcie, meekly. “How soon does the next
train go?”
Mrs. Thorne left the room to consult a time-table, and Barbara began
to express her entire disapproval of the whole affair.
“I don’t see why you can’t stay,” she protested; “there’s plenty of
room. It would be so nice to have you stay all summer, and we could
have such fun all together. Wouldn’t you like to stay?”
“It would be lovely,” said Dulcie, politely, “but your mother doesn’t
think it would be right. She is afraid Papa wouldn’t like it.”
“Our papa is coming home to-day,” chimed in Molly, “and we haven’t
seen him for more than a year.”
“Papas are pretty nice,” Barbara admitted, “but of course they’re not
like mammas. I don’t think I could possibly leave Mamma, even to go
to the nicest place in the world. Mamma says perhaps you can come
to see us again some day. I’m so glad your name isn’t Delia Smith,
Dulcie; Dulcie Winslow is ever so much prettier, and I think I like
Daisy better than Margaret, too. I suppose your papa would be
disappointed if you were away when he came. Haven’t you any
mamma?”
“No,” said Dulcie, with a sigh; “she died when we were very little. I
am the only one who can remember her.”
Barbara looked interested.
“My first mamma died when I was a little baby,” she said; “I can’t
remember her a bit.”
The four little Winslows nearly dropped their spoons into the ice-
cream, so great was their astonishment at this amazing
announcement.
“Your—your what?” gasped Dulcie.
“My first mamma,” repeated Barbara, calmly. “I’ve got her picture on
my bureau, and I always kiss her good-night. Mamma says she
loved me very much, but I’m sure she loves me just as much herself,
because she says I’m the preciousest thing in the world.”
At that moment Mrs. Thorne returned, with a time-table in her hand.
“The next down train leaves here in half an hour,” she said; “I’m
afraid we shall have to hurry a little. I have sent word to James to
harness the ponies, and will drive you to the station myself.”
“Mrs. Thorne,” said Dulcie, regarding her hostess with big,
astonished eyes, “I hope it isn’t a rude question, but I’ve got to ask.
Are you—are you Barbara’s stepmother?”
Mrs. Thorne laughed merrily.
“So you have found out,” she said. “Yes, I am, but that doesn’t make
any difference in our love for each other, does it, Barbara darling?”
And she stooped to kiss the little girl, who responded by flinging both
arms round her neck.
“No, indeed it doesn’t,” she cried, heartily. “I wouldn’t change you for
all the mammas in the world.”
“And we thought all stepmothers were wicked and cruel,” said
Dulcie, slowly. “O dear! I’m afraid we’ve been dreadfully silly, and I
guess we’d better go home just as soon as we possibly can.”
CHAPTER XVIII
A HOME-COMING

“YOU are really, without exception, the worst-behaved children I


have ever heard of in my life. I cannot think of any punishment
severe enough for what you deserve.”
Grandma spoke in a tone of awful sternness, and her expression
was, if possible, even sterner than her voice. The four little culprits
stood before her in a row, and trembled, but nobody could think of
anything to say. It was half-past three, and the children had reached
home five minutes earlier, and been sent straight up to Grandma’s
room by Mary, in obedience to the orders she had received. It was
Mary who had met the party at the station, and on the way home had
told them of the excitement and consternation their disappearance
had caused.
“I never saw the old lady so upset before,” she declared. “She most
took Bridget’s and my head off, and goodness knows we hadn’t
anything to do with it. She read that letter you left on the bureau, and
she thought we’d told you the news about the stepmother, that was
to be kept a secret till your pa came home. She telegraphed to Miss
Kate to come home, and she was ’most wild with fright about you, till
that lady’s message came.”
It was all very dreadful, and yet there was a certain thrill in the
knowledge that Grandma had really been worried about them.
“I didn’t think she’d care much what became of us,” Dulcie had
whispered to Daisy, and Daisy had answered, with her usual
cheerfulness:
“It’s rather nice to know she does care just a little bit, after all.”
And now they were facing Grandma’s wrath, and awaiting the
punishment which they felt sure was to follow.
“I cannot conceive how such an absurd idea ever entered any of
your heads,” Mrs. Winslow went on, eyeing them over her
spectacles. “For children in your position even to contemplate such a
plan is outrageous. A Winslow taking a situation like an Irish servant
girl. It is horrible!” And the aristocratic old lady actually shuddered.
Dulcie hung her head; her cheeks were crimson.
“It was all my fault,” she said, humbly; “I thought of it first, and the
others didn’t want to do it at all.”
“I was quite sure you were the ringleader,” returned Grandma, coldly.
“You generally are, where any mischief is concerned. But Daisy and
Molly are both old enough to know better. Maud is still too young to
be expected to have judgment of any kind.”
It was then that Maud did what Dulcie afterwards described as “a
noble thing.” She had been trying to hide behind Daisy, but at
Grandma’s last words she suddenly stepped forward and spoke.
“If the others are going to be punished,” she said, in a clear, decided
little voice, “I guess you’d better punish me, too. I knew it was
naughty to eat cake for breakfast, and I did it even when Daisy told
me not to.”
There was a little gasp of admiration from the three older children,
and even Grandma’s stern face relaxed into something like a grim
smile.
“I am glad to see that you are capable of realizing how naughty you
have been,” she said. “I have had a terrible morning, but thank
Heaven, my responsibility is nearly at an end. Your father arrives this
afternoon, and it will be his duty to decide upon what punishment
you are to receive.”
“Grandma,” cried Dulcie, scarcely able to believe her ears, “aren’t
you going to punish us, then?”
“Under ordinary circumstances I should certainly punish you all
severely,” Mrs. Winslow answered, “but with your father’s return my
guardianship over you ceases. I wish I could give him a better
account of your behavior during his absence, but perhaps I am
Welcome to our website – the ideal destination for book lovers and
knowledge seekers. With a mission to inspire endlessly, we offer a
vast collection of books, ranging from classic literary works to
specialized publications, self-development books, and children's
literature. Each book is a new journey of discovery, expanding
knowledge and enriching the soul of the reade

Our website is not just a platform for buying books, but a bridge
connecting readers to the timeless values of culture and wisdom. With
an elegant, user-friendly interface and an intelligent search system,
we are committed to providing a quick and convenient shopping
experience. Additionally, our special promotions and home delivery
services ensure that you save time and fully enjoy the joy of reading.

Let us accompany you on the journey of exploring knowledge and


personal growth!

ebookfinal.com

You might also like