Tải bản đầy đủ (.pdf) (581 trang)

IT training learning PHP, MySQL, javascript, and CSS (2nd ed ) nixon 2012 09 03 4

Bạn đang xem bản rút gọn của tài liệu. Xem và tải ngay bản đầy đủ của tài liệu tại đây (14.91 MB, 581 trang )


SECOND EDITION

Learning PHP, MySQL, JavaScript,
and CSS

Robin Nixon

Beijing • Cambridge • Farnham • Köln • Sebastopol • Tokyo


Learning PHP, MySQL, JavaScript, and CSS, Second Edition
by Robin Nixon
Copyright © 2012 Robin Nixon. All rights reserved.
Printed in the United States of America.
Published by O’Reilly Media, Inc., 1005 Gravenstein Highway North, Sebastopol, CA 95472.
O’Reilly books may be purchased for educational, business, or sales promotional use. Online editions
are also available for most titles (). For more information, contact our
corporate/institutional sales department: 800-998-9938 or

Editor: Andy Oram
Production Editor: Iris Febres
Copyeditor: Rachel Head
Proofreader: Kiel Van Horn
August 2012:

Indexer: Ellen Troutman Zaig
Cover Designer: Karen Montgomery
Interior Designer: David Futato
Illustrator: Robert Romano


Second Edition.

Revision History for the Second Edition:
2012-08-10
First release
See for release details.

Nutshell Handbook, the Nutshell Handbook logo, and the O’Reilly logo are registered trademarks of
O’Reilly Media, Inc. Learning PHP, MySQL, JavaScript, and CSS, the image of sugar gliders, and related
trade dress are trademarks of O’Reilly Media, Inc.
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 O’Reilly Media, Inc., was aware of a
trademark claim, the designations have been printed in caps or initial caps.
While every precaution has been taken in the preparation of this book, the publisher and authors assume
no responsibility for errors or omissions, or for damages resulting from the use of the information contained herein.

ISBN: 978-1-449-31926-7
[LSI]
1344626556


For Julie


Table of Contents

Preface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xvii
1. Introduction to Dynamic Web Content . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1
HTTP and HTML: Berners-Lee’s Basics
The Request/Response Procedure

The Benefits of PHP, MySQL, JavaScript, and CSS
Using PHP
Using MySQL
Using JavaScript
Using CSS
The Apache Web Server
About Open Source
Bringing It All Together
Test Your Knowledge

2
2
5
5
6
7
9
9
10
10
12

2. Setting Up a Development Server . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13
What Is a WAMP, MAMP, or LAMP?
Installing a WAMP on Windows
Testing the Installation
Alternative WAMPs
Installing a MAMP on OS X
Configuring MySQL
Testing the Installation

Installing a LAMP on Linux
Working Remotely
Logging In
Using FTP
Using a Program Editor
Using an IDE
Test Your Knowledge

13
14
22
24
24
25
28
31
31
32
32
33
34
36

v


3. Introduction to PHP . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 37
Incorporating PHP Within HTML
Calling the PHP Parser
This Book’s Examples

The Structure of PHP
Using Comments
Basic Syntax
Understanding Variables
Operators
Variable Assignment
Multiple-Line Commands
Variable Typing
Constants
The Difference Between the echo and print Commands
Functions
Variable Scope
Test Your Knowledge

37
38
39
40
40
41
42
46
49
51
54
54
56
56
57
62


4. Expressions and Control Flow in PHP . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 65
Expressions
Literals and Variables
Operators
Operator Precedence
Associativity
Relational Operators
Conditionals
The if Statement
The else Statement
The elseif Statement
The switch Statement
The ? Operator
Looping
while Loops
do…while Loops
for Loops
Breaking Out of a Loop
The continue Statement
Implicit and Explicit Casting
PHP Dynamic Linking
Dynamic Linking in Action
Test Your Knowledge

vi | Table of Contents

65
66
67

