Preface

Boring websites are static. Interesting websites are dynamic—that is, their content changes. A giant static HTML page listing the names, pictures, descriptions, and prices of all 1,000 products a company has for sale is hard to use and takes forever to load. A dynamic web product catalog that lets you search and filter those products so you see only the six items that meet your price and category criteria is more useful, faster, and much more likely to close a sale.

The PHP programming language makes it easy to build dynamic websites. Whatever interactive excitement you want to create—whether it be as a product catalog, a blog, a photo album, or an event calendar—PHP is up to the task. And after reading this book, you’ll be up to the task of building that dynamic website, too.

Who This Book Is For

This book will be useful for many different kinds of people:

  • A hobbyist who wants to create an interactive website for himself, his family, or a nonprofit organization
  • A website builder who wants to use the PHP setup provided by an ISP or hosting provider
  • A developer or designer who needs to write a plugin or extension for a popular piece of software written in PHP, such as Drupal, WordPress, or MediaWiki
  • A page designer who wants to communicate better with her developer co-workers
  • A JavaScript whiz who wants to build server-side programs that complement her client-side code
  • A Perl, Python, or Ruby programmer who wants to get up to speed with PHP
  • Anybody who wants a straightforward, jargon-free introduction to one of the most popular programming languages for building interactive websites

PHP’s gentle learning curve and approachable syntax make it an ideal “gateway” language for the nontechnical web professional. Learning PHP is aimed at this interested, intelligent, but not necessarily technical individual as well as at programmers familiar with another language who want to learn PHP.

If you are completely new to programming and embarking on your first interactive website, you’ve got the right book in your hands. The beginning chapters will give you a gentle introduction to the syntax of the PHP language and basic computer programming topics as they apply to PHP. Start at the beginning of the book and work your way forward.

If you are familiar with programming in another language but starting your first PHP project, you may want to start with the second section of the book and dip back into the first set of chapters when you have a specific question about syntax or how something basic is done in PHP.

Aside from basic computer literacy (knowing how to type, moving files around, surfing the Web), the only assumption that this book makes about you is that you’re acquainted with HTML. You don’t need to be an HTML wizard, but you should be comfortable with the HTML tags that populate a basic web page, such as <html>, <head>, <body>, <p>, <a>, and <br>. If you’re not familiar with HTML, read Head First HTML and CSS by Elisabeth Robson and Eric Freeman (O’Reilly).

Contents of This Book

This book is designed so that you start at the beginning and work through the chapters in order. For the most part, each chapter depends on material in the previous chapters. Chapters 2 through 13 each end with exercises that test your understanding of the chapter’s content.

Chapter 1 provides some general background on PHP and how it interacts with your web browser and a web server. It also shows some PHP programs and what they do, to give you an idea of what PHP programs look like. Especially if you’re new to programming or building dynamic websites, it is important to read Chapter 1.

The next five chapters give you a grounding in the fundamentals of PHP. Before you can write great literature, you need to learn a little grammar and some vocabulary. That’s what these chapters are for. (Don’t worry—you’ll learn enough PHP grammar and vocabulary right away to start writing some short programs, if not great literature.)

Chapter 2 shows you how to work with different kinds of data, such as pieces of text and numbers. This is important because the web pages that your PHP programs generate are just big pieces of text.

Chapter 3 describes the PHP commands that your programs can use to make decisions. These decisions are at the heart of the “dynamic” in dynamic website. The concepts in Chapter 3 are what you use, for example, to display only those items in a product catalog that fall between two prices a user enters in a web form.

Chapter 4 introduces arrays, which are collections of a bunch of individual numbers or pieces of text. Many frequent activities in PHP programs, such as processing submitted web form parameters or examining information pulled out of a database, involve using arrays.

As you write more complicated programs, you’ll find yourself wanting to repeat similar tasks. Functions, discussed in Chapter 5, help you reuse pieces of your programs.

Chapter 6 shows how data and logic together are combined into objects. Objects are reusable bundles of code that help you structure your programs. Objects also allow you to integrate existing PHP add-ons and libraries into your code.

The next five chapters cover essential tasks in building a dynamic website: interacting with users, saving information, and interacting with other websites.

Chapter 7 supplies details on working with web forms, which are the primary way that users interact with your website.

Chapter 8 discusses databases. A database holds the information that your website displays, such as a product catalog or event calendar. This chapter shows you how to make your PHP programs talk to a database. With the techniques in Chapter 8, your website can do user-specific things such as display sensitive information only to authorized people or tell someone how many new message board posts have been created since she last logged in.

