main-content

Make your websites more dynamic by adding a feedback form, creating a private area where members can upload images that are automatically resized, or perhaps storing all your content in a database. David Powers has updated his definitive book to incorporate the latest techniques and changes to PHP, including the arrival of PHP 7. New features include the spaceship and null coalesce operators, generators, using array shorthand syntax for list(), array dereferencing, and array unpacking with the splat operator.

The problem is, you're not a programmer and the thought of writing code sends a chill up your spine. Or maybe you've dabbled a bit in PHP and MySQL, but you can't get past baby steps. If this describes you, then you've just found the right book. PHP and the MySQL database are deservedly the most popular combination for creating dynamic websites. They're free, easy to use, and provided by many web hosting companies in their standard packages. This book also covers MariaDB, a seamless replacement for MySQL that has been adopted on many web servers.

Unfortunately, most PHP books either expect you to be an expert already or force you to go through endless exercises of little practical value. In contrast, this book gives you real value right away through a series of practical examples that you can incorporate directly into your sites, optimizing performance and adding functionality such as file uploading, email feedback forms, image galleries, content management systems, and much more. Each solution is created with not only functionality in mind, but also visual design.

But this book doesn't just provide a collection of ready-made scripts: each PHP solution builds on what's gone before, teaching you the basics of PHP and database design quickly and painlessly. By the end of the book, you'll have the confidence to start writing your own scripts or—if you prefer to leave that task to others—to adapt existing scripts to your own requirements. Right from the start, you're shown how easy it is to protect your sites by adopting secure coding practices.

What You Will Learn

Design and build dynamic PHP-based web sites and applications

Get started right away through practical examples that you can reuse

Incorporate PHP 7 elements including new ways of handling arrays Work with the latest PHP 7 techniques, innovations, and best practices

Who This Book Is For

Readers should have at least some prior exposure to web development using PHP.

### Chapter 1. What Is PHP—And Why Should I Care?

