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

303 learning PHP, MySQL, and javascript

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 (10.03 MB, 528 trang )


Download at Boykma.Com


www.it-ebooks.info
Download at Boykma.Com

Learning PHP, MySQL, and
JavaScript

Robin Nixon

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


www.it-ebooks.info
Download at Boykma.Com

Learning PHP, MySQL, and JavaScript
by Robin Nixon
Copyright © 2009 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: Sumita Mukherji
Copyeditor: Nancy Kotary
Proofreader: Kiel Van Horn



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

Printing History:
July 2009:

First Edition.

Nutshell Handbook, the Nutshell Handbook logo, and the O’Reilly logo are registered trademarks of
O’Reilly Media, Inc. Learning PHP, MySQL, and JavaScript, 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 author assume
no responsibility for errors or omissions, or for damages resulting from the use of the information contained herein.

TM

This book uses RepKover™, a durable and flexible lay-flat binding.
ISBN: 978-0-596-15713-5
[M]
1246467361


www.it-ebooks.info
Download at Boykma.Com


Table of Contents

Preface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xiii
1. Introduction to Dynamic Web Content . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1
HTTP and HTML: Berners-Lee’s Basics
The Request/Response Procedure
The Benefits of PHP, MySQL, and JavaScript
Using PHP
Using MySQL
Using JavaScript
The Apache Web Server
About Open Source
Bringing It All Together
Test Your Knowledge: Questions

2
2
5
5
6
7
8
9
9
11

2. Setting Up a Development Server . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13
What Is a WAMP, MAMP, or LAMP?
Installing a WAMP on Windows

Overcoming Installation Problems
Testing the Installation
Alternative WAMPs
Installing a MAMP on Mac OS X
Some Final Tweaking
Other Alternatives
Installing a LAMP on Linux
Working Remotely
Logging In
Using FTP
Using a Program Editor
Using an IDE
Test Your Knowledge: Questions

13
14
14
16
18
19
24
25
25
26
27
27
28
30
32


iii


www.it-ebooks.info
Download at Boykma.Com

3. Introduction to PHP . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33
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: Questions

33
34
35
36
36
37

38
42
45
47
49
50
51
52
53
58

4. Expressions and Control Flow in PHP . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 61
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: Questions

iv | Table of Contents

61
62
63
64
66
67
70
71
72
73
74
77
78
78
80
81
83
84
84
85
86
87



www.it-ebooks.info
Download at Boykma.Com

5. PHP Functions and Objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 89
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: Questions


90
91
92
93
94
95
96
96
96
97
97
98
98
99
100
101
101
104
105
106
107
107
109
113

6. PHP Arrays . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 115
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()

115
115
117
118
119
121
123
123
124
124
124
125
125
126
127
128
Table of Contents | v



www.it-ebooks.info
Download at Boykma.Com

Test Your Knowledge: Questions

128

7. Practical PHP . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 129
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
XHTML 1.0 Document Types
XHTML Validation
Test Your Knowledge: Questions

129
131
132
133
133
136
136
137
137
137
139
139
140
140
141
142
143
144
149
151
151
151

152
153
153
154
155

8. Introduction to MySQL . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 157
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
Joining Tables Together
vi | Table of Contents

157
158
158
159
163
164
168
177
178
183

192


www.it-ebooks.info
Download at Boykma.Com

Using Logical Operators
MySQL Functions
Accessing MySQL via phpMyAdmin
Windows Users
Mac OS X Users
Linux Users
Using phpMyAdmin
Test Your Knowledge: Questions

194
194
195
195
195
195
197
198

9. Mastering MySQL . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 201
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: Questions

201
202
203
204
206
208
210
211
211

212
212
214
214
215
216
216
216
217
218
219
220
222
222
223
223

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

225
225
226
227
232

234
Table of Contents | vii


www.it-ebooks.info
Download at Boykma.Com

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: Questions

235
236
236
237
238

238
239
240
240
241
242
242
243
244
245
248
250

11. Form Handling . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 251
Building Forms
Retrieving Submitted Data
register_globals: An Old Solution Hangs On
Default Values
Input Types
Text Boxes
Text Areas
Checkboxes
Radio Buttons
Hidden Fields
Select
Labels
Sanitizing Input
An Example Program
Test Your Knowledge: Questions


251
253
254
254
256
256
256
257
259
260
260
262
262
264
266

12. Templating with Smarty . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 269
Why Smarty?
Installation
Creating Scripts
Creating Templates
A Practical Example
Test Your Knowledge: Questions

viii | Table of Contents

270
270
271
272

272
277


www.it-ebooks.info
Download at Boykma.Com

13. Cookies, Sessions, and Authentication . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 279
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: Questions

279
281
281
282
282
285
285
289
289

292
293
296

14. Exploring JavaScript . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 299
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
Browser Incompatibilities

Using the DOM
Test Your Knowledge: Questions