In addition to a database, you might also need to work with data stored in files. Chapter 9 explains to how read and write files from a PHP program.

Next, Chapter 10 details how to keep track of your users. This includes using cookies for transient data, but also users logging in to accounts and tracking session data such as a shopping cart of products.

The last chapter in this section, Chapter 11, delves into how your PHP program can interact with other websites and web services. You can retrieve the contents of other web pages or web APIs to use in your programs. Similarly, you can use PHP to serve up not just regular web pages but API responses to other clients.

Instead of new features you could incorporate into your programs, the next three chapters discuss things that help you be a better programmer.

Chapter 12 explains debugging: finding and fixing errors in your programs.

Chapter 13 shows how to write tests that exercise different parts of your program. These tests provide a way to make sure that your program does what you expect it to do.

Lastly, Chapter 14 talks about some aspects of software engineering that are not specific to PHP but that you should be familiar with as you work on projects with other developers.

The final section of the book is a collection of short explorations into a few common tasks and topics. These are not as fundamental as the material on the basic structure of PHP, or how to store information, but are still things that you’re likely to run into as you spend time with PHP. These chapters give you the basics.

Chapter 15 shows PHP’s powerful and comprehensive set of capabilities for working with dates and times. Chapter 16 discusses package management, with which you have a drop-dead simple way of incorporating useful libraries written by others into your code. Chapter 17 explains how to send email messages from your PHP program. Chapter 18 examines three popular PHP web application frameworks, which can jumpstart your project by eliminating a lot of common boilerplate code. Chapter 19 delves into using PHP from the command line (rather than from a web server), which can be a handy way to write simple utilities or test short programs. Finally, Chapter 20 lays out some techniques for successfully writing PHP programs that flawlessly handle text in different languages and character sets.

The two appendixes provide supplementary material. To run PHP programs, you need to have a copy of the PHP engine installed on your computer (or have an account with a web-hosting provider that supports PHP). Appendix A helps you get up and running, whether you are using Windows, OS X, or Linux.

Appendix B contains the answers to all the exercises in the book. No peeking until you’ve tried the exercises!

What’s Not in This Book

This book is of finite length, so unfortunately it can’t include everything there is to know about PHP. The primary goal of the book is to provide an introduction to PHP and to some of the basics of computer programming.

If you’re already a PHP programmer and are primarily interested in what’s new in PHP 7, Upgrading to PHP 7 by Davey Shafik (O’Reilly) is a great place to look for all the details on what’s new and different in this latest version of PHP. Bruno Skvorc’s compilation of links and references at SitePoint also has a lot of great detail.

Other Resources

The online annotated PHP Manual is a great resource for exploring PHP’s extensive function library. Plenty of user-contributed comments offer helpful advice and sample code, too. Additionally, there are many PHP mailing lists covering installation, programming, extending PHP, and various other topics. You can learn about and subscribe to these mailing lists at php.net. Also worth exploring is the PHP Presentation System archive. This is a collection of presentations about PHP that have been delivered at various conferences.

PHP The Right Way is also a splendid resource for getting to know PHP, especially if you’re familiar with another programming language.

After you’re comfortable with the material in this book, the following books about PHP are good next steps:

  • Programming PHP by Rasmus Lerdorf, Peter MacIntyre, and Kevin Tatroe (O’Reilly). A more detailed and technical look at how to write PHP programs. Includes information on security, XML, and generating graphics.
  • PHP Cookbook by David Sklar and Adam Trachtenberg (O’Reilly). A comprehensive collection of common PHP programming problems and their solutions.
  • Modern PHP by Josh Lockhart (O’Reilly). This book is not about syntax and specific PHP tasks. Instead, it helps you write PHP with consistent, high-quality style and understand good practices for software engineering with PHP: it covers issues such as code deployment, testing, and profiling.

These books are helpful for learning about databases, SQL, and MySQL:

  • Learning PHP, MySQL & JavaScript by Robin Nixon (O’Reilly). Explains how to make PHP, MySQL and JavaScript sing in harmony to make a robust dynamic website.
  • SQL in a Nutshell by Kevin E. Kline, Daniel Kline, and Brand Hunt (O’Reilly). Covers the essentials you need to know to write SQL queries, and covers the SQL dialects used by Microsoft SQL Server, MySQL, Oracle, and PostgreSQL.
  • MySQL Cookbook by Paul DuBois (O’Reilly). A comprehensive collection of common MySQL tasks.
  • MySQL Reference Manual. The ultimate source for information about MySQL’s features and SQL dialect.