68
70
71
75
75
76
78
78
81
82
83
85
85
87
88
89
90
90
91


5. PHP Functions and Objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 93
PHP Functions
Defining a Function
Returning a Value
Returning an Array
Passing by Reference
Returning Global Variables
Recap of Variable Scope
Including and Requiring Files

The include Statement
Using include_once
Using require and require_once
PHP Version Compatibility
PHP Objects
Terminology
Declaring a Class
Creating an Object
Accessing Objects
Constructors
Writing Methods
Declaring Properties
Declaring Constants
Property and Method Scope in PHP 5
Inheritance
Test Your Knowledge

94
95
96
97
98
99
100
100
100
101
101
102
102

103
104
105
105
108
109
110
111
112
114
117

6. PHP Arrays . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 119
Basic Access
Numerically Indexed Arrays
Associative Arrays
Assignment Using the array Keyword
The foreach...as Loop
Multidimensional Arrays
Using Array Functions
is_array
count
sort
shuffle
explode
extract
compact
reset
end


119
119
121
122
122
124
127
127
127
128
128
128
129
130
131
131
Table of Contents | vii


Test Your Knowledge

132

7. Practical PHP . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 133
Using printf
Precision Setting
String Padding
Using sprintf
Date and Time Functions
Date Constants

Using checkdate
File Handling
Checking Whether a File Exists
Creating a File
Reading from Files
Copying Files
Moving a File
Deleting a File
Updating Files
Locking Files for Multiple Accesses
Reading an Entire File
Uploading Files
System Calls
XHTML
The Benefits of XHTML
XHTML Versions
What’s Different?
HTML 4.01 Document Types
The HTML5 Document Type
XHTML 1.0 Document Types
XHTML Validation
Test Your Knowledge

133
134
136
137
137
140
140

141
141
141
143
143
144
144
145
146
147
148
153
154
155
155
155
156
157
157
158
159

8. Introduction to MySQL . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 161
MySQL Basics
Summary of Database Terms
Accessing MySQL via the Command Line
Starting the Command-Line Interface
Using the Command-Line Interface
MySQL Commands
Data Types

Indexes
Creating an Index
Querying a MySQL Database
viii | Table of Contents

161
162
162
163
166
168
172
181
182
187


Joining Tables Together
Using Logical Operators
MySQL Functions
Accessing MySQL via phpMyAdmin
Windows Users
OS X Users
Linux Users
Using phpMyAdmin
Test Your Knowledge

196
198
199

199
199
201
201
201
202

9. Mastering MySQL . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 205
Database Design
Primary Keys: The Keys to Relational Databases
Normalization
First Normal Form
Second Normal Form
Third Normal Form
When Not to Use Normalization
Relationships
One-to-One
One-to-Many
Many-to-Many
Databases and Anonymity
Transactions
Transaction Storage Engines
Using BEGIN
Using COMMIT
Using ROLLBACK
Using EXPLAIN
Backing Up and Restoring
Using mysqldump
Creating a Backup File
Restoring from a Backup File

Dumping Data in CSV Format
Planning Your Backups
Test Your Knowledge

205
206
207
208
210
212
214
215
215
216
216
218
218
219
220
220
221
221
223
223
224
226
226
227
227


10. Accessing MySQL Using PHP . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 229
Querying a MySQL Database with PHP
The Process
Creating a Login File
Connecting to MySQL
A Practical Example

229
229
230
231
236
Table of Contents | ix


The $_POST Array
Deleting a Record
Displaying the Form
Querying the Database
Running the Program
Practical MySQL
Creating a Table
Describing a Table
Dropping a Table
Adding Data
Retrieving Data
Updating Data
Deleting Data
Using AUTO_INCREMENT
Performing Additional Queries

Preventing SQL Injection
Preventing HTML Injection
Test Your Knowledge

238
239
239
240
241
242
242
243
244
244
245
246
246
247
248
249
252
254

