PHP For The Web: Visual QuickStart Guide Web Quick Start Fifth Edition

User Manual: Pdf

Open the PDF directly: View PDF PDF.
Page Count: 497 [warning: Documents this large are best viewed by clicking the View PDF Link!]

ptg18144795
ptg18144795
Peachpit Press
VISUAL QUICKSTART GUIDE
PHP for
the Web
Fifth Edition
LARRY ULLMAN
ptg18144795
Visual QuickStart Guide
PHP for the Web, Fifth Edition
Larry Ullman
Peachpit Press
1301 Sansome Street
San Francisco, CA 94111
Find us on the web at: www.peachpit.com
To report errors, please send a note to: errata@peachpit.com
Peachpit Press is a division of Pearson Education.
Copyright © 2016 by Larry Ullman
Senior Editor: Karyn Johnson
Development Editor: Robyn G. Thomas
Copyeditor: Liz Welch
Technical Reviewer: Paul Reinheimer
Proofreader: Scout Festa
Production Coordinator: David Van Ness
Compositor: WolfsonDesign
Indexer: Valerie Haynes Perry
Notice of Rights
All rights reserved. No part of this book may be reproduced or transmitted in any form by any means, electronic,
mechanical, photocopying, recording, or otherwise, without the prior written permission of the publisher. For
nformation on getting permission for reprints and excerpts, contact permissions@peachpit.com.
Notice of Liability
The information in this book is distributed on an “As Is” basis, without warranty. While every precaution has
been taken in the preparation of the book, neither the author nor Peachpit Press shall have any liability to any
person or entity with respect to any loss or damage caused or alleged to be caused directly or indirectly by the
instructions contained in this book or by the computer software and hardware products described in it.
Trademarks
Visual QuickStart Guide is a registered trademark of Peachpit Press, a division of Pearson Education. Macintosh
and Mac OS X are registered trademarks of Apple Computer, Inc. Microsoft and Windows are registered
trademarks of Microsoft Corp. Other product names used in this book may be trademarks of their own respective
owners. Images of websites in this book are copyrighted by the original holders and are used with their kind
permission. This book is not officially endorsed by nor affiliated with any of the above companies.
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 Peachpit was aware of a trademark claim,
the designations appear as requested by the owner of the trademark. All other product names and services
identified throughout this book are used in editorial fashion only and for the benefit of such companies with no
intention of infringement of the trademark. No such use, or the use of any trade name, is intended to convey
ndorsement or other affiliation with this book.
ISBN-13: 978-0-134-29125-3
ISBN-10: 0-134-29125-5
9 8 7 6 5 4 3 2 1
Printed and bound in the United States of America
ptg18144795
Dedication
For Jessica, Gina, and Rich, with gratitude for all their love and support.
ptg18144795
Special Thanks to:
Many, many thanks to everyone at Peachpit Press for their assistance
and hard work, especially:
Robyn Thomas, for managing the project adeptly, and for knowing when
to push and poke.
Liz Welch, for fine-tuning my prose with her copyediting skills.
Paul Reinheimer, for the superlative technical review, keeping me honest,
and finding things to improve even in a fifth edition.
Scout Festa, for the sharp proofreading eye.
David Van Ness, who takes a bunch of disparate stuff and turns it into
a book.
Thanks for doing what’s required to create, publish, distribute, market,
sell, and support these books.
My sincerest thanks to the readers of the other editions of this book and
my other books. Thanks for your feedback and support and for keeping
me in business.
Rasmus Lerdorf (who got the PHP ball rolling), the people at PHP.net
and Zend.com, those who frequent the various newsgroups and mailing
lists, and the greater PHP and open source communities for developing,
improving upon, and supporting such wonderfully useful technology.
Zoe and Sam, for continuing to be the kid epitome of awesomeness.
Jessica, for doing everything you do and everything you can.
ptg18144795
Table of Contents v
Table of Contents
Introduction. . . . . . . . . . . . . . . . . . . . . . . . . . ix
Chapter 1 Getting Started with PHP . . . . . . . . . . . . . . . . . 1
Basic HTML Syntax . . . . . . . . . . . . . . . . . . . . . . 2
Basic PHP Syntax . . . . . . . . . . . . . . . . . . . . . . . 7
Using SFTP. . . . . . . . . . . . . . . . . . . . . . . . . . 10
Testing Your Script . . . . . . . . . . . . . . . . . . . . . 12
Sending Text to the Browser . . . . . . . . . . . . . . . . 15
Using the PHP Manual . . . . . . . . . . . . . . . . . . . 18
Sending HTML to the Browser . . . . . . . . . . . . . . . 21
Adding Comments to Scripts. . . . . . . . . . . . . . . . 24
Basic Debugging Steps. . . . . . . . . . . . . . . . . . . 27
Review and Pursue . . . . . . . . . . . . . . . . . . . . . 29
Chapter 2 Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . .31
What Are Variables?. . . . . . . . . . . . . . . . . . . . . 32
Variable Syntax . . . . . . . . . . . . . . . . . . . . . . . 36
Types of Variables . . . . . . . . . . . . . . . . . . . . . . 38
Variable Values . . . . . . . . . . . . . . . . . . . . . . . .41
Understanding Quotation Marks . . . . . . . . . . . . . 44
Review and Pursue . . . . . . . . . . . . . . . . . . . . . 48
Chapter 3 HTML Forms and PHP . . . . . . . . . . . . . . . . . . .49
Creating a Simple Form. . . . . . . . . . . . . . . . . . . 50
Choosing a Form Method. . . . . . . . . . . . . . . . . . 54
Receiving Form Data in PHP . . . . . . . . . . . . . . . . 58
Displaying Errors . . . . . . . . . . . . . . . . . . . . . . 63
Error Reporting . . . . . . . . . . . . . . . . . . . . . . . 65
Manually Sending Data to a Page . . . . . . . . . . . . . 68
Review and Pursue . . . . . . . . . . . . . . . . . . . . . 73
ptg18144795
vi Table of Contents
Chapter 4 Using Numbers . . . . . . . . . . . . . . . . . . . . . . .75
Creating the Form . . . . . . . . . . . . . . . . . . . . . . 76
Performing Arithmetic. . . . . . . . . . . . . . . . . . . . 79
Formatting Numbers . . . . . . . . . . . . . . . . . . . . 83
Understanding Precedence . . . . . . . . . . . . . . . . 86
Incrementing and Decrementing a Number . . . . . . . 88
Review and Pursue . . . . . . . . . . . . . . . . . . . . . 92
Chapter 5 Using Strings . . . . . . . . . . . . . . . . . . . . . . . . .93
Creating the HTML Form . . . . . . . . . . . . . . . . . . 94
Concatenating Strings . . . . . . . . . . . . . . . . . . . 97
Handling Newlines . . . . . . . . . . . . . . . . . . . . . 101
HTML and PHP. . . . . . . . . . . . . . . . . . . . . . . .104
Encoding and Decoding Strings . . . . . . . . . . . . . .108
Finding Substrings . . . . . . . . . . . . . . . . . . . . . 113
Replacing Parts of a String . . . . . . . . . . . . . . . . . 117
Review and Pursue . . . . . . . . . . . . . . . . . . . . .120
Chapter 6 Control Structures. . . . . . . . . . . . . . . . . . . . .121
Creating the HTML Form . . . . . . . . . . . . . . . . . . 122
The if Conditional . . . . . . . . . . . . . . . . . . . . . . 125
Validation Functions . . . . . . . . . . . . . . . . . . . .128
Using else . . . . . . . . . . . . . . . . . . . . . . . . . . 132
More Operators . . . . . . . . . . . . . . . . . . . . . . . 135
Using elseif. . . . . . . . . . . . . . . . . . . . . . . . . .144
The Switch Conditional . . . . . . . . . . . . . . . . . . .148
The for Loop . . . . . . . . . . . . . . . . . . . . . . . . .152
Review and Pursue . . . . . . . . . . . . . . . . . . . . . 157
Chapter 7 Using Arrays . . . . . . . . . . . . . . . . . . . . . . . . 159
What Is an Array? . . . . . . . . . . . . . . . . . . . . . .160
Creating an Array . . . . . . . . . . . . . . . . . . . . . .162
Adding Items to an Array . . . . . . . . . . . . . . . . . .166
Accessing Array Elements . . . . . . . . . . . . . . . . . 170
Creating Multidimensional Arrays . . . . . . . . . . . . . 173
Sorting Arrays . . . . . . . . . . . . . . . . . . . . . . . . 178
Transforming Between Strings and Arrays . . . . . . . .182
Creating an Array from a Form. . . . . . . . . . . . . . .186
Review and Pursue . . . . . . . . . . . . . . . . . . . . . 191
ptg18144795
Table of Contents vii
Chapter 8 Creating Web Applications. . . . . . . . . . . . . . .193
Creating Templates . . . . . . . . . . . . . . . . . . . . .194
Using External Files . . . . . . . . . . . . . . . . . . . . .201
Using Constants . . . . . . . . . . . . . . . . . . . . . . 207
Working with the Date and Time. . . . . . . . . . . . . .211
Handling HTML Forms with PHP, Revisited. . . . . . . .214
Making Forms Sticky . . . . . . . . . . . . . . . . . . . 220
Sending Email . . . . . . . . . . . . . . . . . . . . . . . 228
Output Buffering. . . . . . . . . . . . . . . . . . . . . . 233
Manipulating HTTP Headers . . . . . . . . . . . . . . . 237
Review and Pursue . . . . . . . . . . . . . . . . . . . . . 241
Chapter 9 Cookies and Sessions . . . . . . . . . . . . . . . . . . 243
What Are Cookies? . . . . . . . . . . . . . . . . . . . . 244
Creating Cookies . . . . . . . . . . . . . . . . . . . . . 246
Reading from Cookies . . . . . . . . . . . . . . . . . . . 251
Adding Parameters to a Cookie . . . . . . . . . . . . . 254
Deleting a Cookie . . . . . . . . . . . . . . . . . . . . . 257
What Are Sessions? . . . . . . . . . . . . . . . . . . . . 260
Creating a Session . . . . . . . . . . . . . . . . . . . . . 261
Accessing Session Variables. . . . . . . . . . . . . . . 264
Deleting a Session . . . . . . . . . . . . . . . . . . . . 266
Review and Pursue . . . . . . . . . . . . . . . . . . . . 268
Chapter 10 Creating Functions . . . . . . . . . . . . . . . . . . . . 269
Creating and Using Simple Functions. . . . . . . . . . 270
Creating and Calling Functions That Take Arguments 276
Setting Default Argument Values . . . . . . . . . . . . 282
Creating and Using Functions That Return a Value . . 285
Understanding Variable Scope . . . . . . . . . . . . . 290
Review and Pursue . . . . . . . . . . . . . . . . . . . . 296
Chapter 11 Files and Directories . . . . . . . . . . . . . . . . . . . 297
File Permissions . . . . . . . . . . . . . . . . . . . . . . 298
Writing to Files . . . . . . . . . . . . . . . . . . . . . . . 303
Locking Files . . . . . . . . . . . . . . . . . . . . . . . . .310
Reading from Files. . . . . . . . . . . . . . . . . . . . . .313
Handling File Uploads . . . . . . . . . . . . . . . . . . .316
Navigating Directories . . . . . . . . . . . . . . . . . . 325
ptg18144795
viii Table of Contents
Creating Directories. . . . . . . . . . . . . . . . . . . . 330
Reading Files Incrementally . . . . . . . . . . . . . . . 338
Review and Pursue . . . . . . . . . . . . . . . . . . . . 343
Chapter 12 Intro to Databases . . . . . . . . . . . . . . . . . . . . 345
Introduction to SQL . . . . . . . . . . . . . . . . . . . . 346
Connecting to MySQL. . . . . . . . . . . . . . . . . . . 348
MySQL Error Handling . . . . . . . . . . . . . . . . . . 352
Creating a Table . . . . . . . . . . . . . . . . . . . . . . 355
Inserting Data into a Database. . . . . . . . . . . . . . 360
Securing Query Data . . . . . . . . . . . . . . . . . . . 366
Retrieving Data from a Database . . . . . . . . . . . . . 371
Deleting Data in a Database . . . . . . . . . . . . . . . 376
Updating Data in a Database. . . . . . . . . . . . . . . 382
Review and Pursue . . . . . . . . . . . . . . . . . . . . 388
Chapter 13 Putting It All Together . . . . . . . . . . . . . . . . . .389
Getting Started . . . . . . . . . . . . . . . . . . . . . . 390
Connecting to the Database . . . . . . . . . . . . . . . 392
Writing the User-Defined Function . . . . . . . . . . . 393
Creating the Template . . . . . . . . . . . . . . . . . . 396
Logging In . . . . . . . . . . . . . . . . . . . . . . . . . 400
Logging Out . . . . . . . . . . . . . . . . . . . . . . . . 404
Adding Quotes. . . . . . . . . . . . . . . . . . . . . . . 405
Listing Quotes . . . . . . . . . . . . . . . . . . . . . . . 409
Editing Quotes . . . . . . . . . . . . . . . . . . . . . . . .412
Deleting Quotes . . . . . . . . . . . . . . . . . . . . . . .418
Creating the Home Page . . . . . . . . . . . . . . . . . 422
Review and Pursue . . . . . . . . . . . . . . . . . . . . 426
Appendix A Installation and Configuration . . . . . . . . . . . . .427
Appendix B Resources and Next Steps . . . . . . . . . . . . . . . 449
Index . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 459
ptg18144795
When I began the first edition of this book
in 2000, PHP was a little-known
open
source
project. It was adored by technical
people in the know but not yet recognized
as the popular choice for web development
that it is today. When I taught myself PHP,
very little documentation was available on
the language—and that was my motivation
for writing this book in the first place.
Today things are different. The Internet
has gone through a boom and a bust and
has righted itself. Furthermore, PHP is now
the reigning king of dynamic web design
tools and has expanded somewhat beyond
the realm of just web development. But
despite PHP’s popularity and the increase
in available documentation, sample code,
and examples, a good book discussing the
language is still relevant. Although PHP is
in the beginnings of its sixth major release,
a book such as this—which teaches the
language in simple but practical terms—
can still be your best guide in learning the
information you need to know.
Introduction
This book will teach you PHP, providing
both a solid understanding of the funda-
mentals and a sense of where to look for
more advanced information. Although it
isn’t a comprehensive programming refer-
ence, this book, through demonstrations
and real-world examples, provides the
knowledge you need to begin building
dynamic websites and web applications
using PHP.
What Is PHP?
PHP originally stood for
Personal Home
Page.
It was created in 1994 by Rasmus
Lerdorf to track the visitors to his online
résumé. As its usefulness and capabilities
grew (and as it began to be utilized in more
professional situations), PHP came to mean
PHP: Hypertext Preprocessor
. The defini-
tion basically means that PHP handles data
before it becomes HTML—which stands for
Hypertext Markup Language.
ptg18144795
x Chapter
According to the official PHP website,
found at www.php.net A, PHP is “a popu-
lar general-purpose scripting language
that is especially suited to web develop-
ment.” More specifically, PHP is a scripting
language commonly embedded within
HTML. Let’s examine what this means in
more detail.
To say that PHP
can be embedded into
HTML
means that PHP code can be written
within your HTML code—HTML being the
language with which all web pages are
built. Therefore, programming with PHP
starts off as only slightly more complicated
than hand-coding HTML.
Also, PHP is a
scripting language
, as
opposed to a
compiled language
. This
means that PHP is designed to do some-
thing
only after an event occurs
—for
example, when a user submits a form or
goes to a URL (Uniform Resource Locator—
the technical term for a web address).
Another popular example of a scripting
language is JavaScript, which commonly
handles events that occur within the
browser. Both PHP and JavaScript can also
be described as
interpreted
, because the
code must be run through an executable,
such as the PHP module or the browser’s
JavaScript component. Conversely, com-
piled languages such as C and C++ can be
used to write stand-alone applications that
can act independently of any event.
A As of this writing, this is the appearance of
the official PHP website, located at www.php.net.
Naturally, this should be the first place you look
to address most of your PHP questions and
curiosities.
PHP 6?
Yes, as of this writing, the current ver-
sions of PHP were 5 and 7, but not 6!
There’s a long and amusing story here,
but the short version is that PHP 6 was
actively developed for a while. After hit-
ting many snags, the development was
halted and the created work was rolled
into PHP 5.
When it became time to work on the
next major version, after much debate
it was decided that that version would
be named PHP 7. So although there was
once a beta version of PHP 6, no final
release ever saw the light of day.
ptg18144795
Introduction xi
You should also understand that PHP is a
server-side
technology. This refers to the
fact that everything PHP does occurs on
the server (as opposed to on the
client
,
which is the computer being used by the
person viewing the website). A
server
is just a computer set up to provide the
pages you see when you go to a web
address with your browser. I’ll discuss this
process in more detail later in this introduc-
tion (see “How PHP Works”).
Finally, PHP is
cross-platform
, meaning
that it can be used on machines running
Unix, Windows, Macintosh, and other oper-
ating systems. Again, we’re talking about
the
server’s
operating system, not the cli-
ent’s. Not only can PHP run on almost any
operating system, but, unlike many other
programming languages, it enables you
to switch your work from one platform to
another with few or no modifications.
As of this writing, PHP is simultaneously in
versions 5.5.35, 5.6.21, and 7.0.6. (There
are slight differences between versions
5.5 and 5.6, so 5.5 continues to be sup-
ported for a while.) Although I wrote this
book using a stable version of PHP 7, all
of the code is backward compatible, at
least to PHP version 5.
x
. In a couple of
situations where a feature requires a more
current version of PHP, or where older
versions might have slight variations, a
note in a sidebar or a tip will indicate how
you can adjust the code accordingly.
More information can be found at PHP.net
and Zend (www.zend.com), a key company
involved with PHP development B.
B This Zend website contains useful software as
well as a code gallery and well-written tutorials.
What PHP Is Not
The thing about PHP that confuses
most new learners is what PHP can’t do.
Although you can use the language for
an amazing array of tasks, its main limita-
tion is that PHP cannot be used for client-
side features found in some websites.
Using a client-side technology like
JavaScript, you can create a new
browser window, make pop-up dialogs,
dynamically generate and alter forms,
and much more. None of these tasks can
be accomplished using PHP because
PHP is server-side, whereas those are
client-side issues. But you can use PHP
to create JavaScript, just as you can use
PHP to create HTML.
When it comes time to develop your own
PHP projects, remember that you can
use PHP only to send information (HTML
and such) to the browser. You can’t do
anything else within the browser until
another request from the server has
been made (a form has been submitted
or a link has been clicked).
ptg18144795
xii Chapter
Why Use PHP?
Put simply, PHP is better, faster, and easier
to learn than the alternatives. All websites
must begin with just HTML, and you can
create an entire site using a number of
static HTML pages. But basic HTML is a
limited approach that does not allow for
flexibility or dynamic behavior. Visitors
accessing HTML-only sites see simple pages
with no level of customization or dynamic
behavior. With PHP, you can create exciting
and original pages based on whatever
factors you want to consider. PHP can also
interact with databases and files, handle
email, and do many other things that HTML
alone cannot.
Web developers learned a long time ago
that HTML alone won’t produce enticing
and lasting websites. Toward this end,
server-side technologies such as PHP have
become the norm. These technologies
allow developers to create web applica-
tions that are dynamically generated,
taking into account whichever elements
the programmer desires. Often database-
driven, these advanced sites can be
updated and maintained more readily than
static HTML pages.
When it comes to choosing a server-side
technology, the primary alternatives A to
PHP are: ASP.NET (Active Server Pages),
JSP (JavaServer Pages), Ruby (through the
Rails or Sinatra frameworks), and some
newer server-side JavaScript options such
as Node.js.
A The Web Technology Surveys site says that
PHP is running on 82 percent of all websites
(http://w3techs.com/technologies/overview/
programming_language/all).
ptg18144795
Introduction xiii
n
PHP is both free and cross-platform.
Therefore, you can learn and use PHP
on nearly any computer and at no cost.
Furthermore, its open source nature
means that PHP’s users are driving its
development, not some corporate entity.
n
PHP is the most popular tool available
for developing dynamic websites. As
of this writing, PHP is in use on over 82
percent of all websites A and is the
sixth most popular programming lan-
guage overall B. Many of the biggest
websites—Yahoo, Wikipedia, and
Facebook, just to name three—and
content management tools, such as
WordPress, Drupal, Moodle, and Joomla,
use PHP. By learning this one language,
you’ll provide yourself with either a
usable hobby or a lucrative skill.
So the question is, why should a web
developer use PHP instead of ASP.NET,
Node.js, or whatever else to make a
dynamic website?
n
PHP is much easier to learn and use.
People—perhaps like you—without
any formal programming training can
write PHP scripts with ease after read-
ing this one book. In comparison,
ASP.NET requires an understanding of
Visual Basic, C#, or another language;
Node.js requires JavaScript. These are
more complex languages and are much
more difficult to learn.
n
PHP was written specifically for
dynamic web page creation. Perl,
VBScript, Java, and Ruby were not, and
this fact suggests that, by its very intent,
PHP can do certain tasks faster and
more easily than the alternatives. I’d like
to make it clear, however, that although
I’m suggesting that PHP is
better for
certain things
—specifically those it
was created to do, PHP isn’t a “better”
programming language than JavaScript
or C#—they can do things PHP can’t.
B The Tiobe Index (www.tiobe.com/tiobe_index) uses a combination of factors to rank the popularity of
programming languages.
ptg18144795
xiv Chapter
browser, there may or may not be an obvi-
ous difference between what
home.html
and
home.php
look like, but how you arrive
at that point is critically altered. The major
difference is that by using PHP, you can
have the server
dynamically
generate the
HTML code. For example, different infor-
mation could be presented if it’s Monday as
opposed to Tuesday or if the user has visited
the page before. Dynamic web page creation
sets apart the less appealing, static sites
from the more interesting, and therefore
more visited, interactive ones.
The central difference between using PHP
and using straight HTML is that PHP does
everything on the server and then sends
the appropriate information to the browser.
This book covers how to use PHP to send
the right data to the browser.
How PHP Works
PHP is a server-side language, which
means the code you write in PHP resides
on a host computer that serves web pages
to browsers. When you go to a website
(www.LarryUllman.com, for example), your
Internet service provider (ISP) directs
your request to the server that holds the
www.LarryUllman.com information. That
server reads the PHP code and processes
it according to its scripted directions. In
this example, the PHP code tells the server
to send the appropriate web page data to
your browser in the form of HTML A. In
short, PHP creates an HTML page on the
fly based on parameters of your choosing.
This differs from an HTML-generated
site in that when a request is made, the
server merely sends the HTML data to
the browser—no server-side interpreta-
tion occurs B. Hence, to the end user’s
URL Request
HTML
Client Server
PHP
HTML
Script
Request
A This graphic demonstrates (albeit in
very simplistic terms) how the process
works between a client, the server, and
a PHP module (an application added to
the server to increase its functionality)
to send HTML back to the browser.
URL Request
HTML
Client Server B Compare this direct relationship of
how a server handles basic HTML to
A. This is also why HTML pages can
be viewed in your browser from your
own computer—they don’t need to be
“served,” but dynamically generated
pages need to be accessed through a
server that handles the processing.
ptg18144795
Introduction xv
What You’ll Need
The most important requirement for work-
ing with PHP—because it’s a server-side
scripting language—is access to a PHP-
enabled server. Considering PHP’s popu-
larity, your web host most likely has this
option available to you on their servers.
You’ll need to contact them to see what
technology they support.
Your other option is to install PHP and a
web server application (like Apache) on
your own computer. Users of Windows,
Mac OS X, or Linux can easily install and
use PHP for no cost. Directions for install-
ing PHP are available in Appendix A,
“Installation and Configuration.” If you’re up
to the task of using your own PHP-installed
server, you can take some consolation in
knowing that PHP is available for free from
the PHP website (www.php.net) and comes
in easy-to-install packages. If you take this
approach, and I recommend that you do,
then your computer will act as both the
client and the server.
The second requirement is almost a
given: You must have a text editor on your
computer. Atom, Notepad++, UltraEdit,
and similar freeware applications are all
sufficient for your purposes, and TextMate,
SublimeText, and other commercial appli-
cations offer more features that you may
appreciate. If you’re accustomed to using
a graphical interface (also referred to as
WYSIWYG—What You See Is What You Get)
such as Adobe Dreamweaver A or Aptana
Studio, you can consult that applications
manual to see how to program within it.
continues on next page
A The popular Dreamweaver application supports
PHP development, among other server-side
technologies.
ptg18144795
xvi Chapter
Third, you need a method of getting the
scripts you write to the server. If you’ve
installed PHP on your own computer,
you can save the scripts to the appropri-
ate directory. However, if you’re using a
remote server with a web host, you’ll need
an SFTP (Secure File Transfer Protocol)
program to send the script to the server.
There are plenty of SFTP applications avail-
able; for example, in Chapter 1, “Getting
Started with PHP,” I use the free FileZilla
(http://filezilla-project.org B).
Finally, if you want to follow the examples in
Chapter 12, “Intro to Databases,” you need
access to MySQL (www.mysql.com C).
MySQL is available in a free version that
you can install on your own computer.
This book assumes only a basic knowledge
of HTML, although the more comfortable
you are handling raw HTML code
without
the aid of a WYSIWYG application such
as Dreamweaver, the easier the transition
to using PHP will be. Every programmer
will eventually turn to an HTML reference
at some time or other, regardless of how
much you know, so I encourage you to
keep a good HTML book by your side.
One such introduction to HTML is Elizabeth
Castro and Bruce Hyslop’s
HTML, XHTML,
and CSS: Visual QuickStart Guide
(Peachpit Press, 2014).
Previous programming experience is
certainly not required. However, it may
expedite your learning because you’ll
quickly see numerous similarities between,
for example, Perl and PHP or JavaScript
and PHP.
B The FileZilla application can be used on many
different operating systems to move PHP scripts
and other files to a remote server.
C MySQLs website (as of this writing).
ptg18144795
Introduction xvii
About This Book
This book attempts to convey the funda-
mentals of programming with PHP while
hinting at some of the more advanced
features you may want to consider in the
future, without going into overwhelming
detail. It uses the following conventions to
do so.
The step-by-step instructions indicate what
coding you’re to add to your scripts and
where. The specific text you should type
is printed in a unique type style to separate
it from the main body text. For example:
<?php print "Hello, World!"; ?>
The PHP code is also written as its own
complete script and is numbered by line for
reference (Script i.1). You shouldn’t insert
these line numbers yourself, because
doing so will render your work inoperable.
I recommend using a text editor that
automatically displays the line numbers for
you—the numbers will help when you’re
debugging your work. In the scripts, you’ll
sometimes see particular lines highlighted
in bold, in order to draw attention to new or
relevant material.
Script i.1 A sample PHP script, with line numbers
and bold emphasis on a specific section of code.
1 <!doctype html>
2 <html lang="en">
3 <head>
4 <meta charset="utf-8">
5 <title>Hello, World!</title>
6 </head>
7 <body>
8 <?php print "Hello, world!"; ?>
9 </body>
10 </html>
What’s New in This Book?
I would consider this fifth edition to be a
modest revision of an already solid book.
The biggest changes are
.All examples now use HTML5.
.The MySQL code uses the most
current version of PHP’s MySQL
extension.
.We cover PHP 7, as applicable.
Finally, I tweaked some of the examples
mostly to satisfy my own drive for perfec-
tion. No content from the previous edi-
tion has been removed.
ptg18144795
xviii Chapter
Because of the nature of how PHP works,
you need to understand that there are
essentially three views of every script: the
PHP code (e.g., Script i.1), the code that’s
sent to the browser (primarily HTML), and
what the browser displays to the end user.
Where appropriate, sections of, or all of,
the browser window are revealed, showing
the result of the exercise A. Occasionally,
you’ll also see an image displaying the
HTML source that the browser received B.
You can normally access this view by choos-
ing View Source or View Page Source
from the appropriate browser menu. To
summarize, B displays the HTML the
browser receives, and A demonstrates
how the browser interprets that HTML.
Using PHP, you’ll create the HTML that’s
sent to the browser.
A This is a sample view you’ll see of the browser
window. For the purposes of this book, it won’t
make any difference which browser or operating
system you use.
B By viewing the source code received by the
browser, you can see the HTML created by PHP
and sent by the server.
ptg18144795
Introduction xix
Because the columns in this book are nar-
rower than the common text editor screen,
sometimes lines of PHP code printed in the
steps have to be broken where they would
not otherwise break in your editor. A small
gray arrow indicates when this kind of
break occurs. For example:
print "This is going to be a longer
line of code.";
You should continue to use one line in
your scripts, or else you’ll encounter errors
when executing them. (The gray arrow isn’t
used in scripts that are numbered.)
While demonstrating new features and
techniques, I’ll do my best to explain the
why’s and how’s of them as I go. Between
reading about and using a function, you
should clearly comprehend it. Should
something remain confusing, though, this
book contains a number of references
where you can find answers to any ques-
tions (see Appendix B, “Resources and
Next Steps”). If you’re confused by a par-
ticular function or example, your best bet
will be to check the online PHP manual or
the book’s supporting website (and its user
support forum).
ptg18144795
xx Chapter
Companion Website
While you’re reading this book, you may
also find it helpful to visit the
PHP for the
Web: Visual QuickStart Guide, 5th Edition
website, found within www.LarryUllman.com.
There you’ll find every script in this book
available in a downloadable form. However,
I strongly encourage you to type the scripts
yourself in order to become more familiar
with the structure and syntax of PHP. The
site also provides an errata page listing any
mistakes made in this text.
What many users find most helpful, though,
is the book’s supporting forum, found
through the website or more directly at
www.LarryUllman.com/forums/. Using the
forum, you can
n
Find answers to problems you’re having
n
Receive advice on how to approach an
idea you have
n
Get debugging help
n
See how changes in the technologies
have affected the examples in the book
n
Learn what other people are doing
with PHP
n
Confirm the answers to review questions
n
Receive a faster reply from me than if
you send me a direct email
Which Book Is Right for You?
This is the fifth edition of my first book
on PHP. Like the original, it’s written with
the beginner or nonprogrammer in mind.
If you have little or no programming
experience, prefer a gentler pace, or like
to learn things in bite-sized pieces, this is
the book for you. Make no mistake: This
book covers what you need to know to
begin developing dynamic websites and
uses practical examples, but it does so
without any in-depth theory or advanced
applications.
Conversely, if you pick up new tech-
nologies really quickly or already have
some experience developing websites,
you may find this to be too basic. In that
case, you should consider my
PHP and
MySQL for Dynamic Web Sites: Visual
QuickPro Guide
instead (Peachpit Press,
2012). It discusses SQL and MySQL in
much greater detail and goes through
several more complex examples, but it
does so at a quick jog.
ptg18144795
Introduction xxi
Questions, comments,
or suggestions?
If you have a PHP-specific question, there
are newsgroups, mailing lists, and ques-
tion-and-answer sections available on PHP-
related websites for you to turn to. These
are discussed in more detail in Appendix B.
Browsing through these references or
searching the Internet will almost always
provide you with the fastest answer.
You can also direct your questions, com-
ments, and suggestions to me. You’ll get
the fastest reply using the book’s cor-
responding forum; I always answer those
questions first. If you’d rather email me,
you can do so through the contact page on
the website. I do try to answer every email
I receive, but it will probably take a week or
two (whereas you’ll likely get a reply in the
forum within a couple of days).
For more tips and an enlightening read,
see the sidebar on this page and Eric
Steven Raymond’s “How to Ask Questions
the Smart Way,” at www.catb.org/~esr/faqs/
smart-questions.html. The 10 minutes
you spend on it will save you hours in
the future. Those people who will answer
your questions, like myself, will be most
appreciative!
How to Ask Questions the
Smart Way
Whether you’re posting a message to the
books supporting forum, sending me an
email, or asking a question in a news-
group, knowing how to most effectively
ask a question improves the quality of
the response you’ll receive as well as the
speed with which you’ll get your answer.
To receive the best answer in the short-
est amount of time, follow these steps:
1. Search the Internet, read the manu-
als, and browse any applicable
documentation.
2. Ask your question in the most appro-
priate forum (newsgroup, mailing list,
and so on).
3. Use a clear and concise subject.
4. Describe your problem in detail, show
any relevant code, say what went
wrong, indicate what version of PHP
you’re using, and state what operat-
ing system you’re running.
ptg18144795
This page intentionally left blank
ptg18144795
When learning any new programming lan-
guage, always begin with an understanding
of the basic syntax and functionality, which
is what you’ll learn in this chapter. The
focus here is on the fundamentals of HTML
and PHP, and how the two languages work
together. The chapter also covers some
recommended programming and debugging
techniques, the use of which will greatly
ease the learning process.
If you’ve never programmed before, a
focused reading of this chapter will start
you on the right track. If you have some
programming experience, you’ll be able to
breeze through these pages, gaining a per-
spective for the book’s remaining material.
By the end of this chapter you will have
successfully written and executed your first
PHP scripts and be on your way to devel-
oping dynamic web applications.
1
Getting Started
with PHP
In This Chapter
Basic HTML Syntax 2
Basic PHP Syntax 7
Using SFTP 10
Testing Your Script 12
Sending Text to the Browser 15
Using the PHP Manual 18
Sending HTML to the Browser 21
Adding Comments to Scripts 24
Basic Debugging Steps 27
Review and Pursue 29
ptg18144795
2 Chapter 1
Basic HTML Syntax
All web pages are made using HTML
(Hypertext Markup Language). Every web
browser, be it Google’s Chrome, Mozilla’s
Firefox, Microsoft’s Internet Explorer and
Edge, or Apple’s Safari, turns HTML code—
<h1>Hello, World!</h1>
I just wanted to say <em>Hello</em>.
—into the web page presented to the
user A.
As of this writing, the current version of
HTML is 5, which should remain the norm
for some time to come (it was officially
standardized in 2014). HTML5 is a solid
and practical version of the language, well
suited for today’s web.
Before getting into the syntax of PHP, let’s
create one simple but valid HTML document
that can act as a template for many of this
book’s examples.
A How one web browser renders the
HTML code.
ptg18144795
Getting Started with PHP 3
Basic CSS
HTML elements define a page’s content, but formatting the look and behavior of such content is
left to CSS (Cascading Style Sheets). As with HTML, this book does not teach CSS in any detail, but
because some of the book’s code uses CSS, you should be familiar with its basic syntax.
You can add CSS to a web page in a couple of ways. The first, and easiest, method is to use HTML
style tags:
<style type="text/css">
/* rules */
</style>
The CSS rules are defined between the opening and closing style tags.
You can also use the
link
HTML tag to incorporate CSS rules defined in an external file:
<link href="styles.css" rel="stylesheet" type="text/css">
That file would contain only the rules, without the style tags.
CSS rules are applied to combinations of general page elements, CSS classes, and specific items:
img { border: 0px; }
.error { color: red; }
#about { background-color: #ccc; }
The first rule applies to every image tag. The second applies to any element that has a class
of
error
:
<p class="error">Error!</p>
The third rule applies only to the specific element that has an
id
value of
about
:
<p id="about">About...</p>
(Not all elements need to have an
id
attribute, but no two elements should have the same
id
value.)
For the most part, this book uses CSS only to do simple things, such as changing the color or back-
ground color of an element or some text.
For more on CSS, search the web or see a dedicated book on the subject.
ptg18144795
4 Chapter 1
To create an HTML page:
1. Open your text editor or integrated
development environment (IDE).
You can use pretty much any applica-
tion to create HTML and PHP pages.
Popular choices include
> Adobe’s Dreamweaver
(www.adobe.com)
> Aptana Studio (www.aptana.com)
> PhpStorm (www.jetbrains.com)
> Sublime Text (www.sublimetext.com)
> Atom (https://atom.io)
The first three are IDEs, making them
more complicated to use but also more
powerful. The last two are text editors.
All these programs run on most common
operating systems.
2. Choose File > New to create a new,
blank document.
Some text editors allow you to start by
creating a new document of a certain
type—for example, a new HTML file B.
If your application has this option, use it!
3. Start with the HTML header lines
(Script 1.1):
<!doctype html>
<html lang="en">
A valid HTML5 document begins with
these lines. They tell the web browser
what type of document to expect. For
this template, and in this entire book,
HTML5
pages will be created. One of
the niceties of HTML5 is its minimal
doctype and syntax.
B PhpStorm and most
other web development
applications can create the
basics of an HTML document
for you.
Script 1.1 This simple document contains the
basics of an HTML5 page.
1 <!doctype html>
2 <html lang="en">
3 <head>
4 <meta charset="utf-8">
5 <title>Welcome to this Page!</title>
6 </head>
7 <body>
8 <h1>This is a basic HTML page!</h1>
9 <br>
10 <p>Even with <em>some</em> decoration,
it's still not very exciting.</p>
11 </body>
12 </html>
ptg18144795
Getting Started with PHP 5
4. Create the head section of the page:
<head>
<meta charset="utf-8">
<title>Welcome to this Page!
</title>
</head>
The head of an HTML page should
include the
charset
meta tag. The
“Understanding Encoding” sidebar dis-
cusses what this means in more detail.
The head also contains the page’s
title, which appears at the top of the
browser window or tab, as well as in
the browser’s bookmarks and history.
You can also place JavaScript and CSS
references in the head.
5. Create the body section:
<body>
<h1>This is a basic HTML page!
</h1>
<br>
<p>Even with <em>some</em>
decoration, it's still not
very exciting.</p>
</body>
The page’s content—what is shown in
the browser—goes between opening
and closing
body
tags.
6. Complete the page with a closing
HTML tag:
</html>
continues on next page
Understanding Encoding
Encoding is a huge subject, but what
you most need to understand is this:
The encoding you use in a file dictates
what characters can be represented
(and therefore, what written languages
you can use). To select an encoding, you
must first confirm that your text editor
or IDE can save documents using that
encoding. Some applications let you
set the encoding in the preferences or
options area; others set the encoding
when you save the file.
To indicate the encoding to the browser,
there’s a corresponding
meta
tag:
<meta charset="utf-8">
The
charset=utf-8
part says that
UTF-8 (short for 8-bit Unicode Transfor-
mation Format) encoding is being used.
Unicode is a way of reliably representing
every symbol in every alphabet. Version
8.0.0 of Unicodethe current version as
of this writing—supports over 120,000
characters! The most commonly used
Unicode encoding is UTF-8.
If you want to create a multilingual web
page, UTF-8 is the way to go, and it’ll be
used in this book’s examples. You don’t
have to, of course. But whatever encod-
ing you do use, make sure the encoding
indicated by the HTML page matches the
actual encoding used by the text editor
or IDE. If you don’t, you’ll likely see odd
characters when viewing the page in a
web browser.
ptg18144795
6 Chapter 1
7. Choose File > Save As. In the dialog
box that appears, choose Text Only
(or ASCII) for the format, if you’re given
the option.
HTML and PHP documents are just
plain text files (unlike, for example, a
Microsoft Word document, which is
stored in a proprietary, binary format).
You may also need to indicate the
encoding (
utf-8
) when you save the
file (again, see the “Understanding
Encoding” sidebar).
8. Navigate to the location where you
wish to save the script.
You can place this script anywhere
you’d like on your computer, although
using one dedicated folder for every
script in this book, perhaps with sub-
folders for each chapter, makes sense.
9. Save the file as
welcome.html
.
HTML5 pages use the standard
.html
extension.
10. Test the page by viewing it in your
browser C.
Unlike with PHP scripts (as you’ll soon
discover), you can test HTML pages by
opening them directly in a browser.
Search the web or use the book’s sup-
port forum (www.LarryUllman.com/forums/) to
find a good HTML and PHP editor or IDE.
For more information on HTML, check out
Elizabeth Castro and Bruce Hyslop’s excellent
book HTML and CSS, Eighth Edition: Visual
QuickStart Guide (Peachpit Press, 2014).
C The HTML page, as interpreted by the browser.
ptg18144795
Getting Started with PHP 7
Basic PHP Syntax
Now that you’ve seen how HTML will be
handled in this book, it’s time to begin
PHP scripting. To create a PHP page, you’ll
start exactly as you would if you were
creating an HTML document from scratch.
Understanding the reason for this is vitally
important: Web browsers are client appli-
cations that understand HTML;
PHP is a
server-side technology
that cannot run in
the client. To bridge this gap, PHP is used
on the server to generate HTML that’s run
in a browser (refer to the section “How
PHP Works” in this book’s “Introduction” for
a visual representation of this relationship).
There are three main differences between
a standard HTML page and a PHP script.
First, PHP scripts should be saved with the
.php
file extension (for example,
index.php
).
Second, you place PHP code within
<?php
and
?>
tags, normally within the context of
some HTML:
...
<body><h1>This is HTML.</h1>
<?php PHP code! ?>
<p>More HTML</p>
...
The PHP tags indicate the parts of the
page to be run through the PHP processor
on the server. This leads to the third major
difference:
PHP scripts must be run on a
PHP-enabled web server
(whereas HTML
pages can be viewed on any computer,
directly in a browser). This means that
PHP scripts must always be run through
a URL
(for example, http://example.com/
page.php). If you’re viewing a PHP script in
a web browser and the address does not
begin with
http
, the PHP script will not work.
ptg18144795
8 Chapter 1
To make this first PHP script do something
without too much programming fuss, you’ll
use the
phpinfo()
function. This function,
when called, sends a table of information to
the web browser. That table lists the specif-
ics of the PHP installation on that particular
server. It’s a great way to test your PHP
installation and has a high “bang for your
buck” quality.
However, the
phpinfo()
function not only
outputs a table of information, it also creates
a complete HTML page for you. So this first
PHP script does not require the standard
HTML code, although subsequent scripts in
this chapter will.
To create a new PHP script
on your computer:
1. Create a new PHP document in
your text editor or IDE, to be named
phpinfo.php
(Script 1.2).
For this specific case, you’ll start with a
blank file. But if your text editor or IDE
has PHP file templates for you, you can
certainly start with one of those.
2. Begin the page with
<?php
on its
own line.
This opening PHP tag tells the server
that the following code is PHP and
should be handled as such.
If your application has a PHP template
for you, it may have created the PHP
tags already.
Script 1.2 This first PHP script invokes a single
PHP function.
1 <?php
2 phpinfo();
3 ?>
ptg18144795
Getting Started with PHP 9
Just as a file’s extension on your computer
tells the operating system in what application
to open the file, a web page’s extension tells
the server how to process the file:
file.php
goes through the PHP module,
file.aspx
is
processed as ASP.NET, and
file.html
is a
static HTML document (normally). The exten-
sion associations are determined by the web
server’s settings.
If you’re developing PHP scripts for a
hosted website, check with your hosting com-
pany to learn which file extensions you can
use for PHP documents. In this book you’ll see
.php
, the most common extension.
You’ll occasionally see PHP’s short tags
simply
<?
and
?>
—used in other people’s
scripts, although I recommend sticking with
the formal tags:
<?php
and
?>
. Support for the
short tags must be enabled on a server, and
using them makes your code less portable.
You’ll find it handy to have a copy of the
phpinfo.php
file around. As you’ll soon see,
this script reports upon PHP’s capabilities,
settings, and other features of your server.
In fact, this book frequently suggests you
return to this script for those purposes.
PHP scripts can also be executed with-
out a web browser, using a command-line
interface and a standalone PHP executable.
But that topic is well outside the scope of this
book (and it’s a much less common use of PHP
regardless).
3. Add the following on the next line:
phpinfo();
The syntax will be explained in detail
later, but in short, this is just a call to an
existing PHP function named
phpinfo
.
You must use the opening and closing
parentheses, with nothing between
them, and the semicolon.
4. Type
?>
on its own line, as the last line.
The closing PHP tag tells the server that
the PHP section of the script is over.
Again, because the
phpinfo()
function
generates a complete HTML page for
you, no HTML tags are needed.
5. Save the script as
phpinfo.php
.
Not to overstate the point, but remem-
ber that PHP scripts must use a valid
file extension. Most likely you’ll have
no problems if you save your files as
filename.php
.
You also need to be certain that the
application or operating system is not
adding a hidden extension to the file.
Notepad on Windows, for example,
attempts to add
.txt
to uncommon
file extensions, which renders the PHP
script unusable. (Generally speaking,
do not use Notepad.)
ptg18144795
10 Chapter 1
Using SFTP
Unlike HTML, which can be tested directly
in a browser, PHP scripts need to be run
from a PHP-enabled server in order to
see the results. Specifically, PHP is run
through a
web server application
, such
as Apache (http://httpd.apache.org), Nginx
(www.nginx.com), or Internet Information
Server (IIS; www.iis.net).
You can obtain a PHP-enabled server in
one of two ways:
n
Install the software on your own
computer.
n
Acquire web hosting.
PHP is open source software (meaning,
in part, that it’s free) and is generally easy
to install (with no adverse effect on your
computer). If you want to install PHP and
a web server on your computer, follow the
directions in Appendix A, “Installation and
Configuration.” Once you’ve done so, you
can skip ahead to the next section of the
chapter, where you’ll learn how to test your
first PHP script.
A The connection section of FileZilla’s main window (as it appears on the Mac).
B The reported error says that the connection attempt was refused.
If you’re not running PHP on your own
computer, you’ll need to transfer your PHP
scripts to the PHP-enabled server using
SFTP (Secure File Transfer Protocol). The web
hosting company or server’s administrator
will provide you with SFTP access informa-
tion, which you’ll enter into an SFTP client.
Many SFTP client applications are available;
this next sequence of steps uses the free
FileZilla (http://filezilla-project.org), which
runs on many operating systems.
To SFTP your script to the server:
1. Open your SFTP application.
2. In the application’s connection window,
enter the information provided by your
web host A.
SFTP access requires a host (for exam-
ple, the domain name or an IP address),
username, and password.
3. Click Quickconnect (or your SFTP
client’s equivalent).
If you’ve provided the correct informa-
tion, you should be able to connect. If
not, you’ll see error messages at the
top of the FileZilla window B.
ptg18144795
Getting Started with PHP 11
5. Upload your script—
phpinfo.php
—to
the server.
To do this in FileZilla, drag the file from
the left column—your computer—to the
right column—the server.
Some text editors and IDEs have built-in
SFTP capability, allowing you to save your
scripts directly to the server. Other applica-
tions can run PHP scripts without leaving the
application at all.
You can also transfer files to your web
server using version control software, such as
Git (https://git-scm.com). Although this is an
excellent route, it’s well beyond the scope of
a beginner’s guide to PHP.
C I’ve successfully connected to the remote server and navigated into the
html
directory (aka the web
document root).
4. Navigate to the proper directory for
your web pages (for example,
www
,
htdocs
, or
httpdocs
).
The SFTP application won’t necessarily
drop you off in the appropriate directory.
You may need to do some navigation
to get to the
web document root
. The
web document root is the directory on
the server to which a URL directly points
(for example, www.larryullman.com,
as opposed to www.larryullman.com/
somedir/). If you’re unsure of what the
web document root is for your setup, see
the documentation provided by the host-
ing company (or ask them for support).
In FileZilla, the right column represents
the files and directories on the server;
the left column represents the files and
directories on your computer C. Just
double-click folders to open them.
ptg18144795
12 Chapter 1
Testing Your Script
Testing a PHP script is a two-step process.
First, you must put the PHP script in the
appropriate directory for the web server.
Second, you run the PHP script in your web
browser by loading the correct URL.
If you’re using a separate web server,
like one provided by a hosting company,
you just need to use an SFTP application
to upload your PHP script to it (as in the
previous steps). If you have installed PHP
on your personal computer, then you can
test your PHP scripts by saving them in, or
moving them to, the web document root.
This is normally
n
~/Sites
for Mac OS X users (where
~
stands for your home directory; this
is no longer created automatically on
newer versions of Mac OS X, but you
can make one)
n
C:\Inetpub\wwwroot
for Windows
users running IIS
n
C:\xampp\htdocs
for Windows
users running XAMPP
(www.apachefriends.org)
n
/Applications/MAMP/htdocs
for Mac
users running MAMP (www.mamp.info)
If you’re not sure what the web document
root for your setup is, see the documenta-
tion for the web server application or
operating system (if the web server appli-
cation is built in).
Once you’ve got the PHP script in the right
place, use your browser to execute it.
To test your script in the browser:
1. Open your favorite web browser.
For the most part, PHP doesn’t behave
differently on different browsers
(because PHP runs on the server), so
use whichever browser you prefer.
In this book, you’ll see that I primarily
use Chrome, regardless of the operat-
ing system.
2. In the browser’s address bar, enter the
URL of the site where your script has
been saved.
In my case, I enter www.larryullman.com,
but your URL will certainly be different.
If you’re running PHP on your own
computer, the URL is http://localhost
(Windows); or http://localhost
/
~username
(Mac OS X), where you
should replace
username
with your
username. Some all-in-one packages,
such as MAMP and XAMPP, may also
use a
port
as part of the URL: http://
localhost:
8888
.
If you’re not sure what URL to use, see
the documentation for the web server
application you installed.
ptg18144795
Getting Started with PHP 13
3. Add
/phpinfo.php
to the URL.
If you placed the script within a sub-
directory of the web document root,
you would add that subdirectory
name to the URL as well (for example,
/ch01/phpinfo.php
).
4. Press Return/Enter to load the URL.
The page should load in your browser
window A.
continues on next page
A If the script executed correctly, the browser result should look like this (woohoo!).
ptg18144795
14 Chapter 1
If you see the PHP code B or a blank
page, it could mean many things:
n
You are not loading the PHP script
through a URL (that is, the address
does not begin with
http
). Note that
you may need to click the address bar
to view the full URL, including the
http
,
because many of today’s browsers
hide this by default.
n
PHP has not been enabled on
the server.
n
You are not using the proper extension.
If you see a
file not found
or similar error C,
it could be because
n
You entered the incorrect URL.
n
The PHP script is not in the proper
directory.
n
The PHP script does not have the cor-
rect name or extension.
It’s very important to remember that you
can’t open a PHP file directly in a browser as
you would open HTML pages or files in other
applications. PHP scripts must be processed
by the web server, which means you must
access them via a URL (an address that starts
with http://).
Even if you aren’t a seasoned computer
professional, you should consider installing
PHP on your computer. Doing so isn’t too dif-
ficult, and PHP is free. Again, see Appendix A
for instructions.
B If you see the raw PHP code, then the PHP
code is not being executed.
C This server response indicates a mismatch
between the URL attempted and the files that
actually exist on the server.
ptg18144795
Getting Started with PHP 15
Sending Text to
the Browser
PHP wouldn’t be very useful if all you
could do was see that it works (although
that confirmation is critical). You’ll use PHP
most frequently to send information to the
browser in the form of plain text and HTML
tags. To do so, use
print
:
print "something";
Just type the word
print
, followed by what
you want to display: a simple message, the
value of a variable, the result of a calcula-
tion, and so forth. In that example, the
message is a string of text, so it must be
surrounded with quotation marks.
PHP is case-insensitive when it comes to
calling functions, such as
phpinfo()
and
print
. Using
print
,
Print
, and
PRINT
nets the same results. Later in the book,
you’ll see examples where case makes a
crucial difference.
To be clear,
print
doesn’t actually
print
anything; it just outputs data. When a PHP
script is run through a browser, that PHP
output is received by the browser itself as
if it were content from a static HTML file.
Also note that the line is terminated by a
semicolon (
;
). Every statement in PHP code
must end with a semicolon, and forgetting
this requirement is a common cause of
errors. A
statement
in PHP is an executable
line of code, like
print "something";
or
phpinfo();
Conversely, comments, PHP tags, control
structures (for example, conditionals
and loops), and certain other constructs
discussed in this book don’t require
semicolons.
ptg18144795
16 Chapter 1
Finally, you should know about a minor
technicality: Whereas
phpinfo()
is a
function
,
print
is actually a
language
construct
. Although it’s still standard to
refer to
print
as a function, because
print
is a language construct, no paren-
theses are required when using it, as in
the
phpinfo()
example.
To print a simple message:
1. Begin a new HTML document in
your text editor or IDE, to be named
hello1.php
(Script 1.3):
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Hello, World!</title>
</head>
<body>
<p>The following was created by
PHP:
Most of this code is the standard HTML.
The last line will be used to distinguish
between the hard-coded HTML and the
PHP-generated HTML.
2. On the next line, type
<?php
to create
the initial PHP tag.
3. Add
print "Hello, world!";
Printing the phrase
Hello, world!
is the
first step most programming references
teach. Even though it’s a trivial reason
to use PHP, you’re not really a program-
mer until you’ve made at least one
Hello, world!
application.
Script 1.3 By putting the
print
statement between
the PHP tags, the server will dynamically send the
Hello, world!
greeting to the browser.
1 <!doctype html>
2 <html lang="en">
3 <head>
4 <meta charset="utf-8">
5 <title>Hello, World!</title>
6 </head>
7 <body>
8 <p>The following was created by PHP:
9 <?php
10 print "Hello, world!";
11 ?>
12 </p>
13 </body>
14 </html>
ptg18144795
Getting Started with PHP 17
4. Close the PHP section and complete
the HTML page:
?>
</p>
</body>
</html>
5. Save the file as
hello1.php
, place it on
your PHP-enabled server, and test it in
your browser A.
If you’re running PHP on your own com-
puter, remember that you can save the
file to the proper directory and access
the script via http://localhost/.
If you see an error or a blank page
instead of the results shown in the
figure, review the “Testing Your Script”
section, or skip ahead to the “Basic
Debugging Steps” section at the end of
this chapter.
You can use other functions to send text
to the browser, including
echo
and
printf()
,
but this book primarily uses
print
.
You can—and commonly will—use
print
over multiple lines:
print "This is a longer
sentence of text.";
The closing quotation mark terminates the
message being printed, and the semicolon is
placed only at the end of that line.
A A simple
Hello,
world!
example: your first
foray into PHP programming.
ptg18144795
18 Chapter 1
Using the PHP Manual
The PHP manual—accessible online at
www.php.net/manual—lists every function
and feature of the language. The manual
discusses general concepts (installation,
syntax, variables) first and ends with the
functions by topic (MySQL, string functions,
and so on).
To quickly look up any function in the PHP
manual, go to www.php.net/
functionname
in your web browser (for example,
www.php.net/print).
To understand how functions are described,
look at the start of the
print
function’s
page A.
The first line is the name of the function
itself, followed by the versions of PHP in
which it’s available. As the language grows,
new functions are added and, occasionally,
older functions are removed. Then there’s
a textual description of the function along
with the function’s basic usage. The usage
is the most important and confusing part.
In this example, the first value—
int
—says
that
print
returns an integer value (specifi-
cally,
print
returns 1, always). Within the
parentheses,
string
$arg
states that the
function takes one required argument,
which should be in the form of a string.
You’ve already seen this in action.
A The PHP manual’s page for the
print
language
construct.
ptg18144795
Getting Started with PHP 19
As a comparison, check out the manual’s
listing for the
nl2br()
function B. This
function converts newlines found within
text (the equivalent of pressing Return/
Enter) into HTML break tags. This function,
which returns a string, takes a string as its
first argument and an optional Boolean
(TRUE/FALSE) as its second. The square
brackets indicate optional arguments,
which are always listed last. When a func-
tion takes multiple arguments, they are
separated by commas. Hence, this function
can be called like so:
nl2br("Some text");
nl2br("Some text", false);
As the definition also indicates, the second
argument has a default value of
true
,
meaning it’ll create
<br
/>
tags (which is
XHTML compliant) unless the function is
passed a second argument value of
false
.
In that case, the function will create
<br>
tags instead.
The most important thing to remember
about the PHP manual is that it exists! If
you’re ever confused by a function or how
it is properly used, check the PHP manual’s
reference page for it.
B The PHP manual’s page for the
nl2br()
function.
ptg18144795
20 Chapter 1
To look up a function definition:
1. Go to www.php.net/
functionname
in
your web browser.
If the PHP manual doesn’t have a
matching record for the function you
tried, check the spelling or look at the
recommended alternatives that the
manual presents C.
2. Compare the versions of PHP that the
function exists in with the version of
PHP you’re using.
Use the
phpinfo()
function, already
demonstrated, to know for certain what
version of PHP you are running. If a func-
tion was added in a later version of PHP,
you’ll need to either upgrade the version
you have or use a different approach.
3. Examine what type of data the function
returns.
Sometimes you may be having a prob-
lem with a function because it returns a
different type of value than you expect
it to.
4. Examine how many and what types
of arguments the function requires or
can take.
The most common mistake when using
functions is sending the wrong number
or type of arguments when the function
is called.
5. Read the user comments, when present,
to learn more.
Sometimes the user comments can be
quite helpful (other times not).
If you see a message saying that a func-
tion has been deprecated D, that means the
function will be dropped from future versions
of PHP, and you should start using the newer,
better alternative (there is almost always a
better alternative identified).
C The manual will present alternative functions if
the entered URL doesn’t exactly match a reference.
D Deprecated functions should be avoided in
your code.
ptg18144795
Getting Started with PHP 21
Sending HTML to
the Browser
As those who first learned HTML quickly
discovered, viewing plain text in a web
browser leaves a lot to be desired. Indeed,
HTML was created to make plain text more
appealing and useful. Because HTML works
by adding tags to text, you can use PHP to
also send HTML tags to the browser, along
with other data:
print "<b>Hello, world!</b>";
There is one situation where you have to be
careful, though. HTML tags that require
double quotation marks, like
<a href=
"page.php">link</a>
, will cause problems
when printed by PHP, because the
print
function uses quotation marks as well A:
print "<a href="page.php">link</a>";
One workaround is to
escape
the quota-
tion marks within the HTML by preceding
them with a backslash (
\
):
print "<a href=\"page.php\">link</a>";
By escaping each quotation mark within
the
print
statement, you tell PHP to print
the mark itself instead of treating the quo-
tation mark as either the beginning or the
end of the string to be printed.
To send HTML to the browser:
1. Open the
hello1.php
script (Script 1.3)
in your text editor or IDE, if it is not
already open.
2. Within the HTML head, declare a CSS
class (Script 1.4):
<style type="text/css">
.bold {
font-weight: bolder;
}
</style>
continues on next page
A Attempting to print double quotation marks will
create errors, because they conflict with the
print
statement’s primary double quotation marks.
Script 1.4 Using
print
, you can send HTML
tags along with text to the browser, where the
formatting will be applied.
1 <!doctype html>
2 <html lang="en">
3 <head>
4 <meta charset="utf-8">
5 <title>Hello, World!</title>
6 <style type="text/css">
7 .bold {
8 font-weight: bolder;
9 }
10 </style>
11 </head>
12 <body>
13 <p>The following was created by PHP:
14 <?php
15 print "<span class=\"bold\">Hello,
world!</span>";
16 ?>
17 </p>
18 </body>
19 </html>
ptg18144795
22 Chapter 1
This CSS code declares a class named
bold
, which will be used to add empha-
sis to text. This is obviously a fairly trivial
use of CSS, but by declaring this as a
class, it can easily be updated, perhaps
to change the color of the text or the
size, along with its weight.
3. Edit the
Hello, world!
message by
adding HTML tags, making it read as
follows:
print "<span class=\"bold\">
Hello, world!</span>";
To make the PHP-generated part of
the message stand out, CSS styling will
bold the greeting. For this to work, you
must escape the quotation marks within
the span tag so they don’t conflict with
the
print
statement’s quotation mark.
4. Save the script as
hello2.php
, place
it on your PHP-enabled server, and run
the page in your browser B.
B The new version of the
Hello, world!
page, with
a little more decoration and appeal.
Using White Space
When programming in PHP, white space is generally (but not universally) ignored. Any blank line
(just one or several in a row) in PHP code is irrelevant to the end result. Likewise, tabs and spaces
are normally inconsequential to PHP. And because PHP code is not visible in the browser (unless
there’s a problem with the server), white space in your PHP files has no impact on what the end
user sees.
The spacing of HTML code shows up in the HTML source of a web page but has only a minimal
effect on what’s viewed in the browser. For example, all of a page’s HTML source code could be
placed on one line without changing what the end user sees. If you had to hunt for a problem in
the HTML source, however, you would not like the long, single line of HTML.
You can affect the spacing of dynamically generated HTML code by printing it in PHP over multiple
lines, or by using the newline character (
\n
) within double quotation marks:
print "Line 1\nLine 2";
Again, use of the newline character affects the
HTML source code
of the web page, not what the
end user sees rendered in the browser.
To adjust the spacing in the rendered web page, you’ll use CSS, plus paragraph, div, and break
tags, among others.
ptg18144795
Getting Started with PHP 23
Understanding the role of quotation
marks and how to escape problematic charac-
ters is crucial to programming with PHP. These
topics will be covered in more detail in the
next two chapters.
The HTML you send to the web browser
from PHP doesn’t need to be this simple. You
can create tables, JavaScript, and much, much
more.
Remember that any HTML outside the
PHP tags will automatically go to the browser.
Within the PHP tags,
print
statements are
used to send HTML to the web browser.
C The resulting HTML source code of
hello2.php
B.
5. View the HTML page source to see the
code that was sent to the browser C.
How you do this depends on the
browser: Select View > Developer >
View Source in Chrome, View > Page
Source in Firefox, or View > Source in
Internet Explorer.
This is a step you’ll want to be in the
habit of taking, particularly when prob-
lems occur. Remember that PHP is
primarily used to generate HTML, sent
to and interpreted by the browser.
Often, confirming what was sent to the
browser (by viewing the source) will help
explain the problem you’re seeing in the
browser’s interpretation (or visible result).
ptg18144795
24 Chapter 1
Adding Comments
to Scripts
Comments are integral to programming,
not because they do anything but because
they help you remember why
you
did
something. The computer ignores these
comments when it processes the script.
Furthermore, PHP comments are never
sent to the browser, remaining your secret.
PHP supports three ways of adding
comments. You can create a single-line
comment by putting either
//
or
#
at the
beginning of the line you want ignored:
// This is a comment.
You can also use
//
or
#
to begin a com-
ment at the end of a PHP line, like so:
print "Hello"; // Just a greeting.
Although it’s largely a stylistic issue,
//
is
much more commonly used in PHP than
#
.
You can create a multiline comment using
/*
to begin the comment and
*/
to con-
clude it:
/* This is a
multi-line comment. */
Some programmers prefer this comment
style because it contains both open and
closing “tags,” providing demarcation for
where the comment begins and ends.
ptg18144795
Getting Started with PHP 25
To add comments to a script:
1. Open the
hello2.php
created earlier
(Script 1.4) in your text editor or IDE.
2. After the initial PHP tag, add some
comments to your script (Script 1.5):
/*
* Filename: hello3.php
* Book reference: Script 1.5
* Created by: Larry Ullman
*/
This is just a sample of the kind of
comments you can write. You should
document what the script does, what
information it relies on, who created it,
when, and so forth. Stylistically, such
comments are often placed at the top
of a script (as the first thing within the
PHP section, that is), using formatting
like this. The extra asterisks aren’t
required; they just draw attention to
the comments.
3. On line 21, in front of the
print
state-
ment, type
//
.
By preceding the
print
statement with
two slashes, you ensure that the func-
tion call is “commented out,” meaning it
will never be executed.
4. After the closing PHP tag (on line 23),
add an HTML comment:
<!-- This is an HTML comment. -->
This line of code will help you distin-
guish among the different comment
types and where they appear. This com-
ment will appear only within the HTML
source code.
continues on next page
Script 1.5 PHP and HTML comments are added
to the script to document it and to render a line of
PHP code inert.
1 <!doctype html>
2 <html lang="en">
3 <head>
4 <meta charset="utf-8">
5 <title>Hello, World!</title>
6 <style type="text/css">
7 .bold {
8 font-weight: bolder;
9 }
10 </style>
11 </head>
12 <body>
13 <p>The following was created by PHP:
<br>
14 <?php
15 /*
16 * Filename: hello3.php
17 * Book reference: Script 1.5
18 * Created by: Larry Ullman
19 */
20
21 //print "<span class=\"bold\">Hello,
world!</span>";
22
23 ?>
24 <!-- This is an HTML comment. -->
25 </p>
26 </body>
27 </html>
ptg18144795
26 Chapter 1
5. Save the script as
hello3.php
, place
it on your PHP-enabled server, and run
the page in your web browser A.
6. View the source of the page to see the
HTML comment B.
You can comment out just one line of
code or several using the
/*
and
*/
method.
With
//
or
#
, you can negate only one line at
a time.
Different programmers prefer to com-
ment code in different ways. The important
thing is to find a system that works for you
and stick to it.
Note that you cannot use HTML com-
ment characters (
<!--
and
-->
) within PHP to
comment out code. You could have PHP print
those tags to the browser, but in that case
you’d create a comment that appeared in the
HTML source code on the client’s computer
(but not in the browser window). PHP comments
never make it as far as a user’s computer.
Despite my strong belief that you can’t
over-comment your scripts, the scripts in this
book aren’t as documented as they should
be, in order to save space. But the book will
document each script’s name and number, for
cross-reference purposes.
When you change a script’s code, be
certain to update its comments as well. It’s
quite confusing to see a comment that suggests
a script or a line of code does something other
than what it actually does.
A With the
print
statement commented out,
the page looks just as it would if the
print
call
weren’t there.
B HTML comments don’t appear in the web
browser but are in the HTML source. PHP
comments remain in the PHP script on the server,
not visible inside the HTML source.
ptg18144795
Getting Started with PHP 27
Basic Debugging Steps
Debugging is by no means a simple con-
cept to grasp, and unfortunately, it’s one
that is only truly mastered by doing. The
next 50 pages could be dedicated to the
subject and you’d still merely pick up a
fraction of the debugging skills that you’ll
eventually acquire and need.
The reason I introduce debugging in this
harrowing way is that it’s important not to
enter into programming with delusions.
Sometimes code won’t work as expected,
you’ll inevitably create careless errors, and
some days you’ll want to pull your hair out,
even when using a comparatively user-
friendly language such as PHP. In short,
prepare to be perplexed and frustrated
at times
. I’ve been coding in PHP since
1999, and occasionally I still get stuck in
the programming muck. But debugging is
a very important skill to have, and one that
you will eventually pick up out of necessity
and experience. As you begin your PHP
programming adventure, I offer the follow-
ing basic but concrete debugging tips.
ptg18144795
28 Chapter 1
To debug a PHP script:
n
Make sure you’re always running PHP
scripts through a URL!
This is perhaps the most common
beginner’s mistake. PHP code must be
run through the web server applica-
tion, which means it must be requested
through http://
something
. When you
see actual PHP code instead of the
result of that code’s execution, most
likely you’re not running the PHP script
through a URL.
n
Know what version of PHP you’re
running.
Some problems arise from the version
of PHP in use. Before you ever use
any PHP-enabled server, run the
phpinfo.php
file (Script 1.2) to confirm
the version of PHP in use.
n
Make sure
display_errors
is on.
This is a basic PHP configuration set-
ting (discussed in Appendix A). You
can confirm this setting by executing
the
phpinfo()
function (just use your
browser to search for
display_errors
in the resulting page). For security
reasons, PHP may not be set to display
the errors that occur. If that’s the case,
you’ll end up seeing blank pages when
problems occur. To debug most prob-
lems, you’ll need to see the errors, so
turn this setting on while you’re learn-
ing. You’ll find instructions for doing so
in Appendix A and Chapter 3, “HTML
Forms and PHP.
n
Check the HTML source code.
Sometimes the problem is hidden in
the HTML source of the page. In fact,
sometimes the PHP error message can
be hidden there!
n
Trust the error message.
Another very common beginner’s mis-
take is to not fully read or trust the error
that PHP reports. Although an error
message can often be cryptic and may
seem meaningless, it can’t be ignored.
At the very least, PHP is normally cor-
rect as to the line on which the problem
can be found. And if you need to relay
that error message to someone else
(like when you’re asking me for help),
do include the entire error message!
n
Take a break!
So many of the programming problems
I’ve encountered over the years, and
the vast majority of the toughest ones,
have been solved by stepping away
from my computer for a while. It’s easy
to become frustrated and confused,
and in such situations, any further steps
you take are likely to make matters
only worse.
These are just some general debugging
techniques, specifically tailored to the begin-
ning PHP programmer. They should suffice
for now, because the examples in this book
are relatively simple. More complex coding
requires more advanced debugging tech-
niques, so my PHP and MySQL for Dynamic
Web Sites: Visual QuickPro Guide, Fourth
Edition (Peachpit Press, 2012) dedicates a
whole chapter to this subject.
ptg18144795
Getting Started with PHP 29
Review and Pursue
Each chapter in this book ends with a
“Review and Pursue” section. In these
sections you’ll find:
n
Questions regarding the material just
covered
n
Prompts for ways to expand your
knowledge and experience on your own
If you have any problems with these
sections, in either answering the questions
or pursuing your own endeavors, turn
to the book’s supporting forum
(www.LarryUllman.com/forums/).
Review
n
What is HTML? What is the current
version of HTML?
n
What encoding is your text editor or IDE
set to use? Does that match the encod-
ing specified in your generated HTML
pages? Why does the encoding matter?
n
What is CSS and what is it used for?
n
What file extension should PHP scripts
have for your particular server?
n
What is meant by “web root directory”?
What is the web root directory for
your server?
n
How do you test PHP scripts? What
happens when PHP scripts are not
run through a URL?
n
Name two ways comments can be
added to PHP code. Identify some
reasons to use comments.
ptg18144795
30 Chapter 1
Pursue
n
If you have access to more than one
server, confirm what version of PHP is
running on another server.
n
Create a static HTML page that displays
some information. Then replace some of
the static content with content created
by PHP.
n
Create a template to use for your own
work. The template should contain the
HTML shell, the opening and closing
PHP tags, and some basic comments.
n
Confirm, using the
phpinfo()
function,
that
display_errors
is enabled on
your server. If it’s not, change your
server’s configuration to enable it (see
Chapter 3 and Appendix A).
n
In subsequent chapters, occasionally
check the PHP manual’s page when a
new function is mentioned in the book.
ptg18144795
The previous chapter covered how to use
PHP to send simple text and HTML to a
web browser—in other words, something
for which you don’t need PHP at all! Don’t
worry, though; this book will teach you how
to use
print
in conjunction with other PHP
features to do great and useful things with
your website.
To make the leap from creating simple,
static pages to dynamic web applications
and interactive websites, you need vari-
ables. Understanding what variables are,
the types of variables that a language sup-
ports, and how to use them is critical.
This chapter introduces the fundamentals
of variables in PHP, and later chapters
cover the different types in greater detail.
If you’ve never dealt with variables before,
this chapter will be a good introduction. If
you’re familiar with the concept, then you
should be able to work through this chapter
with ease.
2
Variables
In This Chapter
What Are Variables? 32
Variable Syntax 36
Types of Variables 38
Variable Values 41
Understanding Quotation Marks 44
Review and Pursue 48
ptg18144795
32 Chapter 2
What Are Variables?
A
variable
is a container for data. Once
data has been stored in a variable (or,
stated more commonly, once a variable
has been assigned a value), that data can
be altered, printed to the browser, saved to
a database, emailed, and so forth.
Variables in PHP are, by their nature,
flexible: You can put data into a variable,
retrieve that data from it (without affecting
the value of the variable), put new data in
it, and continue this cycle as many times
as necessary. But variables in PHP are
largely temporary:
Most only exist
—that is,
they only have a value—
for the duration
of the script’s execution on the server
.
Once the execution of the script completes
(often when the final closing PHP tag is
encountered), those variables cease to
exist. Furthermore, after users click a link
or submit a form, they are taken to a new
page that may have an entirely separate
set of variables.
Before getting too deep into the discus-
sion of variables, let’s write a quick script
that reveals some of PHP’s
predefined
variables. These are variables that PHP
automatically creates when a script runs.
Over the course of the book, you’ll be
introduced to many different predefined
variables. This particular example looks
at the predefined
$_SERVER
variable. It
contains lots of information about the com-
puter on which PHP is running.
The
print_r()
function offers an easy way
to display any variable’s value:
print_r($variable_name);
Just provide the name of the variable
you’d like to inspect as a single argument
to the
print_r()
function. (You’ll learn
more about a variable’s syntax throughout
this chapter.)
ptg18144795
Variables 33
To print PHP’s predefined variables:
1. Create a new PHP script in your
text editor or IDE, to be named
predefined.php
(Script 2.1).
2. Create the initial HTML tags:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Predefined Variables
</title>
</head>
<body>
<pre>
This code repeats the HTML template
created in the preceding chapter. Within
the body of the page, the
<pre>
tags
are being used to make the generated
PHP information more legible. Without
using the
<pre>
tags, the
print_r()
function’s output would be difficult to
read in a browser.
3. Add the PHP code:
<?php // Script 2.1 -
predefined.php
print_r($_SERVER);
?>
The PHP code contains just one func-
tion call. The function should be pro-
vided with the name of a variable.
In this example, the variable is
$_SERVER
, which is special in PHP.
$_SERVER
stores all sorts of data about
the server: its name and operating
system, the name of the current user,
information about the web server appli-
cation (Apache, Nginx, IIS, and so on),
and more. It also reflects the PHP script
being executed: its name, where it’s
stored on the server, and so forth.
continues on next page
Script 2.1 This script uses the
print_r()
function
to show the values stored in the
$_SERVER
predefined variable.
1 <!doctype html>
2 <html lang="en">
3 <head>
4 <meta charset="utf-8">
5 <title>Predefined Variables</title>
6 </head>
7 <body>
8 <pre>
9 <?php // Script 2.1 - predefined.php
10
11 // Show the value of the $_SERVER
variable:
12 print_r($_SERVER);
13
14 ?>
15 </pre>
16 </body>
17 </html>
ptg18144795
34 Chapter 2
Note that you must type
$_SERVER
exactly as it is here, in all upper-
case letters.
4. Complete the HTML page:
</pre>
</body>
</html>
5. Save the file as
predefined.php
,
upload it to your server (or save it to the
appropriate directory on your com-
puter), and test it in your browser A.
Once again, remember that you must
run all PHP scripts through a URL (that
is, http://
something
).
6. If possible, transfer the file to another
computer or server running PHP and
execute the script in your browser
again B.
Printing out the value of any variable
as you’ve done here is one of the greatest
debugging tools. Scripts often don’t work
as you expect them to because one or more
variables do not have the values you assume
they should, so confirming their actual values
is extremely helpful.
If you don’t use the HTML
<pre></pre>
tags, the result will be like the jumble of infor-
mation in C.
A The
$_SERVER
variable, as printed out by this script, is a master list
of values pertaining to the server and the PHP script.
ptg18144795
Variables 35
B With the
predefined.php
page, different servers will generate different
results (compare with A).
C With large, complex variables such as
$_SERVER
, not using the HTML
preformatting tags with
print_r()
creates an incomprehensible mess
(compare to A B).
ptg18144795
36 Chapter 2
Variable Syntax
Now that you’ve had a quick dip in the vari-
able pool, it’s time to swim a bit deeper. In
the preceding example, the script printed
out the value of PHP’s predefined
$_SERVER
variable. You can also create your own
variables, once you understand the proper
syntax. To create appropriate variable
names, you must follow these rules:
n
All variable names must be preceded
by a dollar sign (
$
).
n
Following the dollar sign, the variable
name must begin with either a letter
(A–Z, a–z) or an underscore (
_
). A num-
ber cannot immediately follow the
dollar sign.
n
The rest of the variable name can con-
tain any combination of letters, under-
scores, and numbers.
n
You may not use spaces within the
name of a variable. (Instead, the under-
score is commonly used to separate
words.)
n
Each variable must have a unique
name.
n
Variable names are
case-sensitive
!
Consequently,
$variable
and
$Variable
are two different constructs,
and it would be a bad idea to use two
variables with such similar names.
This last point is perhaps the most important:
Variable names in PHP are case-sensitive.
Using the wrong letter case is a very
common cause of bugs. (If you used, for
example,
$_server
or
$_Server
in the
previous script, you’d see either an error
message or nothing at all A.)
A Misspelling a variable’s name, including its
case, will create undesired and unpredictable
results.
ptg18144795
Variables 37
To help minimize bugs, I recommend the
following policies:
n
Always use all lowercase variable names.
n
Make your variable names descriptive
(for example,
$first_name
is better
than
$fn
).
n
Use comments to indicate the purpose
of variables (Script 2.2), redundant as
that may seem.
n
Above all, be consistent with whatever
naming convention you choose!
Table 2.1 lists some sample valid variables;
Table 2.2 lists some invalid variables and
the rules they violate.
Unlike some other languages, PHP
doesn’t require you to declare or initialize a
variable prior to use, although PHP does issue
warnings when you do. In other words, you
can refer to variables without first defining
them. But it’s best not to do that; try to write
scripts so that every variable is defined or
validated before use.
There are two main variable naming
conventions, determined by how you delineate
words. These are the so-called camel-hump
or camel-case (named because of the way
capital letters break up the word—for example,
$FirstName
) and underscore (
$first_name
)
styles. This book uses the latter convention.
Script 2.2 Properly documenting the purposes of
variables, along with using meaningful names, is a
hallmark of a professional programmer.
1 <!doctype html>
2 <html lang="en">
3 <head>
4 <meta charset="utf-8">
5 <title>Variables and Comments</title>
6 </head>
7 <body>
8 <?php // Script 2.2
9
10 // Define my variables....
11 $year = 2016; // The current year.
12 $june_avg = 88; // The average
temperature for the month of June.
13 $page_title = 'Weather Reports'; //
A title for the page.
14
15 // ... and so forth.
16 ?>
17 </body>
18 </html>
TABLE 2.1 Valid Variables in PHP
Name
$first_name
$person
$address1
$_SERVER
TABLE 2.2 Invalid Variables in PHP
Name Reason
$first name
Has a space
$first.name
Has a period
first_name
Does not begin with
$
$1address
A number cannot follow
$
ptg18144795
38 Chapter 2
Types of Variables
This book covers three common PHP vari-
able types:
numbers
,
strings
, and
arrays
.
This chapter introduces them quickly, and
later chapters discuss them in more detail:
n
Chapter 4, “Using Numbers”
n
Chapter 5, “Using Strings
n
Chapter 7, “Using Arrays”
A fourth variable type,
objects
, is intro-
duced in Appendix B, “Resources and Next
Steps,” but isn’t covered in this book. That
particular subject is just too advanced for
a beginner’s guide—in fact, basic coverage
of the subject in my
PHP Advanced and
Object-Oriented Programing: Visual
QuickPro Guide, Third Edition
(Peachpit
Press, 2013) requires over 150 pages!
TABLE 2.3 Valid Numbers in PHP
Number Type
1 Integer
1.0 Floating-point
1972 Integer
19.72 Floating-point
–1 Integer
–1.0 Floating-point
TABLE 2.4 Invalid Numbers in PHP
Number Reason
1/3 Contains a slash
1996a Contains a letter
08.02.06 Contains multiple
decimals
Numbers
Technically speaking, PHP breaks numbers
into two types:
integers
and
floating-point
(also known as
double-precision
floating-
point
or
doubles
). Due to the lax way PHP
handles variables, it largely won’t affect your
programming to group the two categories
of numbers into one all-inclusive member-
ship, at least when you’re just starting out.
Still, let’s briefly discuss the differences
between the two, to be precise.
The first type of numbers—
integers
—is also
known as
whole numbers
. They can be pos-
itive or negative but include neither fractions
nor decimals. Numbers that use a decimal
point (even something like 1.0) are
floating-
point
numbers, also known as
floats
. You
use floating-point numbers to refer to frac-
tions, because the only way to express a
fraction in PHP is to convert it to its decimal
equivalent. Hence, 1¼ is written as 1.25.
Table 2.3 lists some sample valid numbers
and their formal type; Table 2.4 lists invalid
numbers and the rules they violate.
As you’ll soon see, you add quotation
marks around invalid numbers to turn them
into valid strings.
ptg18144795
Variables 39
Strings
A string is any number of characters
enclosed within a pair of either single (
'
)
or double (
"
) quotation marks. Strings can
contain any combination of characters
that exist: letters, numbers, symbols, and
spaces. Strings can also contain variables.
Here are examples of valid string values:
"Hello, world!"
"Hello, $first_name!"
"1/3"
'Hello, world! How are you today?'
"08.02.06"
"1996"
''
That last example is an
empty string
—a
string that contains no characters.
To create a string, just wrap 0 or more
characters within quotation marks. There
are cases, however, where you may run
into problems. For example:
"I said, "How are you?""
This string will be tricky. Chapter 1, “Getting
Started with PHP,” hinted at the same prob-
lem with respect to printing HTML code.
When PHP hits the second quotation mark
in the example, it assumes the string ends
there; the continuing text (
How
) causes
an error. To use a quotation mark within a
string you
escape
the quotation mark by
putting a backslash (
\
) before it:
"I said, \"How are you?\""
The backslash tells PHP to treat each
escaped quotation mark as part of the
value
of the string, rather than using it as
the string’s opening or closing indicators.
You can similarly circumvent this problem
by using different quotation mark types:
'I said, "How are you?"'
"I said, 'How are you?'"
Notice that “1996” converts an integer
into a string, simply by placing the number
within quotes. Essentially, the string contains
the characters 1996, whereas the number (a
nonquoted value) would be equal to 1996. It’s
a fine distinction, and one that won’t matter
in your code, because PHP lets you perform
mathematical calculations with the string 1996
just as you can with the number.
Chapter 1 also demonstrated how to
create a new line by printing the
\n
charac-
ter within double quotation marks. Although
escaping a quotation mark prints the quota-
tion mark, escaping an n prints a new line,
escaping an r creates a carriage return, and
escaping a t creates a tab.
Understanding strings, variables, and the
single and double quotation marks is critical
to programming with PHP. For this reason, a
section at the end of this chapter is dedicated
to the subject.
ptg18144795
40 Chapter 2
Arrays
Arrays are covered more thoroughly in
Chapter 7, but let’s look at them briefly
here. Whereas a string or a number con-
tains a single value (both are said to be
scalar
), an array can have more than one
value assigned to it. You can think of an
array as a list or table of values: You can
put multiple strings and/or numbers into
one array.
Arrays use
keys
to create and retrieve the
values they store. The resulting structure—
a list of key-value pairs—is similar to a
two-column spreadsheet. Unlike arrays in
other programming languages, the array
structure in PHP is so flexible that it can use
either numbers or strings for both the keys
and the values. The array doesn’t even need
to be consistent in this respect. (All of this
will make more sense in Chapter 7, when
you start working with specific examples.)
PHP supports two kinds of arrays, based
on the format of the keys. If the array uses
numbers for the keys (Table 2.5), it’s known
as an
indexed
array. If it uses strings for
the keys (Table 2.6), it’s an
associative
array. In either case, the values in the array
can be of any variable type (string, number,
and so on).
The array’s key is also referred to as
its index. You’ll see these two terms used
interchangeably.
An array can, and frequently will, contain
other arrays, creating what is called a multi-
dimensional array.
What PHP refers to as an associative
array is known as a hash in Perl and Ruby,
among other languages.
TABLE 2.5 Indexed Array
Key Value
0 Dev
1 Rachel
2 Denise
3 Arnold
TABLE 2.6 Associative Array
Key Value
VT Vermont
NH New Hampshire
IA Iowa
PA Pennsylvania
ptg18144795
Variables 41
Variable Values
To assign a value to a variable, regardless
of the variable type, you use the equals
sign (
=
). Therefore, the equals sign is known
as the
assignment operator
, because it
assigns the value on the right to the variable
on the left. For example:
$number = 1;
$floating_number = 1.2;
$string = "Hello, world!";
Each of these lines represents a complete
statement (that is, an executable action),
so each concludes with a semicolon.
To print the value of a variable, use the
print
function:
print $number;
print $string;
If you want to print a variable’s value within
a context, you can place the variable’s
name in the printed string, as long as you
use double quotation marks A:
print "Number is $number";
print "String is $string";
Using
print
in this way works for the sca-
lar (single-valued) variable types—numbers
and strings. For complex variable types—
arrays and objects—you cannot just use
print
B:
print "_SERVER is $_SERVER";
As you’ve already seen,
print_r()
can
handle these nonscalar types, and you’ll
learn other approaches later in the book.
Whether you’re dealing with scalar or non-
scalar variables, don’t forget that printing
out their values is an excellent debugging
technique when you’re having problems
with a script.
A The result of printing the values
of two variables.
B Using the
print
statement on a complex
variable type, such as an array, will not have the
results you desire.
ptg18144795
42 Chapter 2
Because variable types aren’t locked in
(PHP is referred to as a
weakly typed
lan-
guage), they can be changed on the fly:
$variable = 1;
$variable = "Greetings";
If you were to print the value of
$variable
now, the result would be
Greetings
. The
following section better demonstrates the
concept of assigning values to variables
and then accessing those values.
To assign values to and
access variables:
1. Create a new PHP script in your
text editor or IDE, to be named
variables.php
(Script 2.3).
2. Create the initial HTML tags:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Variables</title>
</head>
<body>
3. Begin the PHP code:
<?php // Script 2.3 -
variables.php
4. Define some number and string
variables:
$street = "100 Main Street";
$city = "State College";
$state = "PA";
$zip = 16801;
These lines create four different vari-
ables of both string and number types.
The strings are defined using quotation
marks, and each variable name follows
the syntactical naming rules.
Script 2.3 Some basic variables are defined and
their values printed by this script.
1 <!doctype html>
2 <html lang="en">
3 <head>
4 <meta charset="utf-8">
5 <title>Variables</title>
6 </head>
7 <body>
8 <?php // Script 2.3 - variables.php
9
10 // An address:
11 $street = "100 Main Street";
12 $city = "State College";
13 $state = "PA";
14 $zip = 16801;
15
16 // Print the address:
17 print "<p>The address is:<br>$street
<br>$city $state $zip</p>";
18
19 ?>
20 </body>
21 </html>
ptg18144795
Variables 43
Remember that each statement must
conclude with a semicolon and that the
variable names are case-sensitive.
5. Print out the values of the variables
within some context:
print "<p>The address is:
<br>$street <br>$city $state
$zip</p>";
Here a single
print
statement refer-
ences all the variables. The entire string
to be printed (consisting of text, HTML
tags, and variables) is enclosed within
double quotation marks. The HTML
<br>
tags make the text flow over mul-
tiple lines in the browser.
6. Complete the PHP section and the
HTML page:
?>
</body>
</html>
7. Save the file as
variables.php
, upload
it to your server (or save it to the appro-
priate directory on your computer), and
test it in your browser C.
If you see a parse error D when you
run this script, you probably either omitted
a semicolon or have an imbalance in your
quotation marks. In such particular cases, the
mistake itself is likely on the previous line of
code (than reported in the error message) but
wasn’t caught by PHP until the next line.
If one of the variable’s values isn’t
printed out or you see an Undefined variable
error E, you most likely failed to spell a
variable name the same way twice.
If you see a blank page, you most likely
have an error but PHP’s
display_errors
configuration is set to off. See Chapter 3,
“HTML Forms and PHP,” for details.
C Some variables are assigned values, and then
printed within a context.
D Parse errors are the most common type of PHP
error, as you’ll discover. They’re frequently caused
by missing semicolons or mismatched quotation
marks or parentheses.
E The
Undefined variable
error indicates that
you used a variable with no value (it hasn’t been
defined). This can happen with misspellings and
capitalization inconsistencies.
ptg18144795
44 Chapter 2
Understanding
Quotation Marks
Now that you know the basics of variables
and how to create them, let’s do an exer-
cise to make sure you completely under-
stand how to properly use quotation marks.
PHP, like most programming languages,
allows you to use both double (
"
) and
single (
'
) quotation marks—but they give
vastly different results. It’s critical that you
comprehend the distinction, so the next
example will run tests using both types just
to emphasize the different behaviors.
The rule to remember is:
Items within
single quotation marks are treated literally;
items within double quotation marks
are extrapolated
. This means that within
double quotation marks, a variable’s name
is replaced with its value, as in Script 2.3,
but the same is not true for single quota-
tion marks.
This rule applies anywhere in PHP you
might use quotation marks, including
uses of the
print
function and the assign-
ment of values to string variables. An
example is the best way to demonstrate
this critical concept.
ptg18144795
Variables 45
To use quotation marks:
1. Begin a new PHP script in your text
editor or IDE, to be named
quotes.php
(Script 2.4).
2. Create the initial HTML tags:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Quotes</title>
</head>
<body>
3. Begin the PHP code:
<?php // Script 2.4 - quotes.php
4. Create two string variables:
$first_name = 'Larry';
$last_name = "Ullman";
It doesn’t matter whether you use single
or double quotation marks for these two
variables, because each string can be
treated literally. However, if you’re using
your own name here (and feel free to
do so) and it contains an apostrophe,
you’ll need to either use double quota-
tion marks or escape the apostrophe
within single quotation marks:
$last_name = "O'Toole";
$last_name = 'O\'Toole';
continues on next page
Script 2.4 This script simply demonstrates how
the type of quotation mark you use with variables
affects the result.
1 <!doctype html>
2 <html lang="en">
3 <head>
4 <meta charset="utf-8">
5 <title>Quotes</title>
6 </head>
7 <body>
8 <?php // Script 2.4 - quotes.php
9
10 // Single or double quotation marks
won't matter here:
11 $first_name = 'Larry';
12 $last_name = "Ullman";
13
14 // Single or double quotation marks DOES
matter here:
15 $name1 = '$first_name $last_name';
16 $name2 = "$first_name $last_name";
17
18 // Single or double quotation marks DOES
matter here:
19 print "<h1>Double Quotes</h1>
20 <p>name1 is $name1 <br>
21 name2 is $name2</p>";
22
23 print '<h1>Single Quotes</h1>
24 <p>name1 is $name1 <br>
25 name2 is $name2</p>';
26
27 ?>
28 </body>
29 </html>
ptg18144795
46 Chapter 2
5. Create two different
name
variables,
using the existing
first_
and
last_
name
variables:
$name1 = '$first_name
$last_name';
$name2 = "$first_name
$last_name";
In these lines, it makes a huge differ-
ence which quotation marks you use.
The
$name1
variable is now literally
equal to
$first_name
$last_name
,
because no extrapolation occurs.
Conversely,
$name2
is equal to
Larry
Ullman
, presumably the intended result.
6. Print out the variables using both types
of quotation marks:
print "<h1>Double Quotes</h1>
<p>name1 is $name1 <br>
name2 is $name2</p>";
print '<h1>Single Quotes</h1>
<p>name1 is $name1 <br>
name2 is $name2</p>';
Again, the quotation marks make all the
difference here. The first
print
state-
ment, using double quotation marks,
prints out the values of the
$name1
and
$name2
variables, whereas the second,
using single quotation marks, prints out
$name1
and
$name2
literally.
The HTML in the
print
statements
makes them more legible in the
browser. Each statement is executed
over three lines of PHP code for addi-
tional readability, which is perfectly
acceptable.
ptg18144795
Variables 47
7. Complete the PHP section and the
HTML page:
?>
</body>
</html>
8. Save the file as
quotes.php
, upload it
to your server (or save it to the appropri-
ate directory on your computer), and
test it in your browser A.
If you’re still confused about the distinc-
tion between the two types of quotation marks,
always stick with double quotation marks and
you’ll be safer.
Arguably, using single quotation marks
when you can is marginally preferable, because
PHP won’t need to search the strings looking
for variables, resulting in better performance.
But, at best, this is a minor optimization.
The shortcuts for creating newlines (
\n
),
carriage returns (
\r
), and tabs (
\t
) must be
used within double quotation marks to have
the desired effect. Within single quotes, each
of those is treated literally.
Remember that you don’t always need to
use quotation marks at all. When assigning a
numeric value or when only printing a variable,
you can omit them:
$num = 2;
print $num;
A The different quotation marks (single
versus double) dictate whether the
variable’s name or value is printed.
ptg18144795
48 Chapter 2
Review and Pursue
If you have any problems with the review
questions or the pursue prompts, turn
to the book’s supporting forum
(www.LarryUllman.com/forums/).
Review
n
What kind of variable is
$_SERVER
an
example of?
n
What character must all variables
begin with?
n
What characters can be used in a vari-
able’s name (after the required initial
character)? What other characters can
be used in a variable’s name, after the
first character?
n
Are variable names case-sensitive or
case-insensitive?
n
What does it mean to say that a variable
is
scalar
? What are examples of scalar
variable types? What is an example of
a nonscalar variable type?
n
What is the assignment operator?
n
What great debugging technique—with
respect to variables—was introduced
in this chapter?
n
What is the difference between using
single and double quotation marks?
Pursue
n
Create another PHP script that defines
some variables and prints their values.
Try using variables of different scalar
types.
n
Create a PHP script that prints the value
of some variables within some HTML.
More sophisticated practice might
involve using PHP and variables to
create a link or image tag.
ptg18144795
The previous chapter provided a brief
introduction to the topic of variables.
Although you’ll commonly create your
own variables, you’ll also frequently use
variables in conjunction with HTML forms.
Forms are a fundamental unit of websites,
enabling such features as registration
and login systems, search capability, and
online shopping. Even the simplest site
will find logical reasons to incorporate
HTML forms. And with PHP, it’s stunningly
simple to receive and handle data gener-
ated by them.
With that in mind, this chapter will cover
the basics of creating HTML forms and
explain how the submitted form data is
available to a PHP script. This chapter will
also introduce several key concepts of real
PHP programming, including how to man-
age errors in your scripts.
3
HTML Forms
and PHP
In This Chapter
Creating a Simple Form 50
Choosing a Form Method 54
Receiving Form Data in PHP 58
Displaying Errors 63
Error Reporting 65
Manually Sending Data to a Page 68
Review and Pursue 73
ptg18144795
50 Chapter 3
Creating a
Simple Form
For the HTML form example in this chapter,
you’ll create a feedback page that takes
the user’s salutation (or title), name, email
address, response, and comments A. The
code that generates a form goes between
opening and closing form tags:
<form>
form elements
</form>
The form tags dictate where a form begins
and ends. Every element of the form must
be entered between these two tags. The
opening form tag should also contain an
action
attribute. It indicates the page to
which the form data should be submitted.
This value is one of the most important
considerations when you’re creating a form.
In this book, the
action
attributes will
always point to PHP scripts:
<form action="somepage.php">
Before creating this next form, let’s briefly
revisit the topic of HTML5. HTML5 intro-
duces some new form element types, such
as
email
,
number
, and
url
. These types,
which are generally well supported by
current browsers, provide additional ben-
efits over a simple text input, including:
n
Built-in browser-based validation (for
example, the browser will check that
entered text is a syntactically valid email
address or URL).
n
Better user experience (for example,
an email address-specific keyboard
presented to mobile users).
HTML5 also introduces a
required
attribute
that prevents a form from being submitted
without a value entered or selected B.
A The HTML form that will be used in this
chapter’s examples.
B The
required
attribute validates—in the
browser—that a selection was made or content
was entered.
ptg18144795
HTML Forms and PHP 51
As a final note, give each form element its
own unique name. Stick to a consistent
naming convention when naming elements,
using only letters, numbers, and the under-
score (
_
). The result should be names that
are also logical and descriptive.
To create a basic HTML form:
1. Begin a new document in your text editor
or IDE, to be named
feedback.html
(Script 3.1):
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Feedback Form</title>
</head>
<body>
<!-- Script 3.1 - feedback.html
-->
<div><p>Please complete this
form to submit your feedback:
</p>
2. Add the opening form tag:
<form action="handle_form.php">
The form tag indicates that this form
will be submitted to the page
handle_
form.php
, found within the same direc-
tory as this HTML page. You can use a
full URL to the PHP script, if you’d prefer
to be explicit (for example,
http://
www.example.com/handle_form.php
).
continues on next page
Script 3.1 This HTML page has a form with several
different input types.
1 <!doctype html>
2 <html lang="en">
3 <head>
4 <meta charset="utf-8">
5 <title>Feedback Form</title>
6 </head>
7 <body>
8 <!-- Script 3.1 - feedback.html -->
9 <div><p>Please complete this form to
submit your feedback:</p>
10
11 <form action="handle_form.php">
12
13 <p>Name: <select name="title"
required>
14 <option value="Mr.">Mr.</option>
15 <option value="Mrs.">Mrs.</option>
16 <option value="Ms.">Ms.</option>
17 </select> <input type="text"
name="name" size="20" required>
</p>
18
19 <p>Email Address: <input
type="email" name="email"
size="20" required></p>
20
21 <p>Response: This is...
22 <input type="radio"
name="response" value="excellent"
required> excellent
23 <input type="radio"
name="response" value="okay"> okay
24 <input type="radio"
name="response" value="boring">
boring</p>
25
26 <p>Comments: <textarea
name="comments" rows="3" cols="30"
required></textarea></p>
27
28 <input type="submit" name="submit"
value="Send My Feedback">
29
30 </form>
31 </div>
32 </body>
33 </html>
ptg18144795
52 Chapter 3
3. Add a select menu plus a text input for
the person’s name:
<p>Name: <select name="title"
required>
<option value="Mr.">Mr.</option>
<option value="Mrs.">Mrs.
</option>
<option value="Ms.">Ms.</option>
</select> <input type="text"
name="name" size="20" required>
</p>
The inputs for the person’s name will
consist of two elements A. The first is
a drop-down menu of common titles:
Mr.
,
Mrs
., and
Ms
. Each option listed
between the select tags is an answer
the user can choose C. The second
element is a basic text box for the
person’s full name. Arguably, this list
should be expanded, or you could
use a text input to let users enter their
preferred title.
Every form element, except for the submit
button, will have the
required
attribute.
4. Add a text input for the user’s email
address:
<p>Email Address: <input type=
"email" name="email" size="20"
required></p>
The email input type is new in HTML5.
On browsers that support it—all the
most recent ones—client-side validation
is automatic D.
C The select element creates a drop-down menu
of options.
D The email input type, new in HTML5, validates
the syntax of the entered text against what’s
required for email addresses.
ptg18144795
HTML Forms and PHP 53
5. Add radio buttons for a response:
<p>Response: This is...
<input type="radio"
name="response"
value="excellent" required>
excellent
<input type="radio"
name="response" value="okay">
okay
<input type="radio"
name="response"
value="boring"> boring</p>
This HTML code creates three radio
buttons (clickable circles, A). Because
they all have the same value for the
name
attribute, only one of the three
can be selected at a time. Adding the
required
attribute to any one of them
makes selection of one of them a
requirement.
6. Add a
textarea
to record the
comments:
<p>Comments: <textarea
name="comments" rows="3"
cols="30" required>
</textarea></p>
A textarea gives users more space to
enter their comments than a text input
would. However, the text input lets
you limit how much information users
can enter, which you can’t do with the
textarea (not without using JavaScript,
that is). When you’re creating a form,
choose input types appropriate to the
information you wish to retrieve from
the user.
Note that a textarea
does
have a clos-
ing tag, unlike the text input type.
7. Add the submit button:
<input type="submit"
name="submit" value="Send My
Feedback">
The
value
attribute of a submit input
is what appears on the button in the
browser A. You could also use
Go!
or
Submit
, for example.
8. Close the form:
</form>
9. Complete the page:
</div>
</body>
</html>
10. Save the page as
feedback.html
, and
view it in your browser.
Because this is an HTML page, not a
PHP script, you could view it in your
browser directly from your computer.
Note that
feedback.html
uses the
HTML extension because it’s a standard HTML
page (not a PHP script). You could use the
.php
extension without a problem, even though
there’s no actual PHP code. (Remember that
in a PHP page, anything not within the PHP
tags—
<?php
and
?>
—is assumed to be HTML.)
Be certain that your
action
attribute
correctly points to an existing file on the server,
or your form won’t be processed properly.
In this case, the form will be submitted to
handle_form.php
, to be located in the same
directory as the
feedback.html
page.
In this example, an HTML form is created
by hand-coding the HTML, but you can do
this in a webpage application (such as Adobe
Dreamweaver) if you’re more comfortable with
that approach.
ptg18144795
54 Chapter 3
Choosing a
Form Method
The experienced HTML developer will
notice that the feedback form just created
is missing one thing: The initial form tag
has no
method
attribute. The
method
attri-
bute tells the server how to transmit the
data from the form to the handling script.
You have two choices with
method
: GET
and POST. With respect to forms, the dif-
ference between using GET and POST is
squarely in how the information is passed
from the form to the processing script. The
GET method sends all the gathered infor-
mation along as part of the URL. The POST
method transmits the information invisibly
to the user. For example, upon submitting
a form, if you use the GET method, the
resulting URL will be something like
http://example.com/page.php?var=
value&age=20&...
Following the name of the script,
page.php
,
is a question mark, followed by one
name=value
pair for each piece of data
submitted.
When using the POST method, the end
user will only see
http://example.com/page.php
.
ptg18144795
HTML Forms and PHP 55
When deciding which method to use, keep
in mind these four factors:
n
With the GET method, a limited amount
of information can be passed.
n
The GET method sends the data to the
handling script publicly (which means,
for example, that a password entered
in a form would be viewable by anyone
within eyesight of the browser, creating
a larger security risk).
n
A page generated by a form that used
the GET method can be bookmarked,
but one based on POST can’t be.
n
Users will be prompted if they attempt
to reload a page accessed via POST A,
but will not be prompted for pages
accessed via GET.
Generally speaking, GET requests are used
when asking for information from the server.
Search pages almost always use GET (check
out the URLs the next time you use a search
engine), as do sites that paginate results
(like the ability to browse categories of
products). POST is normally used to trigger
a server-based action. This might be the
submission of a contact form (result: an
email gets sent) or the submission of a blog’s
comment form (result: a comment is added
to the database and therefore the page).
This book uses POST almost exclusively for
handling forms, although you’ll also see a
useful technique involving the GET method
(see “Manually Sending Data to a Page” at
the end of this chapter).
A If users refresh a PHP script that data has been
sent to via the POST method, they will be asked to
confirm the action (the specific message will differ
depending on the browser).
ptg18144795
56 Chapter 3
To add a method to a form:
1. Open
feedback.html
(Script 3.1) in your
text editor or IDE, if it is not already
open.
2. Within the initial
form
tag, add
method="post"
(Script 3.2, line 11).
The form’s
method
attribute tells the
browser how to send the form data to
the receiving script. Because there may
be a lot of data in the form’s submission
(including the comments), and because
it wouldn’t make sense for the user to
bookmark the resulting page, POST is
the logical method to use.
3. Save the script and reload it in your
browser.
It’s important that you get in the habit
of reloading pages in the browser after
you make changes. It’s quite easy to
forget the reloading step and find your-
self flummoxed when your changes are
not being reflected.
Script 3.2 Adding a
method
attribute with a value
of
post
completes the form.
1 <!doctype html>
2 <html lang="en">
3 <head>
4 <meta charset="utf-8">
5 <title>Feedback Form</title>
6 </head>
7 <body>
8 <!-- Script 3.2 - feedback.html -->
9 <div><p>Please complete this form to
submit your feedback:</p>
10
11 <form action="handle_form.php"
method="post">
12
13 <p>Name: <select name="title"
required>
14 <option value="Mr.">Mr.</option>
15 <option value="Mrs.">Mrs.</option>
16 <option value="Ms.">Ms.</option>
17 </select> <input type="text"
name="name" size="20" required></p>
18
19 <p>Email Address: <input type="email"
name="email" size="20" required></p>
20
21 <p>Response: This is...
22 <input type="radio" name="response"
value="excellent" required> excellent
23 <input type="radio" name="response"
value="okay"> okay
24 <input type="radio" name="response"
value="boring"> boring</p>
25
26 <p>Comments: <textarea
name="comments" rows="3" cols="30"
required></textarea></p>
27
28 <input type="submit" name="submit"
value="Send My Feedback">
29
30 </form>
31 </div>
32 </body>
33 </html>
ptg18144795
HTML Forms and PHP 57
4. View the source of the page to make sure
all the required elements are present
and have the correct attributes B.
In the discussion of the methods, GET
and POST are written in capital letters to
make them stand out. However, the form in
the script uses post. Don’t worry about this
inconsistency (if you caught it at all)—the
method will work regardless of case.
B With forms, much of the important information, such as the
action
and
method
values or
element names, can be seen only within the HTML source code.
ptg18144795
58 Chapter 3
Receiving
Form Data in PHP
Now that you’ve created a basic HTML
form capable of taking input from a user,
you need to write the PHP script that will
receive and process the submitted form
data. For this example, the PHP script will
simply repeat what the user entered into
the form. In later chapters, you’ll learn how
to take this information and store it in a
database, send it in an email, write it to a
file, and so forth.
To access the submitted form data, you need
to refer to a particular
predefined variable
.
Chapter 2, “Variables,” already introduced
one predefined variable:
$_SERVER
. When
it comes to handling form data, the specific
variable the PHP script would refer to is
either
$_GET
or
$_POST
. If an HTML form
uses the GET method, the submitted form
data will be found in
$_GET
. When an HTML
form uses the POST method, the submitted
form data will be found in
$_POST
.
$_GET
and
$_POST
, besides being predefined
variables (that is, ones you don’t need to
create), are
arrays
, a special variable type
(
$_SERVER
is also an array). This means
that both
$_GET
and
$_POST
may contain
numerous values, making the printing of
those values more challenging. You cannot
treat arrays like so:
print $_POST; // Will not work!
A This ugly parse error is created by attempting to use
$_POST['address']
within double quotation marks.
(Also see B under “Variable Values” in
Chapter 2 for the result of the previous code.)
Instead, to access a specific value, you
must refer to the array’s
index
or
key
.
Chapter 7, “Using Arrays,” goes into this
subject in detail, but the premise is simple.
Start with a form element whose
name
attri-
bute has a value of
address
:
<input type="text" name="address" />
Then, assuming that the form uses the
POST method, the value entered into
that form element would be available in
$_POST['address']
:
print $_POST['address'];
Unfortunately, there is one little hitch here:
When used within double quotation marks,
the single quotation marks around the key
will cause parse errors A:
print "You provided your address as:
$_POST['address']";
You can avoid this problem in a couple of
ways. This chapter will use the solution
that’s syntactically the simpler of the two:
just assign the particular
$_POST
element
to another variable first:
$something = $_POST['something'];
print "Thanks for saying:
$something";
In Chapter 7 you’ll learn another approach.
ptg18144795
HTML Forms and PHP 59
Two final notes before implementing this
information in a new PHP script: First, as
with all variables in PHP,
$_POST
is case
sensitive; it must be typed exactly as you
see it here (a dollar sign, one underscore,
then all capital letters). Second, the indexes
in
$_POST
something
in the preceding
example—must exactly match the values
of the
name
attributes in the corresponding
form element.
To handle an HTML form:
1. Begin a new document in your
text editor or IDE, to be named
handle_form.php
(Script 3.3):
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Your Feedback</title>
</head>
<body>
2. Add the opening PHP tag and any
comments:
<?php // Script 3.3
handle_form.php
// This page receives the data
from feedback.html.
// It will receive: title, name,
email, response, comments, and
submit in $_POST.
Comments are added to make the
script’s purpose clear. Even though
the
feedback.html
page indicates
where the data is sent (via the
action
attribute), a comment here indicates
the reverse (where this script is getting
its data). It also helps to spell out the
exact form element names, in a case-
sensitive manner.
continues on next page
Script 3.3 Form data submitted to the script is
displayed by referencing the associated
$_POST
variables.
1 <!doctype html>
2 <html lang="en">
3 <head>
4 <meta charset="utf-8">
5 <title>Your Feedback</title>
6 </head>
7 <body>
8 <?php // Script 3.3 handle_form.php
9
10 // This page receives the data from
feedback.html.
11 // It will receive: title, name, email,
response, comments, and submit in
$_POST.
12
13 // Create shorthand versions of the
variables:
14 $title = $_POST['title'];
15 $name = $_POST['name'];
16 $response = $_POST['response'];
17 $comments = $_POST['comments'];
18
19 // Print the received data:
20 print "<p>Thank you, $title $name,
for your comments.</p>
21 <p>You stated that you found this
example to be '$response' and
added:<br>$comments</p>";
22
23 ?>
24 </body>
25 </html>
ptg18144795
60 Chapter 3
3. Assign the received data to new
variables:
$title = $_POST['title'];
$name = $_POST['name'];
$response = $_POST['response'];
$comments = $_POST['comments'];
Again, since the form uses the POST
method, the submitted data can be
found in the
$_POST
array. The individual
values are accessed using the syntax
$_POST['name_attribute_value']
.
This works regardless of the form
elements type (input, email, select,
checkbox, etc.).
To make it easier to use these values
in a
print
statement in Step 4, each
value is assigned to a new variable in
this step. Neither
$_POST['email']
nor
$_POST['submit']
is being addressed,
but you can create variables for those
values if you’d like.
4. Print out the user information:
print "<p>Thank you, $title
$name, for your comments.</p>
<p>You stated that you found
this example to be '$response'
and added:<br>$comments</p>";
This one
print
statement uses the four
variables within a context to show the
user what data the script received.
5. Close the PHP section, and complete
the HTML page:
?>
</body>
</html>
ptg18144795
HTML Forms and PHP 61
6. Save the script as
handle_form.php
.
Note that the name of this file must
exactly match the value of the
action
attribute in the form.
7. Upload the script to the server (or store
it in the proper directory on your com-
puter if you’ve installed PHP), making
sure it’s saved in the same directory as
feedback.html
.
8. Load
feedback.html
in your browser
through a URL (
http://something
).
You must load the HTML form through
a URL so that when it’s submitted to
the PHP script, that PHP script is also
run through a URL.
PHP scripts must
always be run through a URL!
Failure to load a form through a URL is
a common beginner’s mistake.
9. Fill out B, and then submit the form C.
If you see a blank page, read the next
section of the chapter for how to display
the errors that presumably occurred.
If you see an error notice D or see that
a variable does not have a value when
printed, you likely misspelled either
the form element’s
name
value or the
$_POST
array’s index (or you filled out
the form incompletely).
B Whatever the user enters into the HTML form
should be printed out to the browser by the
handle_form.php
script C.
C This is another application of the
print
statement discussed in Chapter 1, but it constitutes
your first dynamically generated web page.
D Notices like these occur when a script refers
to a variable that doesn’t exist. In this particular
case, the cause is erroneously referring to
$_POST['Name']
when it should be
$_POST['name']
.
ptg18144795
62 Chapter 3
If you want to pass a preset value along
to a PHP script, use the hidden type of input
within your HTML form. For example, inserting
<input type="hidden"
name="form_page"
value="feedback.html">
between the form tags will create a variable
in the handling script named
$_POST['form_page']
with the value
feedback.html.
Notice that the value of radio button and
certain menu variables is based on the
value
attribute of the selected item (for example,
excellent from the radio button). This is also
true for checkboxes. For text boxes, the value
of the variable is what the user typed.
If the
handle_form.php
script displays
extra slashes in submitted strings, see the
“Magic Quotes” sidebar for an explanation
and solution.
As a brute-force way of seeing all the
form data submitted to a PHP script, call
print_r($_POST)
, in the same way that
Chapter 2 calls
print_r()
with
$_SERVER
.
You can also access form data, regard-
less of the form’s method, in the
$_REQUEST
predefined variable.
$_GET
and
$_POST
are more precise, however, and therefore
preferable.
Magic Quotes
Earlier versions of PHP had a feature
known as
Magic Quotes
, which has
since been removed (as of PHP 5.4).
Magic Quotes—when enabled—auto-
matically escapes single and double
quotation marks found in submitted form
data. So the string
I’d like more informa-
tion
would be turned into
I\’d like more
information
.
The escaping of potentially problem-
atic characters can be useful and even
necessary in some situations. But if the
Magic Quotes feature is enabled on your
PHP installation, you’ll see these back-
slashes when the PHP script prints out
the form data. You can undo its effect
using the
stripslashes()
function. To
apply it to the
handle_form.php
script,
you would do this, for example:
$comments = stripslashes
($_POST['comments']);
instead of just this:
$comments = $_POST['comments'];
That will have the effect of converting
an escaped submitted string back to its
original, non-escaped value.
If you’re not seeing extraneous slashes
added to submitted form data, you don’t
need to worry about Magic Quotes.
ptg18144795
HTML Forms and PHP 63
Displaying Errors
One of the very first issues that arise when
it comes to debugging PHP scripts is that
you may not even see the errors that occur.
After you install PHP on a web server, it
will run under a default configuration with
respect to security, performance, how it
handles data, and so forth. One of the
default settings is to not display any errors.
In other words, the
display_errors
setting
will be off A. When that’s the case, what
you might see when a script has an error
is a blank page. (This is common on fresh
installations of PHP; most hosting companies
will enable
display_errors
.)
The reason that errors should not be
displayed on a live site is that it’s a security
risk. Simply put, PHP’s errors often give
away too much information for the public at
large to see (not to mention that showing
PHP errors looks unprofessional). But you,
the developer,
do need
to see these errors
in order to fix them!
To have PHP display errors, you can do
one of the following:
n
Turn
display_errors
back on for PHP
as a whole. (See the “Configuring PHP”
section of Appendix A, “Installation and
Configuration,” for more information.)
n
Turn
display_errors
back on for an
individual script.
While developing a site, the first option is
by far preferred. However, it’s a possibility
only for those with administrative control
over the server. But anyone can use the
second option by including this line in a script:
ini_set('display_errors', 1);
The
ini_set()
function allows a script to
temporarily override a setting in PHP’s config-
uration file (many, but not all, settings can
be altered this way). The previous example
changes the
display_errors
setting to
on
, which is represented by the number 1.
Although this second method can be
implemented by anyone, the downside is
that if your script contains certain kinds of
errors (discussed next), the script cannot
be executed. In that situation, this line of
code won’t be executed, and the particular
error—or any that prevents a script from
running at all—still results in a blank page.
A Run a
phpinfo()
script (for example, Script 1.2) to view your server’s
display_errors
setting.
ptg18144795
64 Chapter 3
To display errors in a script:
1. Open
handle_form.php
in your text
editor or IDE, if it is not already open.
2. As the first line of PHP code, enter the
following (Script 3.4):
ini_set('display_errors', 1);
Again, this line tells PHP you’d like to
see any errors that occur. You should
call it first thing in your PHP section so
the rest of the PHP code will abide by
this new setting.
3. Save the file as
handle_form.php
.
4. Upload the file to your web server, and
test it in your browser.
If the resulting page has no errors in it,
then the script will run as it did before.
If you saw a blank page when you ran
the form earlier, you should now see
the actual error messages (like those in
D in the previous section). Again, if you
see such errors, you likely misspelled
the name of a form element, misspelled
the index in the
$_POST
array, or didn’t
fill out the form completely.
Make sure
display_errors
is enabled
anytime you’re having difficulties debugging
a script. If you installed PHP on your computer,
I highly recommend enabling it in your PHP
configuration while you learn (again, see
Appendix A).
If you see a blank page when running a
PHP script, also check the HTML source code
for errors or other problems.
Remember that the
display_errors
directive only controls whether error messages
are sent to the browser. It doesn’t create errors
or prevent them from occurring in any way.
Failure to use an equals sign after
name
in a form element will also cause problems:
<input name"something">
Script 3.4 This addition to the PHP script turns on
the
display_errors
directive so that errors will be
shown.
1 <!doctype html>
2 <html lang="en">
3 <head>
4 <meta charset="utf-8">
5 <title>Your Feedback</title>
6 </head>
7 <body>
8 <?php // Script 3.4 - handle_form.php #2
9
10 ini_set('display_errors', 1); // Let
me learn from my mistakes!
11
12 // This page receives the data from
feedback.html.
13 // It will receive: title, name, email,
response, comments, and submit in
$_POST.
14
15 // Create shorthand versions of the
variables:
16 $title = $_POST['title'];
17 $name = $_POST['name'];
18 $response = $_POST['response'];
19 $comments = $_POST['comments'];
20
21 // Print the received data:
22 print "<p>Thank you, $title $name, for
your comments.</p>
23 <p>You stated that you found this
example to be '$response' and
added:<br>$comments</p>";
24
25 ?>
26 </body>
27 </html>
ptg18144795
HTML Forms and PHP 65
Error Reporting
Another PHP configuration issue you should
be aware of, along with
display_errors
,
is
error reporting
. PHP has more than a
dozen different levels of errors, and you
can define your own (a subject not covered
in this book). Table 3.1 lists the four most
important general error levels, along with a
description and example of each.
You can set what errors PHP reports on in
two ways. First, you can adjust the
error_
reporting
level in PHP’s configuration file
(again, see Appendix A). If you are running
your own PHP server, you’ll probably want
to adjust that global setting while develop-
ing your scripts.
The second option is to use the
error_
reporting()
function in a script. The
function takes either a number or one or
more
constants
—nonquoted strings with
predetermined meanings—to adjust the
levels. (Each constant is associated with a
number.) The most important of these con-
stants are listed in Table 3.2, in order from
most forgiving to least.
TABLE 3.1 PHP Error Levels
Type Description Example
Notice Nonfatal error that may or may not be
indicative of a problem Referring to a variable that has no value
Warning Nonfatal error that is most likely problematic Misusing a function
Parse error Fatal error caused by a syntactical mistake Omission of a semicolon or an imbalance
of quotation marks, braces, or parentheses
Error A general fatal error Memory allocation problem
TABLE 3.2 Error Reporting Constants
Name
E_ERROR
E_WARNING
E_PARSE
E_NOTICE
E_STRICT
E_DEPRECATED
ptg18144795
66 Chapter 3
Using this information, you could add any
of the following to a script:
error_reporting(E_WARNINGS);
error_reporting(E_ALL);
error_reporting(E_ALL & ~E_STRICT);
The first line says that only warnings and
below should be reported. The second
requests that all errors be reported. The
last example states that you want to see
all error messages except strict ones (the
&
~
means
and not
).
E_STRICT
also notifies
you of code that could be problematic in
certain environments or future versions of
PHP. Keep in mind that adjusting this set-
ting doesn’t prevent or create errors; it just
affects whether or not errors are reported.
It’s generally best to develop and test PHP
scripts using the highest level of error report-
ing possible. To accomplish that, declare
that you want
all errors
error reporting:
error_reporting(E_ALL);
Otherwise, the default level of error report-
ing (as of this writing) is
E_ALL
&
~E_NOTICE
&
~E_STRICT
&
~E_DEPRECATED
. Unless you
override this default setting, you will not be
told about notices, strict errors, and depre-
cated code. As a developer, you want to be
notified of any potential or actual problem
with your code.
Let’s apply this adjustment to the
handle_
form.php
page.
To adjust error reporting in a script:
1. Open
handle_form.php
(Script 3.4) in
your text editor or IDE, if it is not open
already.
2. After the
ini_set()
line, add the
following (Script 3.5):
error_reporting(E_ALL);
Script 3.5 Adjust a script’s level of error reporting
to give you more or less feedback on potential and
existing problems. In my opinion, more is always
better.
1 <!doctype html>
2 <html lang="en">
3 <head>
4 <meta charset="utf-8">
5 <title>Your Feedback</title>
6 </head>
7 <body>
8 <?php // Script 3.5 - handle_form.php #3
9
10 ini_set('display_errors', 1); // Let me
learn from my mistakes!
11 error_reporting(E_ALL); // Show all
possible problems!
12
13 // This page receives the data from
feedback.html.
14 // It will receive: title, name, email,
response, comments, and submit in
$_POST.
15
16 // Create shorthand versions of the
variables:
17 $title = $_POST['title'];
18 $name = $_POST['name'];
19 $response = $_POST['response'];
20 $comments = $_POST['comments'];
21
22 // Print the received data:
23 print "<p>Thank you, $title $name, for
your comments.</p>
24 <p>You stated that you found this
example to be '$response' and
added:<br>$comments</p>";
25
26 ?>
27 </body>
28 </html>
ptg18144795
HTML Forms and PHP 67
3. Save the file as
handle_form.php
.
4. Place the file in the proper directory for
your PHP-enabled server, and test it in
your browser by submitting the form
(A and B).
At this point, if the form is filled out
completely and the
$_POST
indexes
exactly match the names of the form
elements, you shouldn’t see any errors
(as in the figures). If any problems
exist, including any potential problems
(thanks to
E_STRICT
), they should be
displayed and reported.
The PHP manual lists all the error-
reporting levels, but those listed here are the
most important.
The code in this book was tested using
the highest level of error reporting:
E_ALL
.
Prior to PHP 5.4.0,
E_STRICT
was not
included in
E_ALL
, so the highest level of error
reporting could be achieved using
error_reporting(E_ALL | E_STRICT);
The vertical bar, known as the pipe, is the
equivalent of an “or” conditional.
A Try the form one more time…
B …and here’s the result (if filled out completely
and without any programmer errors).
ptg18144795
68 Chapter 3
Manually Sending
Data to a Page
The last example for this chapter is a
slight tangent to the other topics but plays
off the idea of handling form data with
PHP. As discussed in the earlier section
“Choosing a Form Method,” if a form uses
the GET method, the resulting URL is
something like
http://example.com/page.php?
var=value&age=20&...
The receiving page (here,
page.php
) is
sent a series of
name=value
pairs, each of
which is separated by an ampersand (
&
).
The whole sequence is preceded by
a question mark (immediately after the
handling script’s name).
To access the values passed to the page
in this way, turn to the
$_GET
variable.
Just as you would when using
$_POST
,
refer to the specific name as an index in
$_GET
. In that example,
page.php
receives
a
$_GET['var']
variable with a value of
value
, a
$_GET['age']
variable with a
value of
20
, and so forth.
You can pass data to a PHP script in this
way by creating an HTML form that uses
the GET method. But you can also use this
same idea to send data to a PHP page
without
the use of the form. Normally you’d
do so by creating links:
<a href="page.php?id=22">
Some Link</a>
That link, which could be dynamically gen-
erated by PHP, will pass the value
22
to
page.php
, accessible in
$_GET['id']
.
To try this for yourself, the next pair of
scripts will easily demonstrate this concept,
using a hard-coded HTML page.
Script 3.6 This HTML page uses links to pass
values to a PHP script in the URL (thereby
emulating a form that uses the GET method).
1 <!doctype html>
2 <html lang="en">
3 <head>
4 <meta charset="utf-8">
5 <title>Greetings!</title>
6 </head>
7 <body>
8 <!-- Script 3.6 - hello.html -->
9 <div><p>Click a link to say hello:</p>
10
11 <ul>
12 <li><a href="hello.
php?name=Michael">Michael</a></li>
13 <li><a href="hello.
php?name=Celia">Celia</a></li>
14 <li><a href="hello.
php?name=Jude">Jude</a></li>
15 <li><a href="hello.
php?name=Sophie">Sophie</a></li>
16 </ul>
17
18 </div>
19 </body>
20 </html>
ptg18144795
HTML Forms and PHP 69
To create the HTML page:
1. Begin a new document in your text
editor or IDE, to be named
hello.html
(Script 3.6):
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Greetings!</title>
</head>
<body>
<!-- Script 3.6 - hello.html -->
2. Create links to a PHP script, passing
values along in the URL:
<ul>
<li><a href="hello.php?name=
Michael">Michael</a></li>
<li><a href="hello.php?name=
Celia">Celia</a></li>
<li><a href="hello.php?name=
Jude">Jude</a></li>
<li><a href="hello.php?name=
Sophie">Sophie</a></li>
</ul>
The premise here is that the user will
see a list of links, each associated with
a specific name A. When the user
clicks a link, that name is passed to
hello.php
in the URL B.
continues on next page
A The simple HTML page, with four
links to the PHP script.
B The HTML source of the page shows how values are being passed
along in the URL for the four links.
ptg18144795
70 Chapter 3
If you want to use different names, that’s
fine, but stick to one-word names without
spaces or punctuation or else they won’t
be passed to the PHP script properly.
3. Complete the HTML page:
</div>
</body>
</html>
4. Save the script as
hello.html
, and
place it within the proper directory on
your PHP-enabled server.
5. Load the HTML page through a URL in
your browser.
Although you can view HTML pages
without going through a URL, you’ll click
links in this page to access the PHP script,
so you’ll need to start off using a URL
here. Don’t click any of the links yet,
because the PHP script doesn’t exist!
To create the PHP script:
1. Begin a new document in your text
editor or IDE, to be named
hello.php
(Script 3.7):
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Greetings!</title>
<style type="text/css">
.bold {
font-weight: bolder;
}
</style>
</head>
<body>
Script 3.7 This PHP page refers to the
name
value
passed in the URL in order to print a greeting.
1 <!doctype html>
2 <html lang="en">
3 <head>
4 <meta charset="utf-8">
5 <title>Greetings!</title>
6 <style type="text/css">
7 .bold {
8 font-weight: bolder;
9 }
10 </style>
11 </head>
12 <body>
13 <?php // Script 3.7 - hello.php
14
15 ini_set('display_errors', 1); // Let me
learn from my mistakes!
16 error_reporting(E_ALL); // Show all
possible problems!
17
18 // This page should receive a name value
in the URL.
19
20 // Say "Hello":
21 $name = $_GET['name'];
22 print "<p>Hello, <span
class=\"bold\">$name</span>!</p>";
23
24 ?>
25 </body>
26 </html>
ptg18144795
HTML Forms and PHP 71
2. Begin the PHP code:
<?php // Script 3.7 - hello.php
3. Address the error management,
if desired:
ini_set('display_errors', 1);
error_reporting(E_ALL);
These two lines, which configure how
PHP responds to errors, are explained
in the pages leading up to this section.
They may or may not be necessary for
your situation but can be helpful.
4. Use the
name
value passed in the URL
to create a greeting:
$name = $_GET['name'];
print "<p>Hello, <span class=
\"bold\">$name</span>!</p>";
The
name
variable is sent to the
page through the URL (see Script
3.6). To access that value, refer to
$_GET['name']
. Again, you would use
$_GET
(as opposed to
$_POST
) because
the value is coming from a GET request.
As with earlier PHP scripts, the value in
the predefined variable (
$_GET
) is first
assigned to another variable, to simplify
the syntax in the
print
statement.
5. Complete the PHP code and the HTML
page:
?>
</body>
</html>
6. Save the script as
hello.php
, and place
it within the proper directory on your
PHP-enabled server.
It should be saved in the same directory
as
hello.html
(Script 3.6).
7. Click the links in
hello.html
to view
the result C and D.
continues on next page
C By clicking the first link,
Michael
is passed
along in the URL and is greeted by name.
D By clicking the second link,
Celia
is sent along
in the URL and is also greeted by name.
ptg18144795
72 Chapter 3
If you run
hello.php
directly (that
is, without clicking any links), you’ll get an
error notice because no
name
value would be
passed along in the URL E.
Because
hello.php
reads a value from
the URL, it actually works independently of
hello.html
. For example, you can directly
edit the
hello.php
URL to greet anyone,
even if
hello.html
does not have a link for
that name F.
If you want to use a link to send multiple
values to a script, separate the name=value
pairs (for example,
first_name=Larry
) with
the ampersand (
&
). So, another link may be
hello.php?first_name=Larry&last_
name=Ullman
. You should continue to use
only single words, without punctuation or
spaces, however (until you later learn about
the
urlencode()
function).
Although the example here—setting the
value of a person’s name—may not be very
practical, this basic technique is useful on
many occasions. For example, a PHP script
might constitute a template, and the content
of the resulting web page would differ based
on the values the page received in the URL.
E If the
$_GET['name']
variable isn’t assigned
a value, the browser prints out this awkward
message, along with the error notice.
F Any value assigned to
name
(lowercase) in the
URL is used by the PHP script.
ptg18144795
HTML Forms and PHP 73
Review and Pursue
If you have any problems with the review
questions or the pursue prompts, turn
to the book’s supporting forum
(www.LarryUllman.com/forums/).
Review
n
What is the significance of a form’s
action
attribute?
n
What is the significance of a form’s
method
attribute? Is it more secure to
use GET or POST? Which method type
can be bookmarked in the browser?
n
What predefined variable will contain
the data from a form submission? Note:
There are multiple answers.
n
Why must an HTML page that contains
a form that’s being submitted to a PHP
script be loaded through a URL?
n
Under what circumstances will attempts
to enable
display_errors
in a script
not succeed? Why is it less secure to
enable
display_errors
on live sites?
ptg18144795
74 Chapter 3
Pursue
n
Load
feedback.html
in your browser
without going through a URL (that is,
the address bar would likely start with
file://
). Fill out and submit the form.
Observe the result so that you can
recognize this problem, and understand
its cause, in case you see similar results
in the future.
n
If you have not already, and if you
can, make sure that
display_errors
is enabled on your development
environment.
n
If you have not already, and if you can,
make sure that
error_reporting
is
set to
E_ALL
on your development
environment (or
E_ALL
|
E_STRICT
in
earlier versions of PHP).
n
Try introducing different errors in a
PHP script—by improperly balancing
quotation marks, failing to use semi-
colons, referring to variables improperly,
and so on—to see the result.
n
Experiment with the
hello.html
and
hello.php
pages to send different
values, including numbers, to the PHP
script through the URL.
n
Create a variation on
hello.html
that
sends multiple
name=value
pairs to a
PHP script. Have the PHP script then
print all the received values.
n
If you are the inquisitive type and don’t
mind waiting for answers, try passing
more complicated values to a page
through the URL. Try using spaces and
punctuation to see what happens.
n
Create a new HTML form that performs
a task you envision yourself needing
(or a lighter-weight version of that func-
tionality). Then create the PHP script
that handles the form, printing just the
received data.
ptg18144795
Chapter 2, “Variables,” briefly discussed
the various types of variables, how to
assign values to them, and how they’re
generally used. In this chapter, you’ll work
specifically with number variables—both
integers (whole numbers) and floating-
point numbers (aka floats or decimals).
You’ll begin by creating an HTML form that
will be used to generate number variables.
Then you’ll learn how to perform basic arith-
metic, how to format numbers, and how to
cope with operator precedence. The last
two sections of this chapter cover incre-
menting and decrementing numbers, plus
generating random numbers. Throughout
the chapter, you’ll also learn about other
useful number-related PHP functions.
4
Using
Numbers
In This Chapter
Creating the Form 76
Performing Arithmetic 79
Formatting Numbers 83
Understanding Precedence 86
Incrementing and Decrementing
a Number 88
Creating Random Numbers 90
Review and Pursue 92
ptg18144795
76 Chapter 4
Creating the Form
Most of the PHP examples in this chapter
will perform various calculations based on
an e-commerce premise. A form will take
price, quantity, discount amount, tax rate,
and shipping cost A, and the PHP script
that handles the form will return a total
cost. That cost will also be broken down by
the number of payments the user wants to
make in order to generate a monthly cost
value B.
To start, let’s create an HTML page that
allows the user to enter the values.
To create the HTML form:
1. Begin a new HTML document in
your text editor or IDE, to be named
calculator.html
(Script 4.1):
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Product Cost Calculator
</title>
</head>
<body><!-- Script 4.1 -
calculator.html -->
<div><p>Fill out this form to
calculate the total cost:</p>
2. Create the initial form tag:
<form action="handle_calc.php"
method="post">
This form tag begins the HTML form. Its
action
attribute indicates that the form
data will be submitted to a page named
handle_calc.php
. The tag’s
method
attribute tells the page to use POST to
send the data. See Chapter 3, “HTML
Forms and PHP,” for more details on
choosing a method.
A This form takes numbers from the user
and sends them to a PHP page.
B The PHP script performs a series of calculations
on the submitted data and outputs the results. The
results will look like this by the end of the chapter.
ptg18144795
Using Numbers 77
3. Create the inputs for the price, quantity,
discount, and tax:
<p>Price: <input type="text"
name="price" size="5"></p>
<p>Quantity: <input type=
"number" name="quantity"
size="5" min="1" value="1"></p>
<p>Discount: <input type="text"
name="discount" size="5"></p>
<p>Tax: <input type="text"
name="tax" size="5"> (%)</p>
Although HTML5 does have a number
input type, it’s not always the right solu-
tion because it’s more naturally suited
to taking integer values. For that reason,
the quantity input will be a number type,
whereas the others will be text.
To guide the user, a parenthetical indi-
cates that the tax should be entered as
a percent.
Remember that the names used for the
inputs should correspond to valid PHP
variable names: Use letters, numbers,
and the underscore only; don’t start with
a number; and so forth.
continues on next page
Script 4.1 This basic HTML form will provide the
numbers for various mathematical calculations
over multiple PHP scripts.
1 <!doctype html>
2 <html lang="en">
3 <head>
4 <meta charset="utf-8">
5 <title>Product Cost Calculator</title>
6 </head>
7 <body><!-- Script 4.1 - calculator.html
-->
8 <div><p>Fill out this form to calculate
the total cost:</p>
9
10 <form action="handle_calc.php"
method="post">
11
12 <p>Price: <input type="text"
name="price" size="5"></p>
13
14 <p>Quantity: <input type="number"
name="quantity" size="5" min="1"
value="1"></p>
15
16 <p>Discount: <input type="text"
name="discount" size="5"></p>
17
18 <p>Tax: <input type="text" name="tax"
size="5"> (%)</p>
19
20 <p>Shipping method: <select
name="shipping">
21 <option value="5.00">Slow and steady</
option>
22 <option value="8.95">Put a move on it.</
option>
23 <option value="19.36">I need it
yesterday!</option>
24 </select></p>
25
26 <p>Number of payments to make: <input
type="number" name="payments" size="5"
min="1" value="1"></p>
27
28 <input type="submit" name="submit"
value="Calculate!">
29
30 </form>
31
32 </div>
33 </body>
34 </html>
ptg18144795
78 Chapter 4
4. Add a field in which the user can select
a shipping method:
<p>Shipping method: <select
name="shipping">
<option value="5.00">Slow and
steady</option>
<option value="8.95">Put a move
on it.</option>
<option value="19.36">I need it
yesterday!</option>
</select></p>
The shipping selection is made using
a drop-down menu. The value of the
selected option is the cost for that
option. If the user selects, for example,
the
Put a move on it.
option, the value
of
$_POST['shipping']
in
handle_
calc.php
will be
8.95
.
5. Complete the HTML form:
<p>Number of payments to make:
<input type="number"
name="payments" size="5"
min="1" value="1"></p>
<input type="submit" name=
"submit" value="Calculate!">
</form>
The final two input types take a number
for how many payments are required
and then create a submit button (labeled
Calculate!
). The closing form tag marks
the end of the form section of the page.
6. Complete the HTML page:
</div>
</body>
</html>
7. Save the script as
calculator.html
,
and view it in your browser.
Because this is an HTML page, you can
view it directly in a browser.
ptg18144795
Using Numbers 79
Performing Arithmetic
Just as you learned in grade school, basic
mathematics involves the principles of
addition, subtraction, multiplication, and
division. These are performed in PHP using
the most obvious operators:
n
Addition (
+
)
n
Subtraction (
-
)
n
Multiplication (
*
)
n
Division (
/
)
To use these operators, you’ll create a PHP
script that calculates the total cost for the
sale of some widgets. This handling script
could be the basis of a shopping cart appli-
cation—a very practical web page feature
(although in this case the relevant number
values will come from
calculator.html
).
When you’re writing this script, be sure to
note the comments (Script 4.2) used to
illuminate the different lines of code and
the reasoning behind them.
To create your sales cost calculator:
1. Create a new document in your
text editor or IDE, to be named
handle_calc.php
(Script 4.2):
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Product Cost Calculator
</title>
<style type="text/css">
.number {font-weight:bold;}
</style>
</head>
<body>
continues on next page
Script 4.2 This PHP script performs all the
standard mathematical calculations using the
numbers submitted from the form.
1 <!doctype html>
2 <html lang="en">
3 <head>
4 <meta charset="utf-8">
5 <title>Product Cost Calculator</
title>
6 <style type="text/css">
7 .number { font-weight: bold; }
8 </style>
9 </head>
10 <body>
11 <?php // Script 4.2 - handle_calc.php
12 /* This script takes values from
calculator.html and performs
13 total cost and monthly payment
calculations. */
14
15 // Address error handling, if you want.
16
17 // Get the values from the $_POST array:
18 $price = $_POST['price'];
19 $quantity = $_POST['quantity'];
20 $discount = $_POST['discount'];
21 $tax = $_POST['tax'];
22 $shipping = $_POST['shipping'];
23 $payments = $_POST['payments'];
24
25 // Calculate the total:
26 $total = $price * $quantity;
27 $total = $total + $shipping;
28 $total = $total - $discount;
29
30 // Determine the tax rate:
31 $taxrate = $tax / 100;
32 $taxrate = $taxrate + 1;
33
34 // Factor in the tax rate:
35 $total = $total * $taxrate;
36
37 // Calculate the monthly payments:
38 $monthly = $total / $payments;
39
code continues on next page
ptg18144795
80 Chapter 4
The head of the document defines
one CSS class, named
number
. Any
element within the page that has that
class value will be given extra font
weight. In other words, when the num-
bers from the form, and the results of
the various calculations, are printed
in the script’s output, they’ll be made
more obvious.
2. Insert the PHP tag and address error
handling, if desired:
<?php // Script 4.2 -
handle_calc.php
Depending on your PHP configuration,
you may or may not want to add a couple
of lines that turn on
display_errors
and adjust the level of error reporting.
See Chapter 3 for specifics.
(However, as also mentioned in that
chapter, it’s best to make these adjust-
ments in PHP’s primary configuration file.)
3. Assign the
$_POST
elements to local
variables:
$price = $_POST['price'];
$quantity = $_POST['quantity'];
$discount = $_POST['discount'];
$tax = $_POST['tax'];
$shipping = $_POST['shipping'];
$payments = $_POST['payments'];
The script will receive all the form data
in the predefined
$_POST
variable. To
access individual form values, refer to
$_POST['index']
, replacing
index
with
the corresponding form element’s
name
value. These values are assigned to
individual local variables here, to make
it easier to use them throughout the
rest of the script.
Note that each variable is given a
descriptive name and is written entirely
in lowercase letters.
Script 4.2 continued
40 // Print out the results:
41 print "<p>You have selected to
purchase:<br>
42 <span class=\"number\">$quantity</
span> widget(s) at <br>
43 $<span class=\"number\">$price</span>
price each plus a <br>
44 $<span class=\"number\">$shipping</
span> shipping cost and a <br>
45 <span class=\"number\">$tax</span>
percent tax rate.<br>
46 After your $<span
class=\"number\">$discount</span>
discount, the total cost is
47 $<span class=\"number\">$total</
span>.<br>
48 Divided over <span
class=\"number\">$payments</span>
monthly payments, that would be
$<span class=\"number\">$monthly</
span> each.</p>";
49
50 ?>
51 </body>
52 </html>
ptg18144795
Using Numbers 81
7. Print the results:
print "<p>You have selected to
purchase:<br>
<span class=\"number\">$quantity
</span> widget(s) at <br>
$<span class=\"number\">$price
</span> price each plus a <br>
$<span class=\"number\">$shipping
</span> shipping cost and a <br>
<span class=\"number\">$tax
</span> percent tax rate.<br>
After your $<span class=
\"number\">$discount</span>
discount, the total cost is
$<span class=\"number\">$total
</span>.<br>
Divided over <span class=
\"number\">$payments</span>
monthly payments, that would be
$<span class=\"number\">
$monthly</span> each.</p>";
The
print
statement sends every value
to the browser along with some text.
To make it easier to read,
<br>
tags are
added to format the browser result; in
addition, the
print
function operates
over multiple lines to make the PHP
code cleaner. Each variable’s value will
be highlighted in the browser by wrap-
ping it within span tags that have a
class
attribute of
number
(see Step 1).
8. Close the PHP section, and complete
the HTML page:
?>
</body>
</html>
9. Save the script as
handle_calc.php
,
and place it in the proper directory for
your PHP-enabled server.
Make sure that
calculator.html
is in
the same directory.
continues on next page
4. Begin calculating the total cost:
$total = $price * $quantity;
$total = $total + $shipping;
$total = $total - $discount;
The asterisk (
*
) indicates multiplication in
PHP, so the total is first calculated as the
number of items purchased (
$quantity
)
multiplied by the price. Then the shipping
cost is added to the total value (remem-
ber that the shipping cost correlates
to the
value
attribute of each shipping
drop-down menu’s
option
tags), and
the discount is subtracted.
Note that it’s perfectly acceptable to
determine a variable’s value in part by
using that variable’s existing value (as
is done in the last two lines).
5. Calculate the tax rate and the new total:
$taxrate = $tax / 100;
$taxrate = $taxrate + 1;
$total = $total * $taxrate;
The tax rate should be entered as a
percent—for example, 8 or 5.75. This
number is then divided by 100 to get
the decimal equivalent of the percent
(.08 or .0575). Finally, you calculate how
much something costs with tax by adding
1 to the percent and then multiplying
that new rate by the total. This is the
mathematical equivalent of multiplying
the decimal tax rate times the total and
then adding this result to the total (for
example, a 5 percent tax on $100 is
$5, making the total $105, which is the
same as multiplying $100 times 1.05).
6. Calculate the monthly payment:
$monthly = $total / $payments;
As an example of division, assume that
the widgets can be paid for over the
course of many months. Hence, you
divide the total by the number of pay-
ments to find the monthly payment.
ptg18144795
82 Chapter 4
10. Test the script in your browser by filling
out A and submitting B the form.
Not to belabor the point, but make sure
you start by loading the HTML form
through a URL (
http://something
) so
that when it’s submitted, the PHP script
is also run through a URL.
You can experiment with these values
to see how effectively your calculator
works. If you omit any values, the result-
ing message will just be a little odd but
the calculations should still work C.
As you’ll certainly notice, the calculator
comes up with numbers that don’t correspond
well to real dollar values (see B and C). In
the next section, “Formatting Numbers,” you’ll
learn how to address this issue.
If you want to print the value of the total
before tax or before the discount (or both),
you can do so in two ways. You can insert the
appropriate
print
statements immediately
after the proper value has been determined
but before the
$total
variable has been
changed again. Or you can use new variables
to represent the values of the subsequent
calculations (for example,
$total_with_tax
and
$total_less_discount
).
Attempting to print a dollar sign followed
by the value of a variable, such as $10 (where 10
comes from a variable), has to be handled care-
fully. You can’t use the syntax
$$variable
,
because the combination of two dollar signs
creates a type of variable that’s too complex
to discuss in this book. One solution is to put
something—a space or an HTML tag, as in this
example—between the dollar sign and the
variable name. Another option is to escape the
first dollar sign:
print "The total is \$$total";
A third option is to use concatenation, which is
introduced in the next chapter.
A The HTML form…
B …and the resulting calculations.
C You can omit or change any value and rerun
the calculator. Here the tax and discount values
have been omitted.
This script performs differently, depend-
ing on whether the various fields are submitted.
The only truly problematic field is the number
of monthly payments: If this is omitted, you’ll
see a division-by-zero warning. Chapter 6,
“Control Structures,” will cover validating form
data before it’s used.
ptg18144795
Using Numbers 83
Formatting Numbers
Although the calculator is on its way to
being practical, it still has one legitimate
problem: You can’t ask someone to make
a monthly payment of $10.13183333! To
create more usable numbers, you need to
format them.
Two functions are appropriate for this
purpose. The first,
round()
, rounds a value
to a specified number of decimal places.
The function’s first argument is the number
to be rounded. This can be either a number
or a variable that has a numeric value. The
second argument is optional; it represents
the number of decimal places to which
to round. If omitted, the number will be
rounded to the nearest integer. For example:
round(4.30); // 4
round(4.289, 2); // 4.29
$num = 236.26985;
round($num); // 236
The other function you can use in this
situation is
number_format()
. It works like
round()
in that it takes a number (or a vari-
able with a numeric value) and an optional
decimal specifier. This function has the
added benefit of formatting the number
with commas, the way it would commonly
be written:
number_format(428.4959, 2); // 428.50
number_format(428, 2); // 428.00
number_format(1234567); // 1,234,567
Let’s rewrite the PHP script to format the
numbers appropriately.
ptg18144795
84 Chapter 4
To format numbers:
1. Open
handle_calc.php
in your text
editor or IDE, if it is not already open
(Script 4.2).
2. After all the calculations but before the
print
statement, add the following
(Script 4.3):
$total = number_format($total, 2);
$monthly = number_format
($monthly, 2);
To format these two numbers, apply
this function after every calculation has
been made but before they’re sent to
the browser. The second argument (the
2) indicates that the resulting number
should have exactly two decimal places;
this setting rounds the numbers and
adds zeros at the end, as necessary.
Script 4.3 The
number_format()
function is
applied to the values of two number variables, so
they are more appropriate to the example.
1 <!doctype html>
2 <html lang="en">
3 <head>
4 <meta charset="utf-8">
5 <title>Product Cost Calculator</
title>
6 <style type="text/css">
7 .number { font-weight: bold;}
8 </style>
9 </head>
10 <body>
11 <?php // Script 4.3 - handle_calc.php #2
12 /* This script takes values from
calculator.html and performs
13 total cost and monthly payment
calculations. */
14
15 // Address error handling, if you want.
16
17 // Get the values from the $_POST array:
18 $price = $_POST['price'];
19 $quantity = $_POST['quantity'];
20 $discount = $_POST['discount'];
21 $tax = $_POST['tax'];
22 $shipping = $_POST['shipping'];
23 $payments = $_POST['payments'];
24
25 // Calculate the total:
26 $total = $price * $quantity;
27 $total = $total + $shipping;
28 $total = $total - $discount;
29
30 // Determine the tax rate:
31 $taxrate = $tax/100;
32 $taxrate = $taxrate + 1;
33
34 // Factor in the tax rate:
35 $total = $total * $taxrate;
36
37 // Calculate the monthly payments:
38 $monthly = $total / $payments;
39
40 // Apply the proper formatting:
41 $total = number_format($total, 2);
42 $monthly = number_format($monthly, 2);
43
code continues on next page
ptg18144795
Using Numbers 85
3. Save the file, place it in the same direc-
tory as
calculator.html
, and test it in
your browser A and B.
Another, much more complex way to
format numbers is to use the
printf()
and
sprintf()
functions. Because of their tricky
syntax, they’re not discussed in this book; see
the PHP manual for more information.
Non-Windows versions of PHP also have
a
money_format()
function, which can be
used in lieu of
number_format()
.
The
round()
function rounds exact
halves (.5, .05, .005, and so on) up, although
this behavior can be configured. See the PHP
manual for details.
In PHP, function calls can have spaces
between the function name and its parentheses
or not. Both of these are fine:
round ($num);
round($num);
The
number_format()
function takes two
other optional arguments that let you specify
what characters to use to indicate a decimal
point and break up thousands. This is useful,
for example, for cultures that write 1,000.89 as
1.000,89. See the PHP manual for the correct
syntax, if you want to use this option.
Script 4.3 continued
44 // Print out the results:
45 print "<p>You have selected to
purchase:<br>
46 <span class=\"number\">$quantity</span>
widget(s) at <br>
47 $<span class=\"number\">$price</span>
price each plus a <br>
48 $<span class=\"number\">$shipping</span>
shipping cost and a <br>
49 <span class=\"number\">$tax</span>
percent tax rate.<br>
50 After your $<span
class=\"number\">$discount</span>
discount, the total cost is
51 $<span class=\"number\">$total</
span>.<br>
52 Divided over <span
class=\"number\">$payments</span>
monthly payments, that would be $<span
class=\"number\">$monthly</span> each.</
p>";
53
54 ?>
55 </body>
56 </html>
A Another form entry. B The updated version of the script returns more
appropriate number values thanks to the
number_
format()
function.
ptg18144795
86 Chapter 4
Understanding
Precedence
Inevitably, after a discussion of the various
sorts of mathematical operators comes the
discussion of precedence.
Precedence
refers to the order in which a series of cal-
culations are executed. For example, what
is the value of the following variable?
$number = 10 – 4 / 2;
Is
$number
worth 3 (10 minus 4 equals 6,
divided by 2 equals 3) or 8 (4 divided by
2 equals 2, subtracted from 10 equals 8)?
The answer here is 8, because division
takes precedence over subtraction.
Appendix B, “Resources and Next Steps,
shows the complete list of operator
precedence for PHP (including operators
that haven’t been covered yet). However,
instead of attempting to memorize a large
table of peculiar characters, you forgo
any deliberation by using parentheses.
Parentheses always take precedence over
any other operator. Thus:
$number = (10 – 4) / 2; // 3
$number = 10 – (4 / 2); // 8
Using parentheses in your calculations
ensures that you never see peculiar results
due to precedence issues. Parentheses
can also be used to rewrite complex calcu-
lations in fewer lines of code. Let’s rewrite
the
handle_calc.php
script, combining
multiple lines into one by using parentheses,
while maintaining accuracy.
To manage precedence:
1. Open
handle_calc.php
in your text
editor or IDE, if it is not already open
(Script 4.3).
Script 4.4 By using parentheses, calculations
made over multiple lines (compare with Script 4.3)
can be condensed without affecting the script’s
mathematical accuracy.
1 <!doctype html>
2 <html lang="en">
3 <head>
4 <meta charset="utf-8">
5 <title>Product Cost Calculator</
title>
6 <style type="text/css">
7 .number { font-weight: bold;}
8 </style>
9 </head>
10 <body>
11 <?php // Script 4.4 - handle_calc.php #3
12 /* This script takes values from
calculator.html and performs
13 total cost and monthly payment
calculations. */
14
15 // Address error handling, if you want.
16
17 // Get the values from the $_POST array:
18 $price = $_POST['price'];
19 $quantity = $_POST['quantity'];
20 $discount = $_POST['discount'];
21 $tax = $_POST['tax'];
22 $shipping = $_POST['shipping'];
23 $payments = $_POST['payments'];
24
25 // Calculate the total:
26 $total = (($price * $quantity) +
$shipping) - $discount;
27
28 // Determine the tax rate:
29 $taxrate = ($tax / 100) + 1;
30
31 // Factor in the tax rate:
32 $total = $total * $taxrate;
33
34 // Calculate the monthly payments:
35 $monthly = $total / $payments;
36
37 // Apply the proper formatting:
38 $total = number_format ($total, 2);
39 $monthly = number_format ($monthly, 2);
40
code continues on next page
ptg18144795
Using Numbers 87
2. Replace the three lines that initially cal-
culate the order total with the following
(Script 4.4):
$total = (($price * $quantity) +
$shipping) - $discount;
In this script, it’s fine to make all the
calculations in one step, as long as you
use parentheses to ensure that the
math works properly. The other option
is to memorize PHP’s rules of prece-
dence for multiple operators, but using
parentheses is a lot easier.
3. Change the two lines that calculate and
add in the tax to this:
$taxrate = ($tax / 100) + 1;
Again, the tax calculations can be made
in one line instead of two separate ones.
4. Save the script, place it in the same
directory as
calculator.html
, and test
it in your browser A B.
Be sure that you match your parentheses
consistently as you create your formulas (every
opening parenthesis requires a closing paren-
thesis). Failure to do so will cause parse errors.
Granted, using the methods applied here,
you could combine all the total calculations
into just one line of code (instead of three)—
but there is such a thing as oversimplifying.
A Testing the form one more time. B Even though the calculations have been
condensed, the math works out the same. If you
see different results or get an error message,
double-check your parentheses for balance (an
equal number of opening and closing parentheses).
Script 4.4 continued
41 // Print out the results:
42 print "<p>You have selected to
purchase:<br>
43 <span class=\"number\">$quantity</span>
widget(s) at <br>
44 $<span class=\"number\">$price</span>
price each plus a <br>
45 $<span class=\"number\">$shipping</span>
shipping cost and a <br>
46 <span class=\"number\">$tax</span>
percent tax rate.<br>
47 After your $<span
class=\"number\">$discount</span>
discount, the total cost is
48 $<span class=\"number\">$total</
span>.<br>
49 Divided over <span
class=\"number\">$payments</span>
monthly payments, that would be $<span
class=\"number\">$monthly</span> each.</
p>";
50
51 ?>
52 </body>
53 </html>
ptg18144795
88 Chapter 4
Incrementing and
Decrementing
a Number
PHP, like most programming languages,
includes shortcuts that let you avoid ugly
constructs such as
$tax = $tax + 1;
When you need to increase the value of
a variable by 1 (known as an
incremental
adjustment) or decrease the value of a
variable by 1 (a
decremental
adjustment),
you can use
++
and
--
, respectively:
$var = 20; // 20
$var++; // 21
$var++; // 22
$var--; // 21
Solely for the sake of testing this concept,
you’ll rewrite the
handle_calc.php
script
one last time.
To increment the value of a variable:
1. Open
handle_calc.php
in your text
editor or IDE, if it is not already open
(Script 4.4).
2. Change the tax rate calculation from
Script 4.3 to read as follows (Script 4.5):
$taxrate = $tax / 100;
$taxrate++;
The first line calculates the tax rate
as the
$tax
value divided by 100. The
second line increments this value by 1
so that it can be multiplied by the total
to determine the total with tax.
3. Save the script, place it in the same
directory as
calculator.html
, and test
it in your browser A B.
Script 4.5 Incrementing or decrementing a
number is a common operation using
++
or
––
,
respectively.
1 <!doctype html>
2 <html lang="en">
3 <head>
4 <meta charset="utf-8">
5 <title>Product Cost Calculator</
title>
6 <style type="text/css">
7 .number { font-weight: bold;}
8 </style>
9 </head>
10 <body>
11 <?php // Script 4.3 - handle_calc.php #4
12 /* This script takes values from
calculator.html and performs
13 total cost and monthly payment
calculations. */
14
15 // Address error handling, if you want.
16
17 // Get the values from the $_POST array:
18 $price = $_POST['price'];
19 $quantity = $_POST['quantity'];
20 $discount = $_POST['discount'];
21 $tax = $_POST['tax'];
22 $shipping = $_POST['shipping'];
23 $payments = $_POST['payments'];
24
25 // Calculate the total:
26 $total = (($price * $quantity) +
$shipping) - $discount;
27
28 // Determine the tax rate:
29 $taxrate = $tax / 100;
30 $taxrate++;
31
32 // Factor in the tax rate:
33 $total = $total * $taxrate;
34
35 // Calculate the monthly payments:
36 $monthly = $total / $payments;
37
38 // Apply the proper formatting:
39 $total = number_format ($total, 2);
40 $monthly = number_format ($monthly, 2);
41
code continues on next page
ptg18144795
Using Numbers 89
Although functionally it doesn’t matter
whether you code
$taxrate
=
$taxrate
+
1;
or the abbreviated
$taxrate++
, the latter
method (using the increment operator) is more
professional and common.
In Chapter 6, you’ll see how the increment
operator is commonly used in conjunction
with loops.
A The last execution of the form. B It won’t affect your calculations if you use the
long or short version of incrementing a variable
(compare Scripts 4.4 and 4.5).
Script 4.5 continued
42 // Print out the results:
43 print "<p>You have selected to
purchase:<br>
44 <span class=\"number\">$quantity</span>
widget(s) at <br>
45 $<span class=\"number\">$price</span>
price each plus a <br>
46 $<span class=\"number\">$shipping</span>
shipping cost and a <br>
47 <span class=\"number\">$tax</span>
percent tax rate.<br>
48 After your $<span
class=\"number\">$discount</span>
discount, the total cost is
49 $<span class=\"number\">$total</
span>.<br>
50 Divided over <span
class=\"number\">$payments</span>
monthly payments, that would be $<span
class=\"number\">$monthly</span> each.</
p>";
51
52 ?>
53 </body>
54 </html>
Arithmetic Assignment
Operators
PHP also supports a combination of
mathematical and assignment operators.
These are
+=
,
-=
,
*=
, and
/=
. Each will
assign a value to a variable by perform-
ing a calculation on it. For example, these
next two lines both add 5 to a variable:
$num = $num + 5;
$num += 5;
This means the
handle_calc.php
script
could determine the tax rate using this:
$tax = $_POST['tax']; // Say, 5
$tax /= 100; // Now $tax is .05
$tax += 1; // 1.05
You’ll frequently see these shorthand
ways of performing arithmetic.
ptg18144795
90 Chapter 4
Creating Random
Numbers
The last function you’ll learn about in this
chapter is
mt_rand()
, a random-number
generator. All it does is output a random
number:
$n = mt_rand(); // 31
$n = mt_rand(); // 87
The
mt_rand()
function can also take
minimum and maximum parameters, if you
prefer to limit the generated number to a
specific range:
$n = mt_rand(0, 10);
These values are
inclusive
, so in this case
0 and 10 are feasible returned values.
As an example of generating random
numbers, let’s create a simple “Lucky
Numbers” script.
To generate random numbers:
1. Begin a new document in your text
editor or IDE, to be named
random.php
(Script 4.6):
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Lucky Numbers</title>
</head>
<body>
2. Include the PHP tag and address error
management, if you need to:
<?php // Script 4.6 - random.php
Script 4.6 The
rand()
function generates a
random number.
1 <!doctype html>
2 <html lang="en">
3 <head>
4 <meta charset="utf-8">
5 <title>Lucky Numbers</title>
6 </head>
7 <body>
8 <?php // Script 4.6 - random.php
9 /* This script generates 3 random
numbers. */
10
11 // Address error handling, if you want.
12
13 // Create three random numbers:
14 $n1 = mt_and(1, 99);
15 $n2 = mt_rand(1, 99);
16 $n3 = mt_rand(1, 99);
17
18 // Print out the numbers:
19 print "<p>Your lucky numbers are:<br>
20 $n1<br>
21 $n2<br>
22 $n3</p>";
23
24 ?>
25 </body>
26 </html>
ptg18144795
Using Numbers 91
3. Create three random numbers:
$n1 = mt_rand(1, 99);
$n2 = mt_rand(1, 99);
$n3 = mt_rand(1, 99);
This script prints out a person’s lucky
numbers, like those found on the back
of a fortune cookie. These numbers are
generated by calling the
mt_rand()
function three separate times and assign-
ing each result to a different variable.
4. Print out the numbers:
print "<p>Your lucky numbers
are:<br>
$n1<br>
$n2<br>
$n3</p>";
The
print
statement is fairly simple.
The numbers are printed, each on its
own line, by using the HTML break tag.
5. Close the PHP code and the HTML
page:
?>
</body>
</html>
6. Save the file as
random.php
, place it
in the proper directory for your PHP-
enabled server, and test it in your
browser A. Refresh the page to see
different numbers B.
The
getrandmax()
function returns the
largest possible random number that can be
created using
mt_rand()
. This value differs
by operating system.
PHP has other functions for generating
random numbers, such as
random_int()
.
Unlike
mt_rand()
,
random_init()
creates
cryptographically secure random numbers.
A The three random numbers
created by invoking the
mt_rand()
function.
B Running the script again
produces different results.
ptg18144795
92 Chapter 4
Review and Pursue
If you have any problems with the
review questions or the pursue prompts,
turn to the book’s supporting forum
(www.LarryUllman.com/forums/).
Review
n
What are the four primary arithmetic
operators?
n
Why will the following code not work:
print "The total is $$total";
What must be done instead?
n
Why must an HTML page that contains
a form that’s being submitted to a PHP
script be loaded through a URL?
n
What functions can be used to
format numerical values? How do you
format numbers to a specific number
of decimals?
n
What is the importance of operator
precedence?
n
What are the incremental and decre-
mental operators?
n
What are the arithmetic assignment
operators?
Pursue
n
Look up the PHP manual page for one
of the new functions mentioned in this
chapter. Use the links on that page to
investigate a couple of other number-
related functions that PHP has.
n
Create another HTML form for taking
numeric values. Then create the PHP
script that receives the form data,
performs some calculations, formats
the values, and prints the results.
Other Mathematical Functions
PHP has a number of built-in functions
for manipulating mathematical data.
This chapter introduced
round()
,
number_format()
, and
mt_rand()
.
PHP has broken
round()
into two other
functions. The first,
ceil()
, rounds
every number to the next highest integer.
The second,
floor()
, rounds every
number to the next lowest integer.
Another function the calculator page
could make good use of is
abs()
, which
returns the absolute value of a number.
In case you dont remember your abso-
lute values, the function works like this:
$number = abs(-23); // 23
$number = abs(23); // 23
In layman’s terms, the absolute value of
a number is always a positive number.
Beyond these functions, PHP supports
all the trigonometry, exponent, base
conversion, and logarithm functions
you’ll ever need. See the PHP manual for
more information.
ptg18144795
As introduced in Chapter 2, “Variables,
a second category of variables used by
PHP is strings—a collection of characters
enclosed within either single or double
quotation marks. The value of a string
variable may be a single letter, a word, a
sentence, a paragraph, HTML code, or even
a jumble of nonsensical letters, numbers,
and symbols (which might represent a
password). Strings may be the most com-
mon variable type used in PHP.
This chapter covers PHP’s most basic
built-in functions and operators for manipu-
lating string data, regardless of whether
the string originates from a form or is first
declared within the script. Some common
techniques will be introduced: joining strings
together, trimming strings, and encoding
strings. Other uses for strings are illustrated
in subsequent chapters.
5
Using
Strings
In This Chapter
Creating the HTML Form 94
Concatenating Strings 97
Handling Newlines 101
HTML and PHP 104
Encoding and Decoding Strings 108
Finding Substrings 113
Replacing Parts of a String 117
Review and Pursue 120
ptg18144795
94 Chapter 5
Creating the
HTML Form
As in Chapter 3, “HTML Forms and PHP,
let’s begin by creating an HTML form that
sends different values—in the form of string
variables—to a PHP script. The theoretical
example being used is an online bulletin
board or forum where users can post a
message, their email address, and their
first and last names A.
To create the HTML form:
1. Begin a new HTML document in
your text editor or IDE, to be named
posting.html
(Script 5.1):
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Forum Posting</title>
</head>
<body>
<!-- Script 5.1 - posting.html -->
<div><p>Please complete this form
to submit your posting:</p>
2. Create the initial form tag:
<form action="handle_post.php"
method="post">
This form will send its data to the
handle_post.php
script and will use
the POST method.
3. Add inputs for the first name, last name,
and email address:
<p>First Name: <input type="text"
name="first_name" size="20"></p>
<p>Last Name: <input type="text"
name="last_name" size="20"></p>
<p>Email Address: <input type=
"email" name="email"
size="30"></p>
A This HTML form is the basis for most
of the examples in this chapter.
ptg18144795
Using Strings 95
The form uses two basic text input
types and one email type. Remember
that the various inputs’ name values
should adhere to the rules of PHP vari-
able names (no spaces; must not begin
with a number; must consist only of
letters, numbers, and the underscore).
4. Add an input for the posting:
<p>Posting: <textarea name=
"posting" rows="9" cols="30">
</textarea></p>
The posting field is a
textarea
, which
is a larger type of text input box.
5. Create a submit button, and close
the form:
<input type="submit"
name="submit"
value="Send My Posting">
</form>
Every form must have a submit button
(or a submit image).
6. Complete the HTML page:
</div>
</body>
</html>
continues on next page
Script 5.1 This form sends string data to a
PHP script.
1 <!doctype html>
2 <html lang="en">
3 <head>
4 <meta charset="utf-8">
5 <title>Forum Posting</title>
6 </head>
7 <body>
8 <!-- Script 5.1 - posting.html -->
9 <div><p>Please complete this form to
submit your posting:</p>
10
11 <form action="handle_post.php"
method="post">
12
13 <p>First Name: <input type="text"
name="first_name" size="20"></p>
14
15 <p>Last Name: <input type="text"
name="last_name" size="20"></p>
16
17 <p>Email Address: <input type="email"
name="email" size="30"></p>
18
19 <p>Posting: <textarea name="posting"
rows="9" cols="30"></textarea></p>
20
21 <input type="submit" name="submit"
value="Send My Posting">
22
23 </form>
24 </div>
25 </body>
26 </html>
ptg18144795
96 Chapter 5
7. Save the file as
posting.html
, place
it in the appropriate directory on your
PHP-enabled server, and view it in your
browser A.
This is an HTML page, so it doesn’t
have to be on a PHP-enabled server
in order for you to view it. But because
it will eventually send data to a PHP
script, it’s best to place the file on
your server.
Technically speaking, all form data, aside
from uploaded files, is sent to the handling
script as strings. This includes numeric data
entered into text boxes, options selected
from drop-down menus, checkbox or radio
button values, and so forth. Even the form in
Chapter 4, “Using Numbers,” sent strings with
numeric values to the handling script.
Many forum systems written in PHP
are freely available for your use. This book
doesn’t discuss how to fully develop one, but
a multilingual forum is developed in my PHP
and MySQL for Dynamic Web Sites (Fourth
Edition): Visual QuickPro Guide (Peachpit
Press, 2012).
This book’s website has a forum where
readers can post questions and other readers
(and the author) answer questions. You can
find it at www.LarryUllman.com/forums/.
ptg18144795
Using Strings 97
Concatenating Strings
Concatenation
is an unwieldy term but a
useful concept. It refers to the appending
of one item onto another. Specifically, in
programming, you concatenate
strings
.
The period (
.
) is the operator for perform-
ing this action, and it’s used like so:
$s1 = 'Hello, ';
$s2 = 'world!';
$greeting = $s1 . $s2;
The result of this concatenation is that the
$greeting
variable has a value of
Hello,
world!
Because of the way PHP deals with
variables, the same effect could be
accomplished using
$greeting = "$s1$s2";
This code works because PHP replaces
variables within double quotation marks
with their value. However, the formal method
of using the period to concatenate strings is
more commonly used and is recommended
(it will be more obvious what’s occurring in
your code).
Another way of performing concatenation
involves the
concatenation assignment
operator
:
$greeting = 'Hello, ';
$greeting .= 'world!';
This second line roughly means “assign
to
$greeting
its current value plus the
concatenation of
world!
” The end result is
$greeting
having the value
Hello, world!
once again.
The
posting.html
script sends several
string variables to the
handle_post.php
page. Of those variables, the first and last
names could logically be concatenated.
You’ll write the PHP script with this in mind.
ptg18144795
98 Chapter 5
To use concatenation:
1. Begin a new document in your
text editor or IDE, to be named
handle_post.php
(Script 5.2):
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Forum Posting</title>
</head>
<body>
2. Create the initial PHP tag, and address
error management, if necessary:
<?php // Script 5.2 -
handle_post.php
If you don’t have
display_errors
enabled, or if
error_reporting
is set
to the wrong level, see Chapter 3 for
the lines to include here to alter those
settings.
3. Assign the form data to local variables:
$first_name =
$_POST['first_name'];
$last_name =
$_POST['last_name'];
$posting = $_POST['posting'];
The form uses the POST method, so
all the form data will be available in
$_POST
.
This example doesn’t have a line for the
email address because you won’t be
using it yet, but you can replicate this
code to reference that value as well.
Script 5.2 This PHP script demonstrates
concatenation, one of the most common
manipulations of a string variable. Think of it as
addition for strings.
1 <!doctype html>
2 <html lang="en">
3 <head>
4 <meta charset="utf-8">
5 <title>Forum Posting</title>
6 </head>
7 <body>
8 <?php // Script 5.2 - handle_post.php
9 /* This script receives five values from
posting.html:
10 first_name, last_name, email, posting,
submit */
11
12 // Address error management, if you
want.
13
14 // Get the values from the $_POST array:
15 $first_name = $_POST['first_name'];
16 $last_name = $_POST['last_name'];
17 $posting = $_POST['posting'];
18
19 // Create a full name variable:
20 $name = $first_name . ' ' .
$last_name;
21
22 // Print a message:
23 print "<div>Thank you, $name, for your
posting:
24 <p>$posting</p></div>";
25
26 ?>
27 </body>
28 </html>
ptg18144795
Using Strings 99
4. Create a new
$name
variable using
concatenation:
$name = $first_name . ' ' .
$last_name;
This act of concatenation takes two
variables plus a space and joins them
all together to create a new variable,
named
$name
. Assuming that you
entered
Elliott
and
Smith
as the names,
$name
would be equal to
Elliott Smith
.
5. Print out the message to the user:
print "<div>Thank you, $name,
for your posting:
<p>$posting</p></div>";
This message reports back to the user
what was entered in the form.
6. Close the PHP section and complete
the HTML page:
?>
</body>
</html>
7. Save your script as
handle_post.php
,
place it in the same directory as
posting.html
(on your PHP-enabled
server), and test both the form and the
script in your browser A B.
As a reminder, you must load the form
through a URL (
http
:
//something
) so that,
when the form is submitted, the handling
PHP script is also run through a URL.
A The HTML form in use…
B …and the resulting PHP page.
ptg18144795
100 Chapter 5
You can link as many strings as you
want using concatenation. You can even join
numbers to strings:
$new_string = $s1 . $s2 . $number;
This works because PHP is weakly typed,
meaning that its variables aren’t locked in to
one particular format. Here, the
$number
vari-
able will be turned into a string and appended
to the value of the
$new_string
variable.
Concatenation can be used in many
ways, even when feeding arguments to a
function. An uncommon but functional
example would be
$text = nl2br($heading . $body);
The
nl2br()
function, first mentioned in
Chapter 1, “Getting Started with PHP,” will be
discussed in detail next.
If you used quotation marks of any kind
in your form and saw extraneous slashes in
the printed result, see the sidebar “Magic
Quotes” in Chapter 3 for an explanation of
the cause and for the fix. This is uncommon
in current versions of PHP.
As a reminder, it’s important to under-
stand the difference between single and
double quotation marks in PHP. Characters
within single quotation marks are treated
literally; characters within double quotation
marks are interpreted (for example, a variable’s
name will be replaced by its value). See
Chapter 3 for a refresher.
Taking the first and last names as
separate inputs makes for a good concatena-
tion example. However, not everyone has just
two names, and it’s best not to make such
assumptions in your own registration forms.
A more inclusive example would have a single
input for the user’s name.
ptg18144795
Using Strings 101
Handling Newlines
A common question beginning PHP devel-
opers have involves handling newlines
in strings. The
textarea
form element
allows a user to enter text over multiple
lines by pressing Return/Enter. Each use
of Return/Enter equates to a newline in
the resulting string. These newlines work
within a
textarea
but have no effect on a
rendered PHP page A B.
To create the equivalent of newlines in a
rendered web page, you use the break tag:
<br>
. Fortunately, PHP has the
nl2br()
function, which automatically converts
newlines into break tags:
$var = nl2br($var);
Let’s apply this function to
handle_post.php
so that the user’s posting retains its
formatting.
To convert newlines to breaks:
1. Open
handle_post.php
(Script 5.2)
in your text editor or IDE, if it is not
already open.
continues on next page
A Newlines in form data like textareas…
B …are not rendered by the browser.
ptg18144795
102 Chapter 5
2. Apply the
nl2br()
function when
assigning a value to the
$posting
variable (Script 5.3):
$posting = nl2br($_POST
['posting'], false);
Now
$posting
will be assigned the
value of
$_POST['posting']
, with any
newlines converted to HTML break tags.
The second argument to the function—
the Boolean
false
—says that you
do
not want
XHTML-compliant break tags
created. In other words, the default
behavior is for this function to replace
newlines with
<br
/>
. In HTML5,
<br>
is more commonly used.
Script 5.3 When you use the
nl2br()
function,
newlines entered into the posting
textarea
are
honored when displayed in the browser.
1 <!doctype html>
2 <html lang="en">
3 <head>
4 <meta charset="utf-8">
5 <title>Forum Posting</title>
6 </head>
7 <body>
8 <?php // Script 5.3 - handle_post.php #2
9 /* This script receives five values from
posting.html:
10 first_name, last_name, email, posting,
submit */
11
12 // Address error management, if you
want.
13
14 // Get the values from the $_POST array:
15 $first_name = $_POST['first_name'];
16 $last_name = $_POST['last_name'];
17 $posting = nl2br($_POST['posting'],
false);
18
19 // Create a full name variable:
20 $name = $first_name . ' ' . $last_name;
21
22 // Print a message:
23 print "<div>Thank you, $name, for your
posting:
24 <p>$posting</p></div>";
25
26 ?>
27 </body>
28 </html>
ptg18144795
Using Strings 103
3. Save the file, place it in the same
directory as
posting.html
(on your
PHP-enabled server), and test again
in your browser C.
Newlines can also be inserted into
strings by placing the newline character—
\n
between double quotation marks.
Other HTML tags, such as paragraph
tags, also affect spacing in the rendered web
page. You can turn newlines (or any character)
into paragraph tags using a replacing function,
but the code for doing so is far more involved
than just invoking
nl2br()
.
Newlines present in strings sent to the
browser will have an effect, but only in the
HTML source of the page D.
C Now the same submitted data A is properly
displayed over multiple lines in the browser.
D The HTML source, corresponding to B, shows
the effect that newlines have in the browser (i.e.,
they add spacing within the HTML source code).
ptg18144795
104 Chapter 5
HTML and PHP
As stated several times over by now, PHP
is a server-side technology that’s fre-
quently used to send data to the browser.
This data can be in the form of plain text,
HTML code, or, more commonly, both.
In this chapter’s primary example, data is
entered in an HTML form and then printed
back to the browser using PHP. A potential
problem is that the user can enter HTML
characters in the form, which can affect
the resulting page’s formatting A B—or,
worse, cause security problems.
You can use a few PHP functions to
manipulate HTML tags within PHP string
variables:
n
htmlspecialchars()
converts certain
HTML tags into their entity versions.
n
htmlentities()
turns all HTML tags
into their entity versions.
n
strip_tags()
removes all HTML and
PHP tags.
The first two functions turn an HTML tag
(for example,
<span>
) into an entity ver-
sion like
&lt;span&gt;
. The entity version
appears in the output but isn’t rendered.
You might use either of these if you wanted
to display code without enacting it. The
third function,
strip_tags()
, removes
HTML and PHP tags entirely.
A If the user enters HTML code in the posting…
B …it’s rendered by the browser when reprinted.
ptg18144795
Using Strings 105
You ought to watch for special tags in
user-provided data for two reasons. First,
as already mentioned, submitted HTML
would likely affect the rendered page
(for example, mess up a table, tweak the
CSS, or just add formatting where there
shouldn’t be any). The second concern
is more important. Because JavaScript is
placed within HTML
script
tags, a malicious
user could submit JavaScript that would
be executed when it’s redisplayed on the
page C. This is how
cross-site scripting
(XSS) attacks are performed.
To see the impact these functions have,
this next rewrite of
handle_post.php
will
use each of them and display the respec-
tive results.
C Displaying HTML submitted by a user in a
browser can have terrible consequences, such as
the execution of JavaScript.
ptg18144795
106 Chapter 5
To address HTML in PHP:
1. Open
handle_post.php
(Script 5.3)
in your text editor or IDE, if it is not
already open.
2. Before the
print
line, add the following
(Script 5.4):
$html_post = htmlentities
($_POST['posting']);
$strip_post = strip_tags
($_POST['posting']);
To clarify the difference between how
these two functions work, apply them
both to the posting text, creating two
new variables in the process. Refer
to
$_POST['posting']
here and not
$posting
because
$posting
already
reflects the application of the
nl2br()
function, which means that break tags
may have been introduced that were
not explicitly entered by the user.
3. Alter the
print
statement to read
as follows:
print "<div>Thank you, $name,
for your posting:
<p>Original: $posting</p>
<p>Entity: $html_post</p>
<p>Stripped: $strip_post</p>
</div>";
To highlight the different results, print
out the three different versions of the
posting text. First is the original posting
as it was entered, after being run through
nl2br()
. Next is the
htmlentities()
version of the posting, which will show
the HTML tags without rendering them.
Finally, the
strip_tags()
version will
be printed; it doesn’t include any HTML
(or PHP) tags.
Script 5.4 This version of the PHP script addresses
HTML tags in two different ways.
1 <!doctype html>
2 <html lang="en">
3 <head>
4 <meta charset="utf-8">
5 <title>Forum Posting</title>
6 </head>
7 <body>
8 <?php // Script 5.4 - handle_post.php #3
9 /* This script receives five values from
posting.html:
10 first_name, last_name, email, posting,
submit */
11
12 // Address error management, if you
want.
13
14 // Get the values from the $_POST array:
15 $first_name = $_POST['first_name'];
16 $last_name = $_POST['last_name'];
17 $posting = nl2br($_POST['posting']);
18
19 // Create a full name variable:
20 $name = $first_name . ' ' . $last_name;
21
22 // Adjust for HTML tags:
23 $html_post =
htmlentities($_POST['posting']);
24 $strip_post =
strip_tags($_POST['posting']);
25
26 // Print a message:
27 print "<div>Thank you, $name, for
your posting:
28 <p>Original: $posting</p>
29 <p>Entity: $html_post</p>
30 <p>Stripped: $strip_post</p></div>";
31
32 ?>
33 </body>
34 </html>
ptg18144795
Using Strings 107
4. Save the file, place it in the same
directory as
posting.html
(on your
PHP-enabled server), and test it again
in your browser D E.
If you view the HTML source code of
the resulting PHP page F, you’ll also
see the effect that applying these func-
tions has.
For security purposes, it’s almost
always a good idea to use
htmlentities()
,
htmlspecialchars()
, or
strip_tags()
to
any user-provided data that’s being printed
to the browser. The only reason I don’t do so
in this book is to minimize clutter.
Today’s browsers can identify and block
execution of potentially malicious JavaScript,
although you should not rely on that behavior.
The
html_entity_decode()
function
does just the opposite of
htmlentities()
,
turning HTML entities into their respective
HTML code.
Another useful function for outputting
strings in the browser is
wordwrap()
. This
function wraps a string to a certain number
of characters.
To turn newlines into breaks while
still removing any HTML or PHP tags, apply
nl2br()
after
strip_tags()
:
$posting = nl2br(strip_tags
($_POST['posting']));
In that line, the
strip_tags()
function will
be called first, and its result will be sent to
the
nl2br()
function.
D The HTML characters entered as part of a
posting will now be addressed by PHP.
E The resulting PHP page shows the original post
as it would look if printed without modification,
the effect of
htmlentities()
, and the effect of
strip_tags()
.
F The HTML source for the content displayed in E.
ptg18144795
108 Chapter 5
Encoding and
Decoding Strings
At the end of Chapter 3, the section
“Manually Sending Data to a Page” demon-
strated how to use the thinking behind the
GET form method to send data to a page.
In that example, instead of using an actual
form, data was appended to the URL, mak-
ing it available to the receiving script. I was
careful to say that only single words could
be passed this way, without spaces or
punctuation. But what if you want to pass
several words as one variable value or use
special characters?
To safely pass any value to a PHP script
through the URL, apply the
urlencode()
function. As its name implies, this function
takes a string and
encodes
it (changes its
format) so that it can properly be passed
as part of a URL. Among other things, the
function replaces spaces with plus signs
(
+
) and translates special characters (for
example, the apostrophe) into less prob-
lematic versions. You can use the function
like so:
$string = urlencode($string);
To demonstrate one application of
urlencode()
, let’s update the
handle_
post.php
page so that it also creates a
link that passes the user’s name and email
address to a third page.
ptg18144795
Using Strings 109
To use urlencode():
1. Open
handle_post.php
(Script 5.4)
in your text editor or IDE, if it is not
already open.
2. Delete the
htmlentities()
and
strip_tags()
lines added in the previ-
ous set of steps (Script 5.5).
3. Revert to the older version of the
print invocation:
print "<div>Thank you, $name,
for your posting:
<p>$posting</p></div>";
4. After the
print
statement, add the
following:
$name = urlencode($name);
$email = urlencode($_POST
['email']);
This script will pass these two variables
to a second page. In order for it to do
so, they must both be encoded.
Because the script has not previously
referred to or used the
$email
vari-
able, the second line both retrieves the
email value from the
$_POST
array and
encodes it in one step. This is the same
as having these two separate lines:
$email = $_POST['email'];
$email = urlencode($email);
continues on next page
Script 5.5 This script encodes two variables
before adding them to a link. Then the values can
be successfully passed to another page.
1 <!doctype html>
1 <html lang="en">
2 <head>
3 <meta charset="utf-8">
4 <title>Forum Posting</title>
5 </head>
6 <body>
7 <?php // Script 5.5 - handle_post.php #4
8 /* This script receives five values from
posting.html:
9 first_name, last_name, email, posting,
submit */
10
11 // Address error management, if you
want.
12
13 // Get the values from the $_POST array:
14 $first_name = $_POST['first_name'];
15 $last_name = $_POST['last_name'];
16 $posting = nl2br($_POST['posting']);
17
18 // Create a full name variable:
19 $name = $first_name . ' ' . $last_name;
20
21 // Print a message:
22 print "<div>Thank you, $name, for your
posting:
23 <p>$posting</p></div>";
24
25 // Make a link to another page:
26 $name = urlencode($name);
27 $email = urlencode($_POST['email']);
28 print "<p>Click <a href=\"thanks.php?
name=$name&email=$email\">here</a> to
continue.</p>";
29
30 ?>
31 </body>
32 </html>
ptg18144795
110 Chapter 5
5. Add another
print
statement that
creates the link:
print "<p>Click <a href=\
"thanks.php?name=$name&email=
$email\">here</a> to continue.
</p>";
The primary purpose of this
print
statement is to create an HTML link
in the web page, the source code of
which would be something like
<a href="thanks.php?name=
Larry+Ullman&email=
larry%40example.com">here</a>
To accomplish this, begin by hard-coding
most of the HTML and then include the
appropriate variable names. Because
the HTML code requires that the URL
for the link be in double quotation marks
—and the
print
statement already
uses double quotation marks—you
must escape them (by preceding them
with backslashes) in order for them to
be printed.
6. Save the file, place it in the proper
directory of your PHP-enabled server,
and test it again in your browser A B.
Note that clicking the link will result in
a server error, because the
thanks.php
script hasn’t yet been written.
A Another use of the form.
B The handling script now displays a link to
another page.
ptg18144795
Using Strings 111
7. View the HTML source code of the
handling page to see the resulting link
in the HTML code C.
Values sent directly from a form are auto-
matically URL-encoded prior to being sent and
decoded upon arrival at the receiving script.
You only need the
urlencode()
function to
manually encode data (as in the example).
The
urldecode()
function does just
the opposite of
urlencode()
—it takes an
encoded URL and turns it back into a standard
form. You’ll use it less frequently, though,
because PHP will automatically decode most
values it receives.
Since you can use concatenation with
functions, the new
print
statement could be
written as follows:
print 'Click <a href="thanks.php?
name=' . $name . '&email=' .
$email . '">here</a> to continue.';
This method has two added benefits over the
original approach. First, it uses single quota-
tion marks to start and stop the statement,
meaning you don’t need to escape the double
quotation marks. Second, the variables used
are more obvious—they aren’t buried in a lot of
other code.
C The HTML source code of the page B shows the dynamically generated link.
ptg18144795
112 Chapter 5
Encrypting and Decrypting Strings
Frequently, in order to protect data, programmers
encrypt
it—alter its state by transforming it to a
form that’s more difficult, if not impossible, to discern. Passwords are an example of a value you
might want to encrypt. Depending on the level of security you want to establish, usernames, email
addresses, and phone numbers are likely candidates for encryption too.
You can use the
password_hash()
function to encrypt data, but be aware that no decryption
option is available (it’s known as
one-way
encryption). So a password may be encrypted using
it and then stored, but the decrypted value of the password can never be determined. Using
this function in a web application, you might encrypt a user’s password upon registration; then,
when the user logged in, the password the user entered at that time would also be encrypted,
and the two protected versions of the password would be compared. The syntax for using
password_hash()
is
$data = password_hash($data, PASSWORD_DEFAULT);
The second argument says to use the default encryption algorithm (the algorithm determining how
quickly and securely the encryption is performed).
If the data is being stored in a database, you can also use functions built into the database applica-
tion (for example, MySQL, PostgreSQL, Oracle, or SQL Server) to perform encryption and decryp-
tion. Depending on the technology you’re using, it most likely provides both one- and two-way
encryption tools.
You do not need to encode numeric
PHP values in order to use them in a URL,
because they do not contain problematic
characters. That being said, it won’t hurt to
encode them either.
At the end of the chapter you’ll be
prompted to create
thanks.php
, which greets
the user by name and email address D.
D The third page in this process—to be created by you at the end of the chapter—prints a message based
on values it receives in the URL.
ptg18144795
Using Strings 113
Finding Substrings
PHP has a few functions you can use to
pull apart strings, search through them,
and perform comparisons. Although these
functions are normally used with condi-
tionals, discussed in Chapter 6, “Control
Structures,” they are important enough that
they’ll be introduced here; later chapters
will use them more formally.
Earlier in this chapter,
you learned how
to join strings using concatenation. Along
with making larger strings out of smaller
pieces, PHP easily lets you extract subsec-
tions from a string. The trick to using any
method to pull out a subsection of a string
is that you must know something about the
string itself in order to know how to break
it up.
The
strtok()
function creates a substring,
referred to as a
token
, from a larger string
by using a predetermined separator (such
as a comma or a space). For example, if
you have users enter their full name in one
field (presumably with their first and last
names separated by a space), you can pull
out their first name with this code:
$first = strtok($_POST['name'], ' ');
That line tells PHP to extract everything
from the beginning of
$_POST['name']
until it finds a blank space.
If you have users enter their full name in
the format
Surname, First
, you can find
their surname by writing
$last = strtok($_POST['name'], ', ');
Comparing Strings
To compare two strings, you can always
use the equality operator, which you’ll
learn about in the next chapter. Other-
wise, you can use the
strcmp()
function.
It indicates how two strings compare
by returning a whole number: 0 if they
are the same, and a positive or negative
number if one is “greater” than the other.
PHP also has a case-insensitive compan-
ion,
strcasecmp()
.
To see if a substring is contained within
another string (that is, to find a needle in
a haystack), you’ll use these functions:
.
strstr()
returns the haystack from
the first occurrence of a needle to the
end.
.
strpos()
searches through a hay-
stack and returns the numeric loca-
tion of a particular needle.
Both of these functions also have a case-
insensitive alternative:
stristr()
and
stripos()
, respectively. Each of these
functions is normally used in a conditional
to test whether the substring was found.
ptg18144795
114 Chapter 5
A second way to pull out sections of a
string is by referring to the
indexed position
of the characters within the string. The
indexed position of a string is the numeri-
cal location of a character, counting from
the beginning. However, PHP—like most
programming languages—begins all indexes
with the number 0. For example, to index
the string
Larry
, you begin with the L at
position 0, followed by
a
at 1,
r
at 2, the
second
r
at 3, and
y
at 4. Even though the
string length of
Larry
is 5, its index goes
from 0 to 4. In short, indexes always go
from 0 to the length minus 1.
With this in mind, you can call on the
substr()
function to create a substring
based on the index position of the sub-
string’s characters:
$sub = substr($string, 0, 10);
The first argument is the master string from
which the substring will be derived. Second,
indicate where the substring begins, as its
indexed position (0 means that you want
to start with the first character). Third, from
that starting point, state how many char-