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