11. Form Handling . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 255
Building Forms
Retrieving Submitted Data
register_globals: An Old Solution Hangs On
Default Values
Input Types
Sanitizing Input

An Example Program
Test Your Knowledge

255
256
258
258
259
266
267
270

12. Cookies, Sessions, and Authentication . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 271
Using Cookies in PHP
Setting a Cookie
Accessing a Cookie
Destroying a Cookie
HTTP Authentication
Storing Usernames and Passwords
Salting
Using Sessions
Starting a Session
Ending a Session
Session Security
Test Your Knowledge

x | Table of Contents

271
273

273
274
274
277
277
281
281
284
286
289


13. Exploring JavaScript . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 291
JavaScript and HTML Text
Using Scripts Within a Document Head
Older and Nonstandard Browsers
Including JavaScript Files
Debugging JavaScript Errors
Using Comments
Semicolons
Variables
String Variables
Numeric Variables
Arrays
Operators
Arithmetic Operators
Assignment Operators
Comparison Operators
Logical Operators
Variable Incrementing and Decrementing

String Concatenation
Escaping Characters
Variable Typing
Functions
Global Variables
Local Variables
The Document Object Model (DOM)
But It’s Not That Simple
Using the DOM
Test Your Knowledge

291
293
293
294
295
297
297
298
298
298
299
299
300
300
301
301
301
302
302

303
303
304
304
305
307
308
309

14. Expressions and Control Flow in JavaScript . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 311
Expressions
Literals and Variables
Operators
Operator Precedence
Associativity
Relational Operators
The with Statement
Using onerror
Using try...catch
Conditionals
The if Statement
The switch statement
The ? Operator

311
312
313
314
314
315

318
318
319
320
320
321
323
Table of Contents | xi


Looping
while Loops
do…while Loops
for Loops
Breaking Out of a Loop
The continue Statement
Explicit Casting
Test Your Knowledge

323
323
324
324
325
326
327
327

15. JavaScript Functions, Objects, and Arrays . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 329
JavaScript Functions

Defining a Function
Returning a Value
Returning an Array
JavaScript Objects
Declaring a Class
Creating an Object
Accessing Objects
The prototype Keyword
JavaScript Arrays
Numeric Arrays
Associative Arrays
Multidimensional Arrays
Using Array Methods
Test Your Knowledge

329
329
331
333
333
333
335
335
336
338
338
339
340
341
345


16. JavaScript and PHP Validation and Error Handling . . . . . . . . . . . . . . . . . . . . . . . . . . 347
Validating User Input with JavaScript
The validate.html Document (Part One)
The validate.html Document (Part Two)
Regular Expressions
Matching Through Metacharacters
Fuzzy Character Matching
Grouping Through Parentheses
Character Classes
Some More Complicated Examples
Summary of Metacharacters
General Modifiers
Using Regular Expressions in JavaScript
Using Regular Expressions in PHP
Redisplaying a Form After PHP Validation
Test Your Knowledge

xii | Table of Contents

347
348
350
353
353
354
355
355
356
359

360
361
361
362
367


17. Using Ajax . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 369
What Is Ajax?
Using XMLHttpRequest
Implementing Ajax via POST Requests
The readyState Property
The Server Half of the Ajax Process
Using GET Instead of POST
Sending XML Requests
About XML
Why Use XML?
Using Frameworks for Ajax
Test Your Knowledge

369
370
372
374
375
377
379
381
383
383

383

18. Introduction to CSS . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 385
Importing a Style Sheet
Importing a Style Sheet from Within HTML
Embedded Style Settings
Using IDs
Using Classes
CSS Rules
Using Semicolons
Multiple Assignments
Using Comments
Style Types
Default Styles
User Styles
External Style Sheets
Internal Styles
Inline Styles
CSS Selectors
The Type Selector
The Descendant Selector
The Child Selector
The Adjacent Sibling Selector
The ID Selector
The Class Selector
The Attribute Selector
The Universal Selector
Selecting by Group
The CSS Cascade
Style Sheet Creators