Conventions Used in This Book

The following programming and typesetting conventions are used in this book.

Programming Conventions

The code examples in this book are designed to work with PHP 7.0.0. They were tested with PHP 7.0.5, which was the most up-to-date version of PHP 7 available at the time of publication. Where the book references or uses features added in PHP 5.4.0 or later, there is generally a mention of which version the feature was added in.

Typographical Conventions

The following typographical conventions are used in this book:

Italic
Indicates new terms, example URLs, example email addresses, filenames, file extensions, pathnames, and directories.
Constant width
Indicates commands, options, switches, variables, attributes, keys, functions, types, classes, namespaces, methods, modules, properties, parameters, values, objects, events, event handlers, XML tags, HTML tags, macros, the contents of files, or the output from commands.
Constant width italic
Shows text that should be replaced with user-supplied values.
Tip

This icon signifies a tip, suggestion, or general note.

Warning

This icon indicates a warning or caution.

Using Code Examples

Typing some of the example programs in the book yourself is instructive when you are getting started. However, if your fingers get weary, you can download all of the code examples from https://github.com/oreillymedia/Learning_PHP.

This book is here to help you get your job done. In general, you may use the code in this book in your programs and documentation. You do not need to contact the publisher for permission unless you’re reproducing a significant portion of the code. For example, writing a program that uses several chunks of code from this book does not require permission. Selling or distributing a CD-ROM of examples from O’Reilly books does require permission. Answering a question by citing this book and quoting example code does not require permission. Incorporating a significant amount of example code from this book into your product’s documentation does require permission.

We appreciate, but do not require, attribution. An attribution usually includes the title, author, publisher, and ISBN. For example: Learning PHP by David Sklar. Copyright 2016 David Sklar, 978-149-193357-2.” If you feel your use of code examples falls outside fair use or the permission given above, feel free to contact the publisher at permissions@oreilly.com.

Safari® Books Online

Note

Safari Books Online is an on-demand digital library that delivers expert content in both book and video form from the world’s leading authors in technology and business.

Technology professionals, software developers, web designers, and business and creative professionals use Safari Books Online as their primary resource for research, problem solving, learning, and certification training.

Safari Books Online offers a range of plans and pricing for enterprise, government, education, and individuals.

Members have access to thousands of books, training videos, and prepublication manuscripts in one fully searchable database from publishers like O’Reilly Media, Prentice Hall Professional, Addison-Wesley Professional, Microsoft Press, Sams, Que, Peachpit Press, Focal Press, Cisco Press, John Wiley & Sons, Syngress, Morgan Kaufmann, IBM Redbooks, Packt, Adobe Press, FT Press, Apress, Manning, New Riders, McGraw-Hill, Jones & Bartlett, Course Technology, and hundreds more. For more information about Safari Books Online, please visit us online.

Comments and Questions

Please address comments and questions concerning this book to the publisher:

  • O’Reilly Media, Inc.
  • 1005 Gravenstein Highway
  • North Sebastopol, CA 95472
  • (800) 998-9938 (in the United States or Canada)
  • (707) 829-0515 (international or local)
  • (707) 829-0104 (fax)

There is a web page for this book, where we list errata, examples, and any additional information. You can access this page at http://bit.ly/learning_php.

To comment or ask technical questions about this book, send email to .

Or you can contact the author directly via his website, http://www.sklar.com.

For more information about our books, conferences, Resource Centers, and the O’Reilly Network, see our website at http://www.oreilly.com.

Acknowledgments

This book is the end result of the hard work of many people. Thank you to:

  • The many programmers, testers, documentation writers, bug fixers, and other folks whose time, talent, and devotion have made PHP the first-class development platform that it is today. Without them, I’d have nothing to write about.
  • My diligent reviewers: Thomas David Baker and Phil McCluskey. They caught plenty of mistakes, turned confusing explanations into clear ones, and otherwise made this book far better than it would have been without them.
  • My diligent editor: Ally MacDonald. The author is just one of the many pieces it takes to make a book and Ally made sure everything that needed to happen with all of those pieces actually happened!

For a better fate than wisdom, thank you also to Susannah, with whom I continue to enjoy ignoring the syntax of things.

Get Learning PHP now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.