You are previewing PHP and MySQL® Web Development, Fifth Edition.
O'Reilly logo
PHP and MySQL® Web Development, Fifth Edition

Book Description

PHP and MySQL Web Development, Fifth Edition

The definitive guide to building database-driven Web applications with PHP and MySQL

PHP and MySQL are popular open-source technologies that are ideal for quickly developing database-driven Web applications. PHP is a powerful scripting language designed to enable developers to create highly featured Web applications quickly, and MySQL is a fast, reliable database that integrates well with PHP and is suited for dynamic Internet-based applications.

PHP and MySQL Web Development shows how to use these tools together to produce effective, interactive Web applications. It clearly describes the basics of the PHP language, explains how to set up and work with a MySQL database, and then shows how to use PHP to interact with the database and the server.

This practical, hands-on book consistently focuses on real-world applications, even in the introductory chapters. The authors cover important aspects of security and authentication as they relate to building a real-world website and show you how to implement these aspects in PHP and MySQL. They also introduce you to the integration of front-end and back-end technologies by using JavaScript in your application development.

The final part of this book describes how to approach real-world projects and takes the reader through the design, planning, and building of several projects, including:

  • User authentication and personalization

  • Web-based email

  • Social media integration

  • The fifth edition of PHP and MySQL Web Development has been thoroughly updated, revised, and expanded to cover developments in PHP through versions 5.6 and 7, as well as features introduced in recent stable releases of MySQL.

    Contents at a Glance

    Part I: Using PHP

    1  PHP Crash Course

    2  Storing and Retrieving Data

    3  Using Arrays

    4  String Manipulation and Regular Expressions

    5  Reusing Code and Writing Functions

    6  Object-Oriented PHP

    7  Error and Exception Handling

    Part II: Using MySQL

    8  Designing Your Web Database

    9  Creating Your Web Database

    10 Working with Your MySQL Database

    11 Accessing Your MySQL Database from the Web with PHP

    12 Advanced MySQL Administration

    13 Advanced MySQL Programming

    Part III: Web Application Security

    14 Web Application Security Risks

    15 Building a Secure Web Application

    16 Implementing Authentication Methods with PHP

    Part IV: Advanced PHP Techniques

    17 Interacting with the File System and the Server

    18 Using Network and Protocol Functions

    19 Managing the Date and Time

    20 Internationalization and Localization

    21 Generating Images

    22 Using Session Control in PHP

    23 Integrating JavaScript and PHP

    24 Other Useful Features


    Part V: Building Practical PHP and MySQL Projects

    25 Using PHP and MySQL for Large Projects

    26 Debugging and Logging

    27 Building User Authentication and Personalization

    28 Building a Web-Based Email Service with Laravel Part I (Web Edition)

    29 Building a Web-Based Email Service with Laravel Part II (Web Edition)

    30 Social Media Integration Sharing and Authentication (Web Edition)

    31 Building a Shopping Cart (Web Edition)

    Part VI: Appendix

    A Installing Apache, PHP, and MySQL

    Table of Contents

    1. About This E-Book
    2. Title Page
    3. Copyright Page
    4. Contents at a Glance
    5. Table of Contents
    6. Lead Authors
    7. Contributing Authors
    8. We Want to Hear from You!
    9. Reader Services
    10. Accessing the Free Web Edition
    11. Introduction
      1. Why You Should Read This Book
      2. What You Will Learn from This Book
      3. What Is PHP?
      4. What Is MySQL?
      5. Why Use PHP and MySQL?
      6. Some of PHP’s Strengths
        1. Performance
        2. Scalability
        3. Database Integration
        4. Built-in Libraries
        5. Cost
        6. Ease of Learning PHP
        7. Object-Oriented Support
        8. Portability
        9. Flexibility of Development Approach
        10. Source Code
        11. Availability of Support and Documentation
      7. Key Features of PHP 7
      8. Some of MySQL’s Strengths
        1. Performance
        2. Low Cost
        3. Ease of Use
        4. Portability
        5. Source Code
        6. Availability of Support
      9. What Is New in MySQL (5.x)?
      10. How Is This Book Organized?
      11. Accessing the Free Web Edition
      12. Finally
    12. I: Using PHP
      1. 1. PHP Crash Course
        1. Before You Begin: Accessing PHP
        2. Creating a Sample Application: Bob’s Auto Parts
          1. Creating the Order Form
          2. Processing the Form
        3. Embedding PHP in HTML
          1. PHP Tags
          2. PHP Statements
          3. Whitespace
          4. Comments
        4. Adding Dynamic Content
          1. Calling Functions
          2. Using the date() Function
        5. Accessing Form Variables
          1. Form Variables
          2. String Concatenation
          3. Variables and Literals
        6. Understanding Identifiers
        7. Examining Variable Types
          1. PHP’s Data Types
          2. Type Strength
          3. Type Casting
          4. Variable Variables
        8. Declaring and Using Constants
        9. Understanding Variable Scope
        10. Using Operators
          1. Arithmetic Operators
          2. String Operators
          3. Assignment Operators
          4. Comparison Operators
          5. Logical Operators
          6. Bitwise Operators
          7. Other Operators
        11. Working Out the Form Totals
        12. Understanding Precedence and Associativity
        13. Using Variable Handling Functions
          1. Testing and Setting Variable Types
          2. Testing Variable Status
          3. Reinterpreting Variables
        14. Making Decisions with Conditionals
          1. if Statements
          2. Code Blocks
          3. else Statements
          4. elseif Statements
          5. switch Statements
          6. Comparing the Different Conditionals
        15. Repeating Actions Through Iteration
          1. while Loops
          2. for and foreach Loops
          3. do...while Loops
        16. Breaking Out of a Control Structure or Script
        17. Employing Alternative Control Structure Syntax
        18. Using declare
        19. Next
      2. 2. Storing and Retrieving Data
        1. Saving Data for Later
        2. Storing and Retrieving Bob’s Orders
        3. Processing Files
        4. Opening a File
          1. Choosing File Modes
          2. Using fopen() to Open a File
          3. Opening Files Through FTP or HTTP
          4. Addressing Problems Opening Files
        5. Writing to a File
          1. Parameters for fwrite()
          2. File Formats
        6. Closing a File
        7. Reading from a File
          1. Opening a File for Reading: fopen()
          2. Knowing When to Stop: feof()
          3. Reading a Line at a Time: fgets(), fgetss(), and fgetcsv()
          4. Reading the Whole File: readfile(), fpassthru(), file(), and file_get_contents()
          5. Reading a Character: fgetc()
          6. Reading an Arbitrary Length: fread()
        8. Using Other File Functions
          1. Checking Whether a File Is There: file_exists()
          2. Determining How Big a File Is: filesize()
          3. Deleting a File: unlink()
          4. Navigating Inside a File: rewind(), fseek(), and ftell()
        9. Locking Files
        10. A Better Way: Databases
          1. Problems with Using Flat Files
          2. How RDBMSs Solve These Problems
        11. Further Reading
        12. Next
      3. 3. Using Arrays
        1. What Is an Array?
        2. Numerically Indexed Arrays
          1. Initializing Numerically Indexed Arrays
          2. Accessing Array Contents
          3. Using Loops to Access the Array
        3. Arrays with Different Indices
          1. Initializing an Array
          2. Accessing the Array Elements
          3. Using Loops
        4. Array Operators
        5. Multidimensional Arrays
        6. Sorting Arrays
          1. Using sort()
          2. Using asort() and ksort() to Sort Arrays
          3. Sorting in Reverse
        7. Sorting Multidimensional Arrays
          1. Using the array_multisort() function
          2. User-Defined Sorts
          3. Reverse User Sorts
        8. Reordering Arrays
          1. Using shuffle()
          2. Reversing an Array
        9. Loading Arrays from Files
        10. Performing Other Array Manipulations
          1. Navigating Within an Array: each(), current(), reset(), end(), next(), pos(), and prev()
          2. Applying Any Function to Each Element in an Array: array_walk()
          3. Counting Elements in an Array: count(), sizeof(), and array_count_values()
          4. Converting Arrays to Scalar Variables: extract()
        11. Further Reading
        12. Next
      4. 4. String Manipulation and Regular Expressions
        1. Creating a Sample Application: Smart Form Mail
        2. Formatting Strings
          1. Trimming Strings: chop(), ltrim(), and trim()
          2. Formatting Strings for Output
        3. Joining and Splitting Strings with String Functions
          1. Using explode(), implode(), and join()
          2. Using strtok()
          3. Using substr()
        4. Comparing Strings
          1. Performing String Ordering: strcmp(), strcasecmp(), and strnatcmp()
          2. Testing String Length with strlen()
        5. Matching and Replacing Substrings with String Functions
          1. Finding Strings in Strings: strstr(), strchr(), strrchr(), and stristr()
          2. Finding the Position of a Substring: strpos() and strrpos()
          3. Replacing Substrings: str_replace() and substr_replace()
        6. Introducing Regular Expressions
          1. The Basics
          2. Delimiters
          3. Character Classes and Types
          4. Repetition
          5. Subexpressions
          6. Counted Subexpressions
          7. Anchoring to the Beginning or End of a String
          8. Branching
          9. Matching Literal Special Characters
          10. Reviewing Meta Characters
          11. Escape Sequences
          12. Backreferences
          13. Assertions
          14. Putting It All Together for the Smart Form
        7. Finding Substrings with Regular Expressions
        8. Replacing Substrings with Regular Expressions
        9. Splitting Strings with Regular Expressions
        10. Further Reading
        11. Next
      5. 5. Reusing Code and Writing Functions
        1. The Advantages of Reusing Code
          1. Cost
          2. Reliability
          3. Consistency
        2. Using require() and include()
          1. Using require() to Include Code
          2. Using require() for Website Templates
          3. Using auto_prepend_file and auto_append_file
        3. Using Functions in PHP
          1. Calling Functions
          2. Calling an Undefined Function
          3. Understanding Case and Function Names
        4. Defining Your Own Functions
        5. Examining Basic Function Structure
          1. Naming Your Function
        6. Using Parameters
        7. Understanding Scope
        8. Passing by Reference Versus Passing by Value
        9. Using the return Keyword
          1. Returning Values from Functions
        10. Implementing Recursion
          1. Implementing Anonymous Functions (or Closures)
        11. Further Reading
        12. Next
      6. 6. Object-Oriented PHP
        1. Understanding Object-Oriented Concepts
          1. Classes and Objects
          2. Polymorphism
          3. Inheritance
        2. Creating Classes, Attributes, and Operations in PHP
          1. Structure of a Class
          2. Constructors
          3. Destructors
        3. Instantiating Classes
        4. Using Class Attributes
        5. Calling Class Operations
        6. Controlling Access with private and public
        7. Writing Accessor Functions
        8. Implementing Inheritance in PHP
          1. Controlling Visibility Through Inheritance with private and protected
          2. Overriding
          3. Preventing Inheritance and Overriding with final
          4. Understanding Multiple Inheritance
          5. Implementing Interfaces
        9. Using Traits
        10. Designing Classes
        11. Writing the Code for Your Class
        12. Understanding Advanced Object-Oriented Functionality in PHP
          1. Using Per-Class Constants
          2. Implementing Static Methods
          3. Checking Class Type and Type Hinting
          4. Late Static Bindings
          5. Cloning Objects
          6. Using Abstract Classes
          7. Overloading Methods with __call()
          8. Using __autoload()
          9. Implementing Iterators and Iteration
          10. Generators
          11. Converting Your Classes to Strings
          12. Using the Reflection API
          13. Namespaces
          14. Using Subnamespaces
          15. Understanding the Global Namespace
          16. Importing and Aliasing Namespaces
        13. Next
      7. 7. Error and Exception Handling
        1. Exception Handling Concepts
        2. The Exception Class
        3. User-Defined Exceptions
        4. Exceptions in Bob’s Auto Parts
        5. Exceptions and PHP’s Other Error Handling Mechanisms
        6. Further Reading
        7. Next
    13. II: Using MySQL
      1. 8. Designing Your Web Database
        1. Relational Database Concepts
          1. Tables
          2. Columns
          3. Rows
          4. Values
          5. Keys
          6. Schemas
          7. Relationships
        2. Designing Your Web Database
          1. Think About the Real-World Objects You Are Modeling
          2. Avoid Storing Redundant Data
          3. Use Atomic Column Values
          4. Choose Sensible Keys
          5. Think About What You Want to Ask the Database
          6. Avoid Designs with Many Empty Attributes
          7. Summary of Table Types
        3. Web Database Architecture
        4. Further Reading
        5. Next
      2. 9. Creating Your Web Database
        1. Using the MySQL Monitor
        2. Logging In to MySQL
        3. Creating Databases and Users
        4. Setting Up Users and Privileges
        5. Introducing MySQL’s Privilege System
          1. Principle of Least Privilege
          2. User Setup: The CREATE USER and GRANT Commands
          3. Types and Levels of Privileges
          4. The REVOKE Command
          5. Examples Using GRANT and REVOKE
        6. Setting Up a User for the Web
        7. Using the Right Database
        8. Creating Database Tables
          1. Understanding What the Other Keywords Mean
          2. Understanding the Column Types
          3. Looking at the Database with SHOW and DESCRIBE
          4. Creating Indexes
        9. Understanding MySQL Identifiers
        10. Choosing Column Data Types
          1. Numeric Types
          2. Date and Time Types
          3. String Types
        11. Further Reading
        12. Next
      3. 10. Working with Your MySQL Database
        1. What Is SQL?
        2. Inserting Data into the Database
        3. Retrieving Data from the Database
          1. Retrieving Data with Specific Criteria
          2. Retrieving Data from Multiple Tables
          3. Retrieving Data in a Particular Order
          4. Grouping and Aggregating Data
          5. Choosing Which Rows to Return
          6. Using Subqueries
        4. Updating Records in the Database
        5. Altering Tables After Creation
        6. Deleting Records from the Database
        7. Dropping Tables
        8. Dropping a Whole Database
        9. Further Reading
        10. Next
      4. 11. Accessing Your MySQL Database from the Web with PHP
        1. How Web Database Architectures Work
        2. Querying a Database from the Web
          1. Checking and Filtering Input Data
          2. Setting Up a Connection
          3. Choosing a Database to Use
          4. Querying the Database
          5. Using Prepared Statements
          6. Retrieving the Query Results
          7. Disconnecting from the Database
        3. Putting New Information in the Database
        4. Using Other PHP-Database Interfaces
          1. Using a Generic Database Interface: PDO
        5. Further Reading
        6. Next
      5. 12. Advanced MySQL Administration
        1. Understanding the Privilege System in Detail
          1. The user Table
          2. The db Table
          3. The tables_priv, columns_priv, and procs priv Tables
          4. Access Control: How MySQL Uses the Grant Tables
          5. Updating Privileges: When Do Changes Take Effect?
        2. Making Your MySQL Database Secure
          1. MySQL from the Operating System’s Point of View
          2. Passwords
          3. User Privileges
          4. Web Issues
        3. Getting More Information About Databases
          1. Getting Information with SHOW
          2. Getting Information About Columns with DESCRIBE
          3. Understanding How Queries Work with EXPLAIN
        4. Optimizing Your Database
          1. Design Optimization
          2. Permissions
          3. Table Optimization
          4. Using Indexes
          5. Using Default Values
          6. Other Tips
        5. Backing Up Your MySQL Database
        6. Restoring Your MySQL Database
        7. Implementing Replication
          1. Setting Up the Master
          2. Performing the Initial Data Transfer
          3. Setting Up the Slave or Slaves
        8. Further Reading
        9. Next
      6. 13. Advanced MySQL Programming
        1. The LOAD DATA INFILE Statement
        2. Storage Engines
        3. Transactions
          1. Understanding Transaction Definitions
          2. Using Transactions with InnoDB
        4. Foreign Keys
        5. Stored Procedures
          1. Basic Example
          2. Local Variables
          3. Cursors and Control Structures
        6. Triggers
        7. Further Reading
        8. Next
    14. III: Web Application Security
      1. 14. Web Application Security Risks
        1. Identifying the Threats We Face
          1. Access to Sensitive Data
          2. Modification of Data
          3. Loss or Destruction of Data
          4. Denial of Service
          5. Malicious Code Injection
          6. Compromised Server
          7. Repudiation
        2. Understanding Who We’re Dealing With
          1. Attackers and Crackers
          2. Unwitting Users of Infected Machines
          3. Disgruntled Employees
          4. Hardware Thieves
          5. Ourselves
        3. Next
      2. 15. Building a Secure Web Application
        1. Strategies for Dealing with Security
          1. Start with the Right Mindset
          2. Balancing Security and Usability
          3. Monitoring Security
          4. Our Basic Approach
        2. Securing Your Code
          1. Filtering User Input
          2. Escaping Output
          3. Code Organization
          4. What Goes in Your Code
          5. File System Considerations
          6. Code Stability and Bugs
          7. Executing Commands
        3. Securing Your Web Server and PHP
          1. Keep Software Up-to-Date
          2. Browse the php.ini file
          3. Web Server Configuration
          4. Shared Hosting of Web Applications
        4. Database Server Security
          1. Users and the Permissions System
          2. Sending Data to the Server
          3. Connecting to the Server
          4. Running the Server
        5. Protecting the Network
          1. Firewalls
          2. Use a DMZ
          3. Prepare for DoS and DDoS Attacks
        6. Computer and Operating System Security
          1. Keep the Operating System Up to Date
          2. Run Only What Is Necessary
          3. Physically Secure the Server
        7. Disaster Planning
        8. Next
      3. 16. Implementing Authentication Methods with PHP
        1. Identifying Visitors
        2. Implementing Access Control
          1. Storing Passwords
          2. Securing Passwords
          3. Protecting Multiple Pages
        3. Using Basic Authentication
        4. Using Basic Authentication in PHP
        5. Using Basic Authentication with Apache’s .htaccess Files
        6. Creating Your Own Custom Authentication
        7. Further Reading
        8. Next
    15. IV: Advanced PHP Techniques
      1. 17. Interacting with the File System and the Server
        1. Uploading Files
          1. HTML for File Upload
          2. Writing the PHP to Deal with the File
          3. Session Upload Progress
          4. Avoiding Common Upload Problems
        2. Using Directory Functions
          1. Reading from Directories
          2. Getting Information About the Current Directory
          3. Creating and Deleting Directories
        3. Interacting with the File System
          1. Getting File Information
          2. Changing File Properties
          3. Creating, Deleting, and Moving Files
        4. Using Program Execution Functions
        5. Interacting with the Environment: getenv() and putenv()
        6. Further Reading
        7. Next
      2. 18. Using Network and Protocol Functions
        1. Examining Available Protocols
        2. Sending and Reading Email
        3. Using Data from Other Websites
        4. Using Network Lookup Functions
        5. Backing Up or Mirroring a File
          1. Using FTP to Back Up or Mirror a File
          2. Uploading Files
          3. Avoiding Timeouts
          4. Using Other FTP Functions
        6. Further Reading
        7. Next
      3. 19. Managing the Date and Time
        1. Getting the Date and Time from PHP
          1. Understanding Timezones
          2. Using the date() Function
          3. Dealing with Unix Timestamps
          4. Using the getdate() Function
          5. Validating Dates with checkdate()
          6. Formatting Timestamps
        2. Converting Between PHP and MySQL Date Formats
        3. Calculating Dates in PHP
        4. Calculating Dates in MySQL
        5. Using Microseconds
        6. Using the Calendar Functions
        7. Further Reading
        8. Next
      4. 20. Internationalization and Localization
        1. Localization Is More than Translation
        2. Understanding Character Sets
          1. Security Implications of Character Sets
          2. Using Multibyte String Functions in PHP
        3. Creating a Basic Localizable Page Structure
        4. Using gettext() in an Internationalized Application
          1. Configuring Your System to Use gettext()
          2. Creating Translation Files
          3. Implementing Localized Content in PHP Using gettext()
        5. Further Reading
        6. Next
      5. 21. Generating Images
        1. Setting Up Image Support in PHP
        2. Understanding Image Formats
          1. JPEG
          2. PNG
          3. GIF
        3. Creating Images
          1. Creating a Canvas Image
          2. Drawing or Printing Text on the Image
          3. Outputting the Final Graphic
          4. Cleaning Up
        4. Using Automatically Generated Images in Other Pages
        5. Using Text and Fonts to Create Images
          1. Setting Up the Base Canvas
          2. Fitting the Text onto the Button
          3. Positioning the Text
          4. Writing the Text onto the Button
          5. Finishing Up
        6. Drawing Figures and Graphing Data
        7. Using Other Image Functions
        8. Next
      6. 22. Using Session Control in PHP
        1. What Is Session Control?
        2. Understanding Basic Session Functionality
          1. What Is a Cookie?
          2. Setting Cookies from PHP
          3. Using Cookies with Sessions
          4. Storing the Session ID
        3. Implementing Simple Sessions
          1. Starting a Session
          2. Registering Session Variables
          3. Using Session Variables
          4. Unsetting Variables and Destroying the Session
        4. Creating a Simple Session Example
        5. Configuring Session Control
        6. Implementing Authentication with Session Control
        7. Next
      7. 23. Integrating JavaScript and PHP
        1. Understanding AJAX
        2. A Brief Introduction to jQuery
        3. Using jQuery in Web Applications
          1. Basic jQuery Techniques and Concepts
          2. Using jQuery Selectors
          3. Introduction to jQuery Events
        4. Using jQuery and AJAX with PHP
          1. The AJAX-Enabled Chat Script/Server
          2. The jQuery AJAX Methods
          3. The Chat Client/jQuery Application
        5. Further Reading
        6. Next
      8. 24. Other Useful Features
        1. Evaluating Strings: eval()
        2. Terminating Execution: die() and exit()
        3. Serializing Variables and Objects
        4. Getting Information About the PHP Environment
          1. Finding Out What Extensions Are Loaded
          2. Identifying the Script Owner
          3. Finding Out When the Script Was Modified
        5. Temporarily Altering the Runtime Environment
        6. Highlighting Source Code
        7. Using PHP on the Command Line
        8. Next
    16. V: Building Practical PHP and MySQL Projects
      1. 25. Using PHP and MySQL for Large Projects
        1. Applying Software Engineering to Web Development
        2. Planning and Running a Web Application Project
        3. Reusing Code
        4. Writing Maintainable Code
          1. Coding Standards
          2. Breaking Up Code
          3. Using a Standard Directory Structure
          4. Documenting and Sharing In-House Functions
        5. Implementing Version Control
        6. Choosing a Development Environment
        7. Documenting Your Projects
        8. Prototyping
        9. Separating Logic and Content
        10. Optimizing Code
          1. Using Simple Optimizations
        11. Testing
        12. Further Reading
        13. Next
      2. 26. Debugging and Logging
        1. Programming Errors
          1. Syntax Errors
          2. Runtime Errors
          3. Logic Errors
        2. Variable Debugging Aid
        3. Error Reporting Levels
        4. Altering the Error Reporting Settings
        5. Triggering Your Own Errors
        6. Logging Errors Gracefully
        7. Logging Errors to a Log File
        8. Next
      3. 27. Building User Authentication and Personalization
        1. Solution Components
          1. User Identification and Personalization
          2. Storing Bookmarks
          3. Recommending Bookmarks
        2. Solution Overview
        3. Implementing the Database
        4. Implementing the Basic Site
        5. Implementing User Authentication
          1. Registering Users
          2. Logging In
          3. Logging Out
          4. Changing Passwords
          5. Resetting Forgotten Passwords
        6. Implementing Bookmark Storage and Retrieval
          1. Adding Bookmarks
          2. Displaying Bookmarks
          3. Deleting Bookmarks
        7. Implementing Recommendations
        8. Considering Possible Extensions
    17. VI: Appendix
      1. A. Installing Apache, PHP, and MySQL
        1. Installing Apache, PHP, and MySQL Under UNIX
          1. Binary Installation
          2. Source Installation
          3. Basic Apache Configuration Modifications
          4. Is PHP Support Working?
          5. Is SSL Working?
        2. Installing Apache, PHP, and MySQL for Windows and Mac OS X Using All-in-One Installation Packages
          1. Testing Your Work
        3. Installing PEAR
        4. Installing PHP with Other Web Servers
    18. Index