Style Sheet Methods
Style Sheet Selectors

386
386
387
387
387
388
388
388
389
390
390
390
390
391
391
392
392
392
393
394
395
395
396
396
397
398
398

398
399
Table of Contents | xiii


The Difference Between <div> and <span>
Measurements
Fonts and Typography
font-family
font-style
font-size
font-weight
Managing Text Styles
Decoration
Spacing
Alignment
Transformation
Indenting
CSS Colors
Short Color Strings
Gradients
Positioning Elements
Absolute Positioning
Relative Positioning
Fixed Positioning
Comparing Positioning Types
Pseudoclasses
Pseudoelements
Shorthand Rules
The Box Model and Layout

Setting Margins
Applying Borders
Adjusting Padding
Object Contents
Test Your Knowledge

401
402
404
404
405
406
406
407
407
407
408
408
408
408
409
410
411
411
412
412
412
413
415
416

416
417
418
419
420
421

19. Advanced CSS with CSS3 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 423
Attribute Selectors
Matching Parts of Strings
The box-sizing Property
CSS3 Backgrounds
The background-clip Property
The background-origin Property
The background-size Property
Multiple Backgrounds
CSS3 Borders
The border-color Property
The border-radius Property

xiv | Table of Contents

423
424
425
425
426
426
428
428

430
430
431


Box Shadows
Element Overflow
Multicolumn Layout
Colors and Opacity
HSL Colors
HSLA Colors
RGB Colors
RGBA Colors
The opacity Property
Text Effects
The text-shadow Property
The text-overflow Property
The word-wrap Property
Web Fonts
Google Web Fonts
Transformations
Transitions
Properties to Transition
Transition Duration
Transition Delay
Transition Timing
Shorthand Syntax
Test Your Knowledge

434

435
435
436
437
437
438
438
438
439
439
439
440
440
441
441
444
444
444
444
445
445
447

20. Accessing CSS from JavaScript . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 449
Revisiting the getElementById Function
The O Function
The S Function
The C Function
Including the Functions
Accessing CSS Properties from JavaScript

Some Common Properties
Other Properties
Inline JavaScript
The this Keyword
Attaching Events to Objects in a Script
Attaching to Other Events
Adding New Elements
Removing Elements
Alternatives to Adding and Removing Elements
Using Interrupts
Using setTimeout
Canceling a Timeout

449
449
450
451
452
453
453
455
456
457
457
458
459
460
461
462
462

463

Table of Contents | xv


Using setInterval
Using Interrupts for Animation
Test Your Knowledge

463
465
467

21. Bringing It All Together . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 469
Designing a Social Networking Site
On the Website
functions.php
The Functions
header.php
setup.php
index.php
signup.php
Checking for Username Availability
checkuser.php
login.php
profile.php
Adding the “About Me” Text
Adding a Profile Image
Processing the Image
Displaying the Current Profile

members.php
Viewing a User’s Profile
Adding and Dropping Friends
Listing All Members
friends.php
messages.php
logout.php
styles.css

469
470
470
470
472
474
475
475
476
478
479
481
482
482
482
483
485
486
486
486
488

491
493
495

A. Solutions to the Chapter Questions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 499
B. Online Resources . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 513
C. MySQL’s FULLTEXT Stopwords . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 517
D. MySQL Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 521
Index . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 533

xvi | Table of Contents


Preface

The combination of PHP and MySQL is the most convenient approach to dynamic,
database-driven web design, holding its own in the face of challenges from integrated
frameworks—such as Ruby on Rails—that are harder to learn. Due to its open source
roots (unlike the competing Microsoft .NET framework), it is free to implement and is
therefore an extremely popular option for web development.
Any would-be developer on a Unix/Linux or even a Windows/Apache platform will
need to master these technologies. At the same time, JavaScript is important, as it provides in-browser dynamic functionality and, through Ajax, hidden communication
with the web server to create seamless interfaces. In conjunction with CSS, these technologies integrate to provide a formidable array of powerful web-development tools.