Abstract
PHP is often described by its critics as one of the worst programming languages, yet it’s also one of the most popular. It helps power Google, Yahoo, and Wikipedia, among others. According to Web Technology Surveys ( https://w3techs.com/technologies/details/pl-php/all/all ), it’s deployed on more than four in every five web sites that use a server-side language. So, PHP has obviously got something going for it. Indeed, it has. PHP was specifically designed for building dynamic web sites. It’s free; it has a very gentle learning curve; and this book will show you how to put it to practical use.
David Powers

### Chapter 2. Getting Ready to Work with PHP

Abstract
Now you’ve decided to use PHP to enrich your web pages, you need to make sure that you have everything you need to get on with the rest of this book. Although you can test everything on your remote server, it’s usually more convenient to test PHP pages on your local computer. Everything you need to install is free. In this chapter, I’ll explain the various options for Windows and macOS. The necessary components are normally installed by default on Linux.
David Powers

### Chapter 3. How to Write PHP ScriptsPHP Scripts

Abstract
This chapter offers a quick overview of how PHP works and gives you the basic rules. It’s aimed primarily at readers who have no previous experience of PHP or coding. Even if you’ve worked with PHP before, check the main headings to see what this chapter contains and brush up your knowledge on any aspects that you’re a bit hazy about.
David Powers

### Chapter 4. PHP: A Quick ReferencePHP Scripts

Abstract
Whereas the previous chapter offered a bird’s eye view of PHP for beginners, this chapter goes into detail. It’s not intended to be read at a single sitting. Dip into it when you need to find out how to do something specific, such as build an array or use a loop to repeat an action. The following sections don’t attempt to cover every aspect of PHP, but they’ll help expand your understanding of the rest of the book.
David Powers

Abstract
The ability to include the contents of one file inside another is one of the most powerful features of PHP. It’s also one of the easiest to implement. This means code can be incorporated into multiple pages—for example, common elements, such as a header, footer, or navigation menu. PHP merges the content into each page on the server, allowing you to update a menu or other common elements by editing and uploading a single file—a great timesaver.
David Powers

### Chapter 6. Bringing Forms to Life

Abstract
Forms lie at the very heart of working with PHP. You use forms for logging in to restricted pages, registering new users, placing orders with online stores, entering and updating information in a database, sending feedback … and the list goes on. The same principles lie behind all these uses, so the knowledge you gain from this chapter will have practical value in most PHP applications. To demonstrate how to process information from a form, I’m going to show you how to gather feedback from visitors to your site and send it to your mailbox.
David Powers

### Chapter 7. Using PHP to Manage Files

Abstract
PHP has a huge range of functions designed to work with the server’s file system, but finding the right one for the job isn’t always easy. This chapter cuts through the tangle to show you some practical uses of these functions, such as reading and writing text files to store small amounts of information without a database. Loops play an important role in inspecting the contents of the file system, so you’ll also explore some of the Standard PHP Library (SPL) iterators that are designed to make loops more efficient.
David Powers

### Chapter 8. Working with ArraysPHP

Abstract
Arrays are one of the most versatile data types in PHP. Their importance is reflected by the fact that there are more than 80 core functions dedicated to handling data stored in arrays. They can be generally categorized as for modifying, sorting, comparing, and extracting information from arrays. This chapter doesn’t attempt to cover all of them. It focuses on some of the more interesting and useful applications of manipulating arrays.
David Powers

Abstract
PHP’s ability to handle forms isn’t restricted to text. It can also be used to upload files to a server. For instance, you could build a real estate web site for clients to upload pictures of their properties or a site for all your friends and relatives to upload their holiday photos. However, just because you can do it doesn’t necessarily mean that you should. Allowing others to upload material to your web site could expose you to all sorts of problems. You need to make sure that images are the right size, that they’re of suitable quality, and that they don’t contain any illegal material. You also need to ensure that uploads don’t contain malicious scripts. In other words, you need to protect your web site just as carefully as your own computer.
David Powers

### Chapter 10. Generating Thumbnail ImagesThumbnail images

Abstract
PHP has an extensive range of functions designed to work with images. You’ve already met one of them, getimagesize(), in Chapter 5. As well as providing useful information about an image’s dimensions, PHP can manipulate images by resizing or rotating them. It can also add text dynamically without affecting the original and can even create images on the fly.
David Powers

### Chapter 11. Pages That Remember: Simple Login and Multipage Forms Sessions

Abstract
The Web is a brilliant illusion. When you visit a well-designed web site, you get a great feeling of continuity, as though flipping through the pages of a book or a magazine. Everything fits together as a coherent entity. The reality is quite different. Each part of an individual page is stored and handled separately by the web server. Apart from needing to know where to send the relevant files, the server has no interest in who you are. Each time a PHP script runs, the variables exist only in the server’s memory and are normally discarded as soon as the script finishes. Even variables in the $_POST and$_GET arrays have only a brief lifespan. Their value is passed once to the next script and then removed from memory unless you do something with it, such as storing the information in a hidden form field. Even then, it persists only if the form is submitted.
David Powers

### Chapter 12. Getting Started with a DatabaseDatabase design

Abstract
Dynamic web sites take on a whole new meaning in combination with a database. Drawing content from a database allows you to present material in ways that would be impractical—if not impossible—with a static web site. Examples that spring to mind are online stores, such as Amazon.​com; news sites, such as the BBC ( www.bbcnews.com ); and the big search engines, including Google and Bing. Database technology allows these web sites to present thousands, often millions, of unique pages. Even if your ambitions are nowhere near as grandiose, a database can increase your web site’s richness of content with relatively little effort.
David Powers

### Chapter 13. Connecting to a Database with PHP and SQL

Abstract
PHP 7 offers two ways to connect to and interact with a MySQL database: MySQL Improved (MySQLi) and PHP Data Objects (PDO). Which one you choose is an important decision, because they use incompatible code. You can’t mix them in the same database connection. It’s also important not to confuse MySQLi with the original MySQL extension, which is no longer supported in PHP 7. In most cases, the only difference in the names of MySQLi functions is the addition of the letter I (e.g., mysqli_query() instead of mysql_query()). However, the order of arguments is usually different, so converting an old script involves more than just inserting an I into the function name.
David Powers

### Chapter 14. Creating a Dynamic Photo GalleryPhoto gallery

Abstract
The previous chapter concentrated mainly on extracting the contents of the images table as text. This chapter builds on those techniques to develop the mini photo gallery shown in Figure 14-1.
David Powers

### Chapter 15. Managing Content

Abstract
Although you can use phpMyAdmin for a lot of database administration, you might want to set up areas where clients can log in to update some data without giving them full rein of your database. To do so, you need to build your own forms and create customized content management systems.
David Powers

### Chapter 16. Formatting Text and Dates

Abstract
We have some unfinished business left over from the previous chapter. Figure 15-1 in Chapter 15 shows content from the blog table with just the first two sentences of each article displayed and a link to the rest of the article. However, I didn’t show you how it was done. There are several ways to extract a shorter piece of text from the beginning of a longer one. Some are rather crude and usually leave you with a broken word at the end. In this chapter, you’ll learn how to extract complete sentences.
David Powers

### Chapter 17. Pulling Data from Multiple Tables

Abstract
As I explained in Chapter 13, one of the major strengths of a relational database is the ability to link data in different tables by using the primary key from one table as a foreign key in another table. The phpsols database has two tables: images and blog. It’s time to add some more and join them, so that you can assign categories to blog entries and associate images with individual articles.
David Powers

### Chapter 18. Managing Multiple Database TablesMultiple database tables

Abstract
The previous chapter showed you how to use INNER JOIN and LEFT JOIN to retrieve information stored in multiple tables. You also learned how to link existing tables by adding an extra column to the child table and updating each record individually to insert a foreign key. However, most of the time you’ll want to insert data simultaneously in both tables. That presents a challenge, because INSERT commands can operate on only one table at a time. You need to handle the insert operations in the correct sequence, starting with the parent table, so that you can get the new record’s primary key and insert it in the child table at the same time as other details. Similar considerations also need to be taken into account when updating and deleting records. The code involved isn’t difficult, but you need to keep the sequence of events clearly in mind as you build the scripts.
David Powers

### Chapter 19. Authenticating Users with a Database

Abstract
Chapter 11 showed you the principles of user authentication and sessions to password protect parts of your web site, but the login scripts all relied on usernames and passwords stored in a CSV file. Keeping user details in a database is both more secure and more efficient. Instead of just storing a list of usernames and passwords, a database can store other details, such as first name, family name, email address, and so on. Databases also give you the option of using either hashing (one-way and irreversible) or encryption (two-way). In the first section of this chapter, we’ll examine the difference between the two. Then you’ll create registration and login scripts for both types of encryption.
David Powers