<span><p>Make your websites more dynamic by adding a feedback form, creating a private area where members can upload images that are automatically resized, or storing all your content in a database. <b>David Powers</b> has updated his definitive book to incorporate the latest techniques and changes
PHP 8 Solutions: Dynamic Web Design and Development Made Easy
✍ Scribed by David Powers
- Publisher
- Apress
- Year
- 2021
- Tongue
- English
- Leaves
- 571
- Edition
- 5
- Category
- Library
No coin nor oath required. For personal study only.
✦ Synopsis
Make your websites more dynamic by adding a feedback form, creating a private area where members can upload images that are automatically resized, or storing all your content in a database. David Powers has updated his definitive book to incorporate the latest techniques and changes to PHP with the arrival of PHP 8. New features include named attributes, constructor property promotion, the stricter and more concise match expression, union types, and more. 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 powers four out of every five websites that use a server-side language. In combination with the MySQL database it’s ideal for creating dynamic websites. PHP and MySQL are 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. You’ll learn how to optimize your code using object-oriented programming (OOP) techniques. 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 Who This Book Is For Readers should ideally have some prior exposure to web development using PHP.
✦ Table of Contents
Table of Contents
About the Author
About the Technical Reviewer
Acknowledgments
Introduction
Chapter 1: What Is PHP 8?
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’s New in PHP 8?
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 Web Site Supports PHP
Deciding Where to Test Your Pages
What You Need for a Local Test Environment
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 macOS
Installing MAMP
Testing and Configuring MAMP
Where to Locate Your PHP Files (Windows and Mac)
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 Web Page
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
Multiline 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
Displaying PHP Output
Using the Short Echo Tag
Joining Strings Together
Working with Numbers
Understanding PHP Error Messages
Why Is My Page Blank?
PHP Quick Checklist
Chapter 4: PHP: A Quick Reference
Using PHP in an Existing Web Site
Data Types in PHP
Checking the Data Type of a Variable
Explicitly Changing a Variable’s Data Type
Checking Whether a Variable Has Been Defined
Doing Calculations with PHP
Arithmetic Operators
Using the Increment and Decrement 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 a match Expression for Decision Chains
Using the Ternary Operator
Setting a Default Value with the Null Coalescing Operator
Executing Code Repeatedly with a Loop
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 Functions
Setting Default Values for Arguments
Variable Scope: Functions as Black Boxes
Returning Values from Functions
Generators: A Special Type of Function That Keeps on Giving
Passing by Reference: Changing the Value of an Argument
Functions That Accept a Variable Number of Arguments
Automatically Unpacking an Array Passed to a Function
Optionally Specifying Data Types
Specifying Multiple Data Types
Using Named Arguments
Where to Locate Custom-Built Functions
Creating Anonymous Functions
Using the Concise Anonymous Syntax of Arrow Functions
Understanding PHP Classes and Objects
Using PHP Built-In Classes
Building Custom Classes
Accessing Methods and Properties in a Class
Setting the Visibility of Class Methods, Properties, and Constants
Using Constructor Property Promotion
Declaring and Using Class Constants
Using a Namespace to Avoid Naming Conflicts
Importing a Namespaced Class
Handling Errors and Exceptions
Creating New Variables Dynamically
Now to the Solutions
Chapter 5: Lightening Your Workload with Includes
Including Code from External Files
Introducing the PHP Include Commands
Where PHP Looks for Include Files
PHP Solution 5-1: Moving the Menu and Footer to Include Files
Choosing the Right Filename Extension for Includes
PHP Solution 5-2: Testing the Security of Includes
PHP Solution 5-3: Automatically Indicating the Current Page
PHP Solution 5-4: Automating a Page’s Title from Its Filename
PHP Solution 5-5: Handling Missing Variables
Creating Pages with Changing Content
PHP Solution 5-6: Automatically Updating a Copyright Notice
PHP Solution 5-7: Displaying a Random Image
PHP Solution 5-8: 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 Web Site
Using the Error Control Operator
Turning Off display_errors in the PHP Configuration
Turning Off display_errors in an Individual File
PHP Solution 5-9: Redirecting When an Include File Can’t Be Found
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
Choosing Where to Locate Your Include Files
Security Considerations with Includes
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()
Nesting Include Files
Chapter Review
Chapter 6: 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 6-1: Preventing Cross-Site Scripting in a Self-Processing Form
PHP Solution 6-2: Making Sure Required Fields Aren’t Blank
Preserving User Input When a Form Is Incomplete
PHP Solution 6-3: Creating Sticky Form Fields
Filtering Out Potential Attacks
PHP Solution 6-4: Blocking Email Addresses That Contain Suspect Content
Sending Email
Using Additional Email Headers Safely
PHP Solution 6-5: Adding Headers and Automating the Reply Address
PHP Solution 6-6: Building the Message Body and Sending the Mail
Troubleshooting mail()
Handling Multiple-Choice Form Elements
PHP Solution 6-7: Handling Radio Button Groups
PHP Solution 6-8: Handling Check-Box Groups
PHP Solution 6-9: Using a Drop-Down Option Menu
PHP Solution 6-10: Handling a Multiple-Choice List
PHP Solution 6-11: Handling a Single Check Box
Chapter Review
Chapter 7: Using PHP to Manage Files
Checking That PHP Can Open a File
Creating a Folder Outside the Server Root for Local Testing on Windows
Creating a Folder Outside the Server Root for Local Testing on macOS
Configuration Settings That Affect File Access
Reading and Writing to 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: Working with Arrays
Modifying Array Elements
PHP Solution 8-1: Modify Array Elements with a Loop
PHP Solution 8-2: Modify Array Elements with array_walk()
PHP Solution 8-3: Modify Array Elements with array_map()
Merging Arrays
Using the Array Union Operator
Using array_merge() and array_merge_recursive()
Merging Two Indexed Arrays into an Associative Array
Comparing Arrays
Removing Duplicate Elements
PHP Solution 8-4: Joining an Array with Commas
Sorting Arrays
PHP Solution 8-5: Custom Sorting with the Spaceship Operator
Complex Sorting with array_multisort()
PHP Solution 8-6: Sorting a Multidimensional Array with array_multisort()
PHP Solution 8-7: Finding All Permutations of an Array
Processing Array Data
PHP Solution 8-8: Building Nested Lists Automatically
PHP Solution 8-9: Extracting Data from JSON
Automatically Assigning Array Elements to Variables
Using the extract() Function
Using list()
Using Array Shorthand Syntax for list()
PHP Solution 8-10: Using a Generator to Process a CSV File
Unpacking Arguments from an Array with the Splat Operator
PHP Solution 8-11: Processing a CSV File with the Splat Operator
Chapter Review
Chapter 9: 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 macOS
Uploading Files
Moving the Temporary File to the Upload Folder
PHP Solution 9-1: Creating a Basic File Upload Script
Creating a PHP File Upload Class
PHP Solution 9-2: Creating the Basic File Upload Class
Checking Upload Errors
PHP Solution 9-3: Testing the Error Level, File Size, and MIME Type
Changing Protected Properties
PHP Solution 9-4: Allowing Different Types and Sizes to Be Uploaded
PHP Solution 9-5: Renaming Files
Uploading Multiple Files
How the $_FILES Array Handles Multiple Files
PHP Solution 9-6: Adapting the Class to Handle Multiple Uploads
Using the Upload Class
Points to Watch with File Uploads
Chapter Review
Chapter 10: 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 10-1: Getting the Image Details
PHP Solution 10-2: Calculating the Thumbnail’s Dimensions
Using gd Functions to Create a Scaled Copy of an Image
PHP Solution 10-3: Generating the Thumbnail Image
Resizing an Image Automatically on Upload
Extending a Class
PHP Solution 10-4: Creating the ThumbnailUpload Class
Using the ThumbnailUpload Class
Chapter Review
Chapter 11: 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 11-1: A Simple Session Example
PHP Solution 11-2: Buffering the Output with ob_start()
Using File-Based Authentication
Making Passwords Secure
PHP Solution 11-3: Creating a Password Strength Checker
PHP Solution 11-4: Creating a File-Based User Registration System
Checking Hashed Passwords with password_verify()
PHP Solution 11-5: Building the Login Page
PHP Solution 11-6: Restricting Access to a Page with a Session
PHP Solution 11-7: Creating a Reusable Logout Button
Keeping the Hashing Algorithm Up to Date
Setting a Time Limit on Sessions
PHP Solution 11-8: Ending a Session After a Period of Inactivity
Passing Information Through Multipage Forms
PHP Solution 11-9: Using Sessions for a Multipage Form
Chapter Review
Chapter 12: Getting Started with a Database
MySQL or MariaDB?
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 13: 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 13-1: Making a Reusable Database Connector
Troubleshooting Database Connection Problems
Sanitizing Text Results from a Database
Querying the Database and Displaying the Results
PHP Solution 13-2: Counting Records in a Result Set (MySQLi)
PHP Solution 13-3: Displaying the Images Table Using MySQLi
MySQLi Connection Crib Sheet
PHP Solution 13-4: Counting Records in a Result Set (PDO)
Counting Records with PDO in Other Databases
PHP Solution 13-5: Displaying the Images Table Using PDO
PDO Connection Crib Sheet
Using SQL to Interact with a Database
Writing SQL Queries
SQL Keywords Are 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 13-6: Inserting an Integer from User Input into a Query
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 13-7: 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 13-8: Using a PDO Prepared Statement in a Search
PHP Solution 13-9: Debugging a PDO Prepared Statement
PHP Solution 13-10: Changing Column Options Through User Input
Chapter Review
Chapter 14: Creating a Dynamic Photo Gallery
Why Not Store Images in a Database?
Planning the Gallery
Converting the Gallery Elements to PHP
PHP Solution 14-1: Displaying the First Image
Building the Dynamic Elements
Passing Information Through a Query String
PHP Solution 14-2: Activating the Thumbnails
Creating a Multicolumn Table
PHP Solution 14-3: Looping Horizontally and Vertically
Paging Through a Long Set of Records
Selecting a Subset of Records
PHP Solution 14-4: Displaying a Subset of Records
Navigating Through Subsets of Records
PHP Solution 14-5: Creating the Navigation Links
Chapter Review
Chapter 15: Managing Content
Setting Up a Content Management System
Creating the Blog Database Table
Creating the Basic Insert and Update Forms
Inserting New Records
PHP Solution 15-1: Inserting a New Record with MySQLi
PHP Solution 15-2: Inserting a New Record with PDO
Linking to the Update and Delete Pages
PHP Solution 15-3: Creating the Links to the Update and Delete Pages
Updating Records
PHP Solution 15-4: Updating a Record with MySQLi
PHP Solution 15-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 16: 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 New Lines to
Tags
Creating a Function to Insert
Tags
Extracting Complete Sentences
PHP Solution 16-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 16-2: Formatting a MySQL Date or Timestamp
Adding to and Subtracting from Dates
PHP Solution 16-3: Displaying Items Updated Within the Past Week
Inserting Dates into MySQL
PHP Solution 16-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 17: Pulling Data from Multiple Tables
Understanding Table Relationships
Linking an Image to an Article
Altering the Structure of an Existing Table
PHP Solution 17-1: Adding an Extra Column to a Table
Inserting a Foreign Key in a Table
PHP Solution 17-2: Adding the Image Foreign Key (MySQLi)
PHP Solution 17-3: Adding the Image Foreign Key (PDO)
Selecting Records from Multiple Tables
PHP Solution 17-4: Building the Details Page
Finding Records That Don’t Have a Matching Foreign Key
Creating an Intelligent Link
PHP Solution 17-5: Returning to the Same Point in a Navigation System
Chapter Review
Chapter 18: Managing Multiple Database Tables
Maintaining Referential Integrity
Support for Transactions and Foreign-key Constraints
PHP Solution 18-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 18-2: Improving the Upload Class
Adapting the Insert Form to Deal with Multiple Tables
PHP Solution 18-3: Adding the Category and Image Input Fields
PHP Solution 18-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 18-5: Adding Categories to the Update Form
Treating Multiple Queries as a Block in a Transaction
Using a Transaction in MySQLi
Using a Transaction in PDO
PHP Solution 18-6: Converting Tables to the InnoDB Storage Engine
PHP Solution 18-7: Wrapping the Update Sequence in a Transaction (MySQLi)
PHP Solution 18-8: Wrapping the Update Sequence in a Transaction (PDO)
Preserving Referential Integrity on Deletion
PHP Solution 18-9: Setting Up Foreign-Key Constraints
Creating Delete Scripts with Foreign-Key Constraints
Creating Delete Scripts Without Foreign-Key Constraints
Chapter Review
Chapter 19: Authenticating Users with a Database
Choosing a Password Storage Method
Using Password Hashing
Creating a Table to Store Users’ Details
Registering New Users in the Database
PHP Solution 19-1: Creating a User Registration Form
PHP Solution 19-2: Authenticating a User’s Credentials with a Database
Using Secret-Key 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
📜 SIMILAR VOLUMES
"In this book you'll learn how to: * Create dynamic websites with design and usability in mind, as well as functionality * Understand how PHP scripts work, giving you confidence to adapt them to your own needs * Bring online forms to life, check required fields, and ensure user input is safe to proc
I have read two books from different publishers and authors on this subject. The other is called Build Your own Database Driven Web Site Using PHP & MySQL from Sitepoint, i recommend that book. I believe sitepoint is one of the better publishers for beginners and their newer books are very well writ
This is the second edition of David Power's highly-respected PHP Solutions: Dynamic Web Design Made Easy . This new edition has been updated by David to incorporate changes to PHP since the first edition and to offer the latest techniques--a classic guide modernized for 21st century PHP techniques,
This is the second edition of David Power's highly-respected PHP Solutions: Dynamic Web Design Made Easy. This new edition has been updated by David to incorporate changes to PHP since the first edition and to offer the latest techniques--a classic guide modernized for 21st century PHP techniques, i