Audience
This book is for people who wish to learn how to create effective and dynamic websites.
This may include webmasters or graphic designers who are already creating static websites but wish to take their skills to the next level, as well as high school and college
students, recent graduates, and self-taught individuals.
In fact, anyone ready to learn the fundamentals behind the Web 2.0 technology known
as Ajax will obtain a thorough grounding in all of these core technologies: PHP, MySQL,

JavaScript, and CSS.

Assumptions This Book Makes
This book assumes that you have a basic understanding of HTML and can at least put
together a simple, static website, but it does not assume that you have any prior knowledge of PHP, MySQL, JavaScript, or CSS. That said, if you do, your progress through
the book will be even quicker.

xvii


Organization of This Book
The chapters in this book are written in a specific order, first introducing all of the core
technologies it covers and then walking you through their installation on a web development server, so that you will be ready to work through the examples.
In the following section, you will gain a grounding in the PHP programming language,
covering the basics of syntax, arrays, functions, and object-oriented programming.
Then, with PHP under your belt, you will move on to an introduction to the MySQL
database system, where you will learn everything from how MySQL databases are
structured up to how to generate complex queries.
After that, you will learn how you can combine PHP and MySQL to start creating your
own dynamic web pages by integrating forms and other HTML features. You will then
spend some time looking at ways to speed up your web development using Smarty
templates.
In the next three chapters you will get down to the nitty-gritty practical aspects of PHP
and MySQL development, learning about a variety of useful functions, how to manage
cookies and sessions, and how to maintain a high level of security.
In the following four chapters you will gain a thorough grounding in JavaScript, from
simple functions and event handling to accessing the Document Object Model and inbrowser validation and error handling.
With an understanding of all three of these core technologies, you will then learn how
to make behind-the-scenes Ajax calls and turn your websites into highly dynamic
environments.

Finally, you’ll spend two chapters learning all about using CSS to style and lay out your
web pages, and then you’ll put together everything you’ve learned in a complete set of
programs that together constitute a fully working social networking website.
Along the way, you’ll also find plenty of pointers and advice on good programming
practices and tips that could help you find and solve hard-to-detect programming errors. There are also plenty of links to websites containing further details on the topics
covered.