299
301
301
302
303
305
305
306
306
307
307
308
308
308
309
309
310
310
310
311
312
312
312
314
316
317
318


Table of Contents | ix


www.it-ebooks.info
Download at Boykma.Com

15. Expressions and Control Flow in JavaScript . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 319
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
Looping
while Loops
do...while Loops
for Loops
Breaking Out of a Loop
The continue Statement
Explicit Casting
Test Your Knowledge: Questions


319
320
321
321
322
323
325
326
327
328
328
329
331
331
331
332
332
333
334
334
335

16. JavaScript Functions, Objects, and Arrays . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 337
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: Questions

337
337
339
341
341
341
343
343
344
346
346
347
348
349
353

17. JavaScript and PHP Validation and Error Handling . . . . . . . . . . . . . . . . . . . . . . . . . . 355
Validating User Input with JavaScript
The validate.html Document (Part One)
x | Table of Contents


355
356


www.it-ebooks.info
Download at Boykma.Com

The validate.html Document (Part Two)
Regular Expressions
Matching Through Metacharacters
Fuzzy Character Matching
Grouping Through Parentheses
Character Classes
Indicating a Range
Negation
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: Questions

358
361
361
362
363
363
364

364
364
367
369
369
369
370
375

18. Using Ajax . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 377
What Is Ajax?
Using XMLHttpRequest
Your First Ajax Program
Using GET Instead of POST
Sending XML Requests
Test Your Knowledge: Questions

378
378
380
385
387
391

19. Using YUI for Ajax and More . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 393
Choosing a Framework
Using YUI
Compressed Versions
Using YUI for Ajax
Other Uses for YUI

A Simple YUI Calendar
Test Your Knowledge: Questions

393
394
396
396
400
401
403

20. Bringing It All Together . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 405
Designing a Social Networking Site
About Third-Party Add-Ons
On the Website
rnfunctions.php
The Functions
rnheader.php
rnsetup.php
index.php
rnsignup.php

405
406
406
406
407
409
410
411

412
Table of Contents | xi


www.it-ebooks.info
Download at Boykma.Com

Checking for Username Availability
rnsignup.php (YUI version)
rncheckuser.php
rnlogin.php
rnprofile.php
Adding the “About Me” Text
Adding a Profile Image
Processing the Image
Displaying the Current Profile
rnmembers.php
Viewing a User’s Profile
Adding and Dropping Friends
Listing All Members
rnfriends.php
rnmessages.php
rnlogout.php

412
415
417
417
419
420

420
420
421
424
424
424
424
427
430
432

A. Solutions to the Chapter Questions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 435
B. Online Resources . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 453
C. MySQL’s FULLTEXT Stopwords . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 457
D. MySQL Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 461
E. Using PEAR and PHPUnit . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 473
Index . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 485

xii | Table of Contents


www.it-ebooks.info
Download at Boykma.Com

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, the JavaScript is important, as it
provides the hidden communication with the web server to create seamless interfaces.

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 three of the core technologies: PHP,
MySQL, and JavaScript.

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 does not assume that you have any prior knowledge of PHP, MySQL, or JavaScript—although if you do, your progress through the
book will be even quicker.

xiii


www.it-ebooks.info
Download at Boykma.Com

Organization of This Book
The chapters in this book are written in a specific order, first introducing all three 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 generating 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 by learning a variety of useful functions and how to manage
cookies and sessions, as well as 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 put together everything you’ve learned in a complete set of PHP 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)
JavaScript: The Definitive Guide by David Flanagan (O’Reilly)

xiv | Preface


www.it-ebooks.info
Download at Boykma.Com

Conventions Used in This Book
The following typographical conventions are used in this book:
Plain text
Indicates menu titles, options, and buttons.
Italic
Indicates new terms, URLs, email addresses, filenames, file extensions, pathnames,
directories, and Unix utilities.
Constant width

Indicates command-line options, variables and other code elements, HTML tags,
macros, the contents of files, and the output from commands.
Constant width bold

Shows commands or other text that should be typed literally by the user; also
occasionally used for emphasis.
Constant width italic

Shows text that should be replaced with user-supplied values.
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, and JavaScript, by
Robin Nixon. Copyright 2009 Robin Nixon, 978-0-596-15713-5.”
If you feel your use of code examples falls outside fair use or the permission given here,
feel free to contact us at
Preface | xv


www.it-ebooks.info
Download at Boykma.Com

We’d Like to Hear from You
Every example in this book has been tested on various platforms, but occasionally you
may encounter problems; for example, if you have a nonstandard installation or a different version of PHP, and so on. The information in this book has also been verified
at each step of the production process. However, mistakes and oversights can occur
and we will gratefully receive details of any you find, as well as any suggestions you
would like to make for future editions. You can contact the author and editors at:
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 available online at:

where you can see all the examples with color-highlighted syntax. To comment or ask
technical questions about this book, send email to the following address, mentioning
its ISBN number (9780596157135):

