Contents at a Glance
Contents
About the Author
About the Technical Reviewer
Acknowledgments
Introduction
Chapter 1: What Is PHP—And Why Should I Care?
How PHP Has Grown
How PHP Makes Pages Dynamic
Creating Pages That Think for Themselves
How Hard Is PHP to Use and Learn?
Can I Just Copy and Paste the Code?
How Safe Is PHP?
What Software Do I Need to Write PHP?
What to Look for When Choosing a PHP Editor
So, Let’s Get on with It . . .
Chapter 2: Getting Ready to Work with PHP
Checking Whether Your Website Supports PHP
Deciding Where to Test Your Pages
What You Need for a Local Test Environment
Individual Programs or an All-in-one Package?
Setting Up on Windows
Getting Windows to Display Filename Extensions
Choosing a Web Server
Installing an All-in-one Package on Windows
Setting Up on Mac OS X
Installing MAMP
Testing and configuring MAMP
Where to Locate Your PHP Files (Windows & Mac)
Using Virtual Hosts
Checking Your PHP Settings
Displaying the Server Configuration with phpinfo()
Editing php.ini
What’s Next?
Chapter 3: How to Write PHP Scripts
PHP: The Big Picture
Telling the Server to Process PHP
Embedding PHP in a Webpage
Storing PHP in an External File
Using Variables to Represent Changing Values
Naming Variables
Assigning Values to Variables
Ending Commands With a Semicolon
Commenting Scripts
Single-line Comments
Multi-line Comments
Using Arrays to Store Multiple Values
PHP’s Built-in Superglobal Arrays
Understanding When to Use Quotes
Special Cases: True, False, and Null
Making Decisions
Making Comparisons
Using Indenting and Whitespace for Clarity
Using Loops for Repetitive Tasks
Using Functions for Preset Tasks
Understanding PHP Classes and Objects
Displaying PHP Output
Using Echo Shortcut Syntax
Joining Strings Together
Working With Numbers
Understanding PHP Error Messages
Why is My Page Blank?
Handling Exceptions
PHP: A Quick Reference
Using PHP in an Existing Website
Data Types in PHP
Doing Calculations with PHP
Arithmetic Operators
Determining the Order of Calculations
Combining Calculations and Assignment
Adding to an existing string
All You Ever Wanted to Know About Quotes—and More
How PHP Treats Variables Inside Strings
Using Escape Sequences Inside Double Quotes
Embedding Associative Array Elements in a String
Avoiding the Need to Escape Quotes with Heredoc Syntax
Creating Arrays
Building an Indexed Array
Building an Associative Array
Creating an Empty Array
Multidimensional Arrays
Using Print_r( ) to Inspect An Array
The Truth According to PHP
Explicit Boolean Values
Implicit Boolean (“Truthy” and “Falsy”) Values
Making Decisions by Comparing Two Values
Testing More Than One Condition
Using the Switch Statement for Decision Chains
Using the Ternary Operator
Creating Loops
Loops Using While and Do . . . While
The Versatile for Loop
Looping Through Arrays and Objects with Foreach
Breaking Out Of a Loop
Modularizing Code with Functions
Passing Values to F unctions
Variable Scope—Functions as Black Boxes
Returning Values from Functions
Passing by Reference—Changing the Value of an Argument
Where to Locate Custom-Built Functions
Creating New Variables Dynamically
PHP Quick Checklist
Chapter 4: Lightening Your Workload with Includes
Including Code from External Files
Introducing the PHP Include Commands
Where PHP Looks for Include Files
PHP Solution 4-1: Moving the Menu and Footer to Include Files
Choosing the Right Filename Extension for Includes
PHP Solution 4-2: Testing the Security of Includes
PHP Solution 4-3: Automatically Indicating the Current Page
PHP Solution 4-4: Generating a Page’s Title From its Filename
Creating Pages with Changing Content
PHP Solution 4-5: Automatically Updating a Copyright Notice
PHP Solution 4-6: Displaying a Random Image
PHP Solution 4-7: Adding a Caption to the Random Image
Preventing Errors with Include Files
Checking the Existence of Variables
Checking Whether a Function or Class has Been Defined
Suppressing Error Messages on a Live Website
Using the Error Control Operator
Turning Off display_errors in the PHP Configuration
Turning Off display_errors in an Individual File
PHP Solution 4-8: Redirecting when an Include File Can’t be Found
Choosing where to Locate your Include Files
Adjusting your include_path
Editing the include_path in php.ini or .user.ini
Using .htaccess to Change the include_path
Using set_include_path( )
Why can’t I Use Site-root-relative Links with PHP Includes?
Document-relative Links
Links Relative to the Site Root
Links Inside Include Files
Nesting Include Files
Security Considerations with Includes
Chapter Review
Chapter 5: Bringing Forms to Life
How PHP Gathers Information from a Form
Understanding the Difference Between Post and get
Getting form Data with PHP Superglobals
Processing and Validating User Input
Creating a Reusable Script
PHP Solution 5-1: Making Sure Required Fields aren’t Blank
Preserving User Input when a Form is Incomplete
PHP Solution 5-2: Creating Sticky form fields
Filtering Out Potential Attacks
PHP Solution 5-3: Blocking Emails that Contain Specific Phrases
Sending Email
Using Additional Email Headers Safely
PHP Solution 5-4: Adding Headers and Automating the Reply Address
PHP Solution 5-5: Building the message Body and Sending the Mail
Troubleshooting mail()
Handling Multiple-Choice Form Elements
PHP Solution 5-6: Handling Radio-Button Groups
PHP Solution 5-7: Handling Check-Box Groups
PHP Solution 5-8: Using a Drop-down Option Menu
PHP Solution 5-9: Handling a Multiple-choice List
PHP Solution 5-10: Handling a Single Check Box
Chapter Review
Chapter 6: Uploading Files
How PHP Handles File Uploads
Checking whether your server supports uploads
Adding a file upload field to a form
Understanding the $_FILES array
Inspecting the $_FILES array
Establishing an upload directory
Creating an upload folder for local testing on Windows
Creating an upload folder for local testing on Mac OS X
Uploading Files
Moving the temporary file to the upload folder
PHP Solution 6-1: Creating a basic file upload script
Creating a PHP File Upload Class
Defining a PHP class
Using a namespace to avoid naming conflicts
Importing a namespaced class
PHP Solution 6-2: Creating the basic file upload class
Checking upload errors
PHP Solution 6-3: Testing the error level, file size, and MIME type
Changing protected properties
PHP Solution 6-4: Allowing different types and sizes to be uploaded
Explicitly changing a data type
Neutralizing potentially dangerous files
PHP Solution 6-5: Checking and amending filenames
Preventing files from being overwritten
PHP Solution 6-6: Renaming duplicate files
Uploading Multiple Files
How the $_FILES array handles multiple files
PHP Solution 6-7: Adapting the class to handle multiple uploads
Using the Upload Class
Points to Watch with File Uploads
Chapter Review
Chapter 7: Using PHP to Manage Files
Checking that PHP Can Open a File
Configuration Settings that Affect File Access
Creating a File Storage Folder for Local Testing
Reading and Writing Files
Reading Files in a Single Operation
PHP Solution 7-1: Getting the Contents of a Text File
Opening and Closing Files for Read/Write Operations
Reading a File with fopen( )
PHP Solution 7-2: Extracting data from a CSV file
Replacing Content with fopen( )
Appending Content with fopen( )
Locking a File Before Writing
Preventing Overwriting an Existing File
Combined Read/Write Operations with fopen( )
Moving the Internal Pointer
Exploring the File System
Inspecting a Folder with Scandir( )
Inspecting the Contents of a Folder with FilesystemIterator
Restricting File Types with the RegexIterator
PHP Solution 7-3: Building a Drop-Down Menu of Files
PHP Solution 7-4: Creating a Generic File Selector
Accessing Remote Files
Consuming News and Other RSS Feeds
Using SimpleXML
PHP Solution 7-5: Consuming an RSS news feed
Creating a Download Link
PHP Solution 7-6: Prompting a User to Download an Image
Chapter Review
Chapter 8: Generating Thumbnail Images
Checking Your Server’s Capabilities
Manipulating Images Dynamically
Making a Smaller Copy of an Image
Getting Ready
Building the Thumbnail Class
PHP Solution 8-1: Getting the Image Details
PHP Solution 8-2: Creating the Setter Methods
PHP Solution 8-3: Calculating the thumbnail’s dimensions
Using GD Functions to Create a Scaled Copy of an Image
PHP Solution 8-4: Generating the thumbnail image
Resizing an Image Automatically on Upload
Extending a Class
PHP Solution 8-5: Creating the ThumbnailUpload Class
Using the ThumbnailUpload Class
Chapter Review
Chapter 9: Pages That Remember: Simple Login and Multipage Forms
What Sessions Are and How They Work
Creating PHP Sessions
Creating and Destroying Session Variables
Destroying a Session
Regenerating the Session ID
The “Headers Already Sent” Error
Using Sessions to Restrict Access
PHP Solution 9-1: A Simple Session Example
PHP Solution 9-2: Buffering the Output with ob_start( )
Using File-based Authentication
PHP Solution 9-3: Building the Login Page
PHP Solution 9-4: Restricting Access to a Page with a Session
PHP Solution 9-5: Creating a Reusable Logout Button
Making Passwords More Secure
PHP Solution 9-6: Creating a Password-strength Checker
PHP Solution 9-7: Creating a File-based User Registration System
Checking Encrypted Passwords with password_verify()
PHP Solution 9-8: Using an Encrypted Login
Keeping Encryption Up to Date
Setting a Time Limit on Sessions
PHP Solution 9-9: Ending a Session after a Period of Inactivity
Passing Information Through Multipage Forms
PHP Solution 9-10: Using Sessions for a Multipage Form
Chapter Review
Chapter 10: Getting Started with a Database
Which Database Should You Choose?
Compatibility of MariaDB and MySQL
How a Database Stores Information
How primary keys work
Linking tables with primary and foreign keys
Breaking down information into small chunks
Checkpoints for good database design
Using a Graphical Interface
Launching phpMyAdmin
Setting Up the phpsols Database
MySQL naming rules
Case sensitivity of names
Using phpMyAdmin to create a new database
Creating database-specific user accounts
Granting user privileges
Creating a database table
Defining the images table
Inserting records into a table
Using phpMyAdmin to insert records manually
Loading the images records from an SQL file
Creating an SQL file for backup and data transfer
Choosing the Right Data Type in MySQL
Storing text
Storing numbers
Storing dates and times
Storing predefined lists
Storing binary data
Chapter Review
Chapter 11: Connecting to a Database with PHP and SQL
Checking Your Remote Server Setup
How PHP Communicates with a Database
Connecting with the MySQL Improved extension
Connecting with PDO
PHP Solution 11-1: Making a reusable database connector
Troubleshooting database connection problems
Querying the database and displaying the results
PHP Solution 11-2: Counting records in a result set (MySQLi)
PHP Solution 11-3: Displaying the images table using MySQLi
MySQLi connection crib sheet
PHP Solution 11-4: Counting records in a result set (PDO)
Counting records with PDO in other databases
PHP Solution 11-5: Displaying the images table using PDO
PDO connection crib sheet
Using SQL to Interact with a Database
Writing SQL queries
SQL is case-insensitive
Whitespace is ignored
Strings must be quoted
Handling numbers
Refining the data retrieved by a SELECT query
Selecting specific columns
Changing the order of results
Searching for specific values
Searching for text with wildcard characters
Understanding the Danger of SQL Injection
PHP Solution 11-6: Inserting an integer from user input into a query
PHP Solution 11-7: Inserting a string in MySQLi with real_escape_string()
Using Prepared Statements for User Input
Embedding variables in MySQLi prepared statements
Initialize the statement
Prepare the statement
Bind values to the placeholders
Execute the statement
Binding the results (optional)
Store the result (optional)
Fetch the result
Close the statement
PHP Solution 11-8: Using a MySQLi prepared statement in a search
Embedding variables in PDO prepared statements
Using anonymous placeholders
Using named placeholders
Preparing the statement
Binding values to the placeholders
Executing the statement
Binding the results (optional)
Fetching the result
PHP Solution 11-9: Using a PDO prepared statement in a search
PHP Solution 11-10: Changing column options through user input
Chapter Review
Chapter 12: Creating a Dynamic Photo Gallery
Why Not Store Images in a Database?
Planning the Gallery
Converting the Gallery Elements to PHP
PHP Solution 12-1: Displaying the First Image
Building the Dynamic Elements
Passing Information Through a Query String
PHP Solution 12-2: Activating the Thumbnails
Creating a Multicolumn table
PHP Solution 12-3: Looping Horizontally and Vertically
Paging Through a Long set of Records
Selecting a Subset of Records
PHP Solution 12-4: Displaying a Subset of Records
Navigating Through Subsets of Records
PHP Solution 12-5: Creating the Navigation Links
Chapter Review
Chapter 13: Managing Content
Setting Up a Content Management System
Creating the Blog Database Table
Creating the Basic Insert and Update Form
Inserting New Records
PHP Solution 13-1: Inserting a New Record with MySQLi
PHP Solution 13-2: Inserting a New Record with PDO
Linking to the Update and Delete Pages
PHP Solution 13-3: Creating the Links to the Update and Delete Pages
Updating Records
PHP Solution 13-4: Updating a Record with MySQLi
PHP Solution 13-5: Updating a Record with PDO
Deleting Records
Reviewing the Four Essential SQL Commands
SELECT
INSERT
UPDATE
DELETE
Security and Error Messages
Chapter Review
Chapter 14: Formatting Text and Dates
Displaying a Text Extract
Extracting a Fixed Number of Characters
Using the PHP substr( ) Function
Using the LEFT( ) Function in an SQL Query
Ending an Extract on a Complete Word
Extracting the First Paragraph
Displaying Paragraphs
Storing Database Records as HTML
Converting Newlines to
Tags
Creating a Function to Insert Tags
Extracting Complete Sentences
PHP Solution 14-1: Displaying the First Two Sentences of an Article
Let’s Make a Date
How MySQL Handles Dates
Formatting Dates in a SELECT Query with DATE_FORMAT( )
PHP Solution 14-2: Formatting a MySQL Date or Timestamp
Adding to and Subtracting from Dates
PHP Solution 14-3: Displaying Items Updated within the Past Week
Inserting Dates into MySQL
PHP Solution 14-4: Validating and Formatting Dates for MySQL Input
Working with Dates in PHP
Setting the Default Time Zone
Creating a DateTime Object
Formatting Dates in PHP
Creating a DateTime Object From a Custom Format
Choosing Between Date( ) and the DateTime Class
Handling Overflows with Relative Dates
Using the DateTimeZone Class
Adding and Subtracting Set Periods with the DateInterval Class
Finding the Difference Between Two Dates with the diff( ) Method
Calculating Recurring Dates with the DatePeriod Class
Chapter Review
Chapter 15: Pulling Data from Multiple Tables
Understanding Table Relationships
Linking an Image to an Article
Altering the Structure of an Existing Table
PHP Solution 15-1: Adding an Extra Column to a Table
Inserting a Foreign Key in a Table
PHP Solution 15-2: Adding the Image Foreign Key ( MySQLi)
PHP Solution 15-3: Adding the Image Foreign Key ( PDO)
Selecting Records from Multiple Tables
PHP Solution 15-4: Building the Details Page
Finding Records that don’t have a Matching Foreign Key
Creating an Intelligent Link
PHP Solution 15-5: Returning to the Same Point in a Navigation System
Chapter Review
Chapter 16: Managing Multiple Database Tables
Maintaining Referential Integrity
Support for foreign-key constraints
PHP Solution 16-1: Checking whether InnoDB is supported
Inserting records into multiple tables
Creating a cross-reference table
Setting up the categories and cross-reference tables
Getting the filename of an uploaded image
PHP Solution 16-2: Improving the Upload class
Adapting the insert form to deal with multiple tables
PHP Solution 16-3: Adding the category and image input fields
PHP Solution 16-4: Inserting data into multiple tables
Main differences in the PDO version
Updating and Deleting Records in Multiple Tables
Updating records in a cross-reference table
PHP Solution 16-5: Adding categories to the update form
Preserving referential integrity on deletion
PHP Solution 16-6: Converting tables to the InnoDB storage engine
PHP Solution 16-7: Setting up foreign-key constraints
Creating delete scripts with foreign-key constraints
Creating delete scripts without foreign-key constraints
Chapter Review
Chapter 17: Authenticating Users with a Database
Choosing an Encryption Method
Using One-Way Encryption
Creating a Table to Store Users’ Details
Registering New Usersin the Database
PHP Solution 17-1: Creating a User Registration Form
PHP Solution 17-2: Authenticating a user’s credentials with a database
Using Two-Way Encryption
Creating the table to store users’ details
Registering new users
User authentication with two-way encryption
Decrypting a password
Updating User Details
Where Next?
Index