Supporting Books
Once you have learned to develop using PHP, MySQL, and JavaScript you will be ready
to take your skills to the next level using the following reference books:
• Dynamic HTML: The Definitive Reference ( ) by Danny
Goodman (O’Reilly)
• PHP in a Nutshell ( by Paul Hudson (O’Reilly)
• MySQL in a Nutshell ( by Russell Dyer (O’Reilly)
xviii | Preface


• JavaScript: The Definitive Guide ( by David Flanagan
(O’Reilly)
• CSS: The Definitive Guide ( by Eric A. Myer (O’Reilly)

Conventions Used in This Book
The following typographical conventions are used in this book:
Italic
Indicates new terms, URLs, email addresses, filenames, and file extensions.
Constant width

Used for program listings, as well as within paragraphs to refer to program elements
such as variable or function names, databases, data types, environment variables,
statements, and keywords.

Constant width bold

Shows commands or other text that should be typed literally by the user.
Constant width italic

Shows text that should be replaced with user-supplied values or by values determined by context.
This icon signifies a tip, suggestion, or general note.

This icon indicates a warning or caution.

Using Code Examples
This book is here to help you get your job done. In general, you may use the code in
this book in your programs and documentation. You do not need to contact us for
permission unless you’re reproducing a significant portion of the code. For example,
writing a program that uses several chunks of code from this book does not require
permission. Selling or distributing a CD-ROM of examples from O’Reilly books does
require permission. Answering a question by citing this book and quoting example
code does not require permission. Incorporating a significant amount of example code
from this book into your product’s documentation does require permission.
We appreciate, but do not require, attribution. An attribution usually includes the title,
author, publisher, and ISBN. For example: “Learning PHP, MySQL, JavaScript &

Preface | xix


CSS, Second Edition, by Robin Nixon. Copyright 2012 Robin Nixon,
978-1-4493-1926-7.”
If you feel your use of code examples falls outside fair use or the permission given here,
feel free to contact us at


Safari® Books Online
Safari Books Online (www.safaribooksonline.com) is an on-demand digital
library that delivers expert content in both book and video form from the
world’s leading authors in technology and business.
Technology professionals, software developers, web designers, and business and creative professionals use Safari Books Online as their primary resource for research,
problem solving, learning, and certification training.
Safari Books Online offers a range of product mixes and pricing programs for organizations, government agencies, and individuals. Subscribers have access to thousands
of books, training videos, and prepublication manuscripts in one fully searchable database from publishers like O’Reilly Media, Prentice Hall Professional, Addison-Wesley
Professional, Microsoft Press, Sams, Que, Peachpit Press, Focal Press, Cisco Press, John
Wiley & Sons, Syngress, Morgan Kaufmann, IBM Redbooks, Packt, Adobe Press, FT
Press, Apress, Manning, New Riders, McGraw-Hill, Jones & Bartlett, Course Technology, and dozens more. For more information about Safari Books Online, please visit
us online.

How to Contact Us
Please address comments and questions concerning this book to the publisher:
O’Reilly Media, Inc.
1005 Gravenstein Highway North
Sebastopol, CA 95472
800-998-9938 (in the United States or Canada)
707-829-0515 (international or local)
707-829-0104 (fax)
We have a web page for this book, where we list errata, examples, and any additional
information. You can access this page at />There is also a companion website to this book, where you can see all the examples
with color-highlighted syntax, available online at .
To comment or ask technical questions about this book, send email to


xx | Preface



For more information about our books, courses, conferences, and news, see our website
at .
Find us on Facebook: />Follow us on Twitter: />Watch us on YouTube: />
Acknowledgments
A huge thank you goes to my editor, Andy Oram, who always has great ideas for better
explaining tricky subjects; Rachel Head for an excellent job of tidying up my manuscript; Iris Febres and Rachel Steely, who oversaw production meticulously; Robert
Romano for the easy-to-follow illustrations in both editions; Ellen Troutman Zaig for
creating a thoroughly comprehensive index; Karen Montgomery for the great sugar
glider front cover; David Futato for the clear and easy-to-read interior design; and all
the other dedicated people at O’Reilly who worked so hard on this book, and without
whom it simply wouldn’t be the same.
I would also like to thank my technical reviewers from the first edition, Derek DeHart,
Christoph Dorn, Tomislav Dugandzic, Becka Morgan, Harry Nixon, Alan Solis, and
Demian Turner, and Albert Wiersch for his invaluable input and advice on the CSS
section new to this edition. Finally, thanks to the first edition readers who spotted typos
and sent in errata and suggestions for improving the book, all of whom have helped to
bring this revised, updated, and improved web development tutorial to fruition.

Preface | xxi



CHAPTER 1

Introduction to Dynamic Web Content

The World Wide Web is a constantly evolving network that has already traveled far
beyond its conception in the early 1990s, when it was created to solve a specific problem. State-of-the-art experiments at CERN (the European Laboratory for Particle Physics—now best known as the operator of the Large Hadron Collider) were producing
incredible amounts of data—so much that the data was proving unwieldy to distribute
to the participating scientists who were spread out across the world.

At this time, the Internet was already in place, with several hundred thousand computers connected to it. Tim Berners-Lee (a CERN fellow) devised a method of navigating between them using a hyperlinking framework, which came to be known as the
Hyper Text Transfer Protocol, or HTTP. He also created a markup language called
HTML, or Hyper Text Markup Language. To bring these together, he wrote the first
web browser and web server.
We now take these tools for granted, but back then, the concept was revolutionary.
The most connectivity so far experienced by at-home modem users was dialing up and
connecting to a bulletin board that was hosted by a single computer, where you could
communicate and swap data only with other users of that service. Consequently, you
needed to be a member of many bulletin board systems in order to effectively communicate electronically with your colleagues and friends.
But Berners-Lee changed all that in one fell swoop, and by the mid-1990s there were
three major graphical web browsers competing for the attention of five million users.
It soon became obvious, though, that something was missing. Yes, pages of text and
graphics with hyperlinks to take you to other pages was a brilliant concept, but the
results didn’t reflect the instantaneous potential of computers and the Internet to meet
the particular needs of each user with dynamically changing content. Using the Web
was a very dry and plain experience, even if we did now have scrolling text and animated
GIFs!
Shopping carts, search engines, and social networks have clearly altered how we use
the Web. In this chapter, we’ll take a brief look at the various components that make
up the Web, and the software that helps make it a rich and dynamic experience.
1


It is necessary to start using some acronyms more or less right away. I
have tried to clearly explain them before proceeding, but don’t worry
too much about what they stand for or what these names mean, because
the details will all become clear as you read on.

HTTP and HTML: Berners-Lee’s Basics
HTTP is a communication standard governing the requests and responses that take

place between the browser running on the end user’s computer and the web server.
The server’s job is to accept a request from the client and attempt to reply to it in a
meaningful way, usually by serving up a requested web page—that’s why the term
server is used. The natural counterpart to a server is a client, so that term is applied
both to the web browser and the computer on which it’s running.
Between the client and the server there can be several other devices, such as routers,
proxies, gateways, and so on. They serve different roles in ensuring that the requests
and responses are correctly transferred between the client and server. Typically, they
use the Internet to send this information.
A web server can usually handle multiple simultaneous connections and—when not
communicating with a client—spends its time listening for an incoming connection
request. When one arrives, the server sends back a response to confirm its receipt.

The Request/Response Procedure
At its most basic level, the request/response process consists of a web browser asking
the web server to send it a web page and the server sending back the page. The browser
then takes care of displaying the page (see Figure 1-1).
These are the steps in the request and response sequence:
1.
2.
3.
4.
5.
6.
7.

You enter into your browser’s address bar.
Your browser looks up the IP address for server.com.
Your browser issues a request for the home page at server.com.
The request crosses the Internet and arrives at the server.com web server.

The web server, having received the request, looks for the web page on its hard disk.
The server retrieves the web page and returns it to the browser.
Your browser displays the web page.

For an average web page, this process takes place once for each object within the page:
a graphic, an embedded video or Flash file, and even a CSS template.
In step 2, notice that the browser looked up the IP address of server.com. Every machine
attached to the Internet has an IP address—your computer included. But we generally
access web servers by name, such as google.com. As you probably know, the browser
2 | Chapter 1: Introduction to Dynamic Web Content


Figure 1-1. The basic client/server request/response sequence

consults an additional Internet service called the Domain Name Service (DNS) to find
the server’s associated IP address and then uses that to communicate with the computer.
For dynamic web pages, the procedure is a little more involved, because it may bring
both PHP and MySQL into the mix (see Figure 1-2).
Here are the steps:
1.
2.
3.
4.
5.

You enter into your browser’s address bar.
Your browser looks up the IP address for server.com.
Your browser issues a request to that address for the web server’s home page.
The request crosses the Internet and arrives at the server.com web server.
The web server, having received the request, fetches the home page from its hard

disk.
6. With the home page now in memory, the web server notices that it is a file incorporating PHP scripting and passes the page to the PHP interpreter.
7. The PHP interpreter executes the PHP code.
8. Some of the PHP contains MySQL statements, which the PHP interpreter now
passes to the MySQL database engine.
HTTP and HTML: Berners-Lee’s Basics | 3


×