For more information about our books, conferences, Resource Centers, and the
O’Reilly Network, see our website at:


Safari® Books Online
When you see a Safari® Books Online icon on the cover of your favorite
technology book, that means the book is available online through the
O’Reilly Network Safari Bookshelf.
Safari offers a solution that’s better than e-books. It’s a virtual library that lets you easily
search thousands of top tech books, cut and paste code samples, download chapters,
and find quick answers when you need the most accurate, current information. Try it
for free at .

xvi | Preface


www.it-ebooks.info
Download at Boykma.Com


Acknowledgments
A huge thank you goes to my editor, Andy Oram, and all the folks at O’Reilly who
worked so hard on this book, and without whom it could never have been written.
In particular I must thank my technical reviewers, Derek DeHart, Christoph Dorn,
Tomislav Dugandzic, Becka Morgan, Harry Nixon, Alan Solis, and Demian Turner, for
their help in ensuring the accuracy of this book.
I wish to also thank my wife, Julie, for her constant encouragement, and also Rachel,
Hannah, Laura, Matthew, Harry, and Naomi, wonderful children who all helped with
this project—each in their own way.

Preface | xvii


www.it-ebooks.info
Download at Boykma.Com


www.it-ebooks.info
Download at Boykma.Com

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, so Tim Berners-Lee (a CERN fellow) devised a method of navigating between them using a hyperlinking framework, which came to be known as

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, tools that we now take 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 with 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


www.it-ebooks.info
Download at Boykma.Com

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.
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).
Each step in the request and response sequence is as follows:
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 web page is retrieved by the server and returned 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


www.it-ebooks.info
Download at Boykma.Com

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

consults an additional Internet service called the Domain Name Service (DNS) to find
its associated IP address and then uses it 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).
1.
2.
3.
4.
5.
6.

7.
8.
9.

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.
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.
The PHP interpreter executes the PHP code.
Some of the PHP contains MySQL statements, which the PHP interpreter now
passes to the MySQL database engine.
The MySQL database returns the results of the statements back to the PHP
interpreter.
HTTP and HTML: Berners-Lee’s Basics | 3


www.it-ebooks.info
Download at Boykma.Com

Figure 1-2. A dynamic client/server request/response sequence

10. The PHP interpreter returns the results of the executed PHP code, along with the
results from the MySQL database, to the web server.
11. The web server returns the page to the requesting client, which displays it.
Although it’s helpful to be aware of this process so that you know how the three elements work together, in practice you don’t really need to concern yourself with these
details, because they all happen automatically.
HTML pages returned to the browser in each example may well contain JavaScript,

which will be interpreted locally by the client, and which could initiate another
request—the same way embedded objects such as images would.

4 | Chapter 1: Introduction to Dynamic Web Content


www.it-ebooks.info
Download at Boykma.Com

The Benefits of PHP, MySQL, and JavaScript
At the start of this chapter, I introduced the world of Web 1.0, but it wasn’t long before
the rush was on to create Web 1.1, with the development of such browser enhancements as Java, JavaScript, JScript (Microsoft’s slight variant of JavaScript) and ActiveX.
On the server side, progress was being made on the Common Gateway Interface (CGI)
using scripting languages such as Perl (an alternative to the PHP language) and serverside scripting—inserting the contents of one file (or the output of a system call) into
another one dynamically.
Once the dust had settled, three main technologies stood head and shoulders above
the others. Although Perl was still a popular scripting language with a strong following,
PHP’s simplicity and built-in links to the MySQL database program had earned it more
than double the number of users. And JavaScript, which had become an essential part
of the equation for dynamically manipulating CSS (Cascading Style Sheets) now took
on the even more muscular task of handling the client side of the Ajax process. Under
Ajax, web pages perform data handling and send requests to web servers in the background—without the web user being aware that this is going on.
No doubt the symbiotic nature of PHP and MySQL helped propel them both forward,
but what attracted developers to them in the first place? The simple answer has to be
the ease with which you can use them to quickly create dynamic elements on websites.
MySQL is a fast and powerful yet easy-to-use database system that offers just about
anything a website would need in order to find and serve up data to browsers. When
PHP allies with MySQL to store and retrieve this data, you have the fundamental parts
required for the development of social networking sites and the beginnings of Web 2.0.


Using PHP
With PHP, it’s a simple matter to embed dynamic activity in web pages. When you give
pages the .php extension, they have instant access to the scripting language. From a
developer’s point of view, all you have to do is write code such as the following:
echo "Hello World. Today is ".date("l").". ";
?>
How are you?

The opening following code up to the ?> command. Outside of this construct, everything is sent to
the client as direct HTML. So the text “How are you?” is simply output to the browser;
within the PHP tags, the built-in date function displays the current day of the week
according to the server’s system time.
The final output of the two parts looks like this:
Hello World. Today is Wednesday. How are you?

The Benefits of PHP, MySQL, and JavaScript | 5


×