You are previewing Programming PHP, 3rd Edition.

Programming PHP, 3rd Edition

Cover of Programming PHP, 3rd Edition by Kevin Tatroe... Published by O'Reilly Media, Inc.
  1. Dedication
  2. Special Upgrade Offer
  3. Foreword
  4. Preface
    1. Audience
    2. Assumptions This Book Makes
    3. Contents of This Book
    4. Conventions Used in This Book
    5. Using Code Examples
    6. Safari® Books Online
    7. How to Contact Us
    8. Acknowledgments
      1. Kevin Tatroe
      2. Peter MacIntyre
  5. 1. Introduction to PHP
    1. What Does PHP Do?
    2. A Brief History of PHP
      1. The Evolution of PHP
      2. The Widespread Use of PHP
    3. Installing PHP
    4. A Walk Through PHP
      1. Configuration Page
      2. Forms
      3. Databases
      4. Graphics
  6. 2. Language Basics
    1. Lexical Structure
      1. Case Sensitivity
      2. Statements and Semicolons
      3. Whitespace and Line Breaks
      4. Comments
      5. Literals
      6. Identifiers
      7. Keywords
    2. Data Types
      1. Integers
      2. Floating-Point Numbers
      3. Strings
      4. Booleans
      5. Arrays
      6. Objects
      7. Resources
      8. Callbacks
      9. NULL
    3. Variables
      1. Variable Variables
      2. Variable References
      3. Variable Scope
      4. Garbage Collection
    4. Expressions and Operators
      1. Number of Operands
      2. Operator Precedence
      3. Operator Associativity
      4. Implicit Casting
      5. Arithmetic Operators
      6. String Concatenation Operator
      7. Auto-increment and Auto-decrement Operators
      8. Comparison Operators
      9. Bitwise Operators
      10. Logical Operators
      11. Casting Operators
      12. Assignment Operators
      13. Miscellaneous Operators
    5. Flow-Control Statements
      1. if
      2. switch
      3. while
      4. for
      5. foreach
      6. try...catch
      7. declare
      8. exit and return
      9. goto
    6. Including Code
    7. Embedding PHP in Web Pages
      1. Standard (XML) Style
      2. SGML Style
      3. ASP Style
      4. Script Style
      5. Echoing Content Directly
  7. 3. Functions
    1. Calling a Function
    2. Defining a Function
    3. Variable Scope
      1. Global Variables
      2. Static Variables
    4. Function Parameters
      1. Passing Parameters by Value
      2. Passing Parameters by Reference
      3. Default Parameters
      4. Variable Parameters
      5. Missing Parameters
      6. Type Hinting
    5. Return Values
    6. Variable Functions
    7. Anonymous Functions
  8. 4. Strings
    1. Quoting String Constants
      1. Variable Interpolation
      2. Single-Quoted Strings
      3. Double-Quoted Strings
      4. Here Documents
    2. Printing Strings
      1. echo
      2. print()
      3. printf()
      4. print_r() and var_dump()
    3. Accessing Individual Characters
    4. Cleaning Strings
      1. Removing Whitespace
      2. Changing Case
    5. Encoding and Escaping
      1. HTML
      2. URLs
      3. SQL
      4. C-String Encoding
    6. Comparing Strings
      1. Exact Comparisons
      2. Approximate Equality
    7. Manipulating and Searching Strings
      1. Substrings
      2. Miscellaneous String Functions
      3. Decomposing a String
      4. String-Searching Functions
    8. Regular Expressions
      1. The Basics
      2. Character Classes
      3. Alternatives
      4. Repeating Sequences
      5. Subpatterns
      6. Delimiters
      7. Match Behavior
      8. Character Classes
      9. Anchors
      10. Quantifiers and Greed
      11. Noncapturing Groups
      12. Backreferences
      13. Trailing Options
      14. Inline Options
      15. Lookahead and Lookbehind
      16. Cut
      17. Conditional Expressions
      18. Functions
      19. Differences from Perl Regular Expressions
  9. 5. Arrays
    1. Indexed Versus Associative Arrays
    2. Identifying Elements of an Array
    3. Storing Data in Arrays
      1. Adding Values to the End of an Array
      2. Assigning a Range of Values
      3. Getting the Size of an Array
      4. Padding an Array
    4. Multidimensional Arrays
    5. Extracting Multiple Values
      1. Slicing an Array
      2. Splitting an Array into Chunks
      3. Keys and Values
      4. Checking Whether an Element Exists
      5. Removing and Inserting Elements in an Array
    6. Converting Between Arrays and Variables
      1. Creating Variables from an Array
      2. Creating an Array from Variables
    7. Traversing Arrays
      1. The foreach Construct
      2. The Iterator Functions
      3. Using a for Loop
      4. Calling a Function for Each Array Element
      5. Reducing an Array
      6. Searching for Values
    8. Sorting
      1. Sorting One Array at a Time
      2. Natural-Order Sorting
      3. Sorting Multiple Arrays at Once
      4. Reversing Arrays
      5. Randomizing Order
    9. Acting on Entire Arrays
      1. Calculating the Sum of an Array
      2. Merging Two Arrays
      3. Calculating the Difference Between Two Arrays
      4. Filtering Elements from an Array
    10. Using Arrays
      1. Sets
      2. Stacks
    11. Iterator Interface
  10. 6. Objects
    1. Terminology
    2. Creating an Object
    3. Accessing Properties and Methods
    4. Declaring a Class
      1. Declaring Methods
      2. Declaring Properties
      3. Declaring Constants
      4. Inheritance
      5. Interfaces
      6. Traits
      7. Abstract Methods
      8. Constructors
      9. Destructors
    5. Introspection
      1. Examining Classes
      2. Examining an Object
      3. Sample Introspection Program
    6. Serialization
  11. 7. Web Techniques
    1. HTTP Basics
    2. Variables
    3. Server Information
    4. Processing Forms
      1. Methods
      2. Parameters
      3. Self-Processing Pages
      4. Sticky Forms
      5. Multivalued Parameters
      6. Sticky Multivalued Parameters
      7. File Uploads
      8. Form Validation
    5. Setting Response Headers
      1. Different Content Types
      2. Redirections
      3. Expiration
      4. Authentication
    6. Maintaining State
      1. Cookies
      2. Sessions
      3. Combining Cookies and Sessions
    7. SSL
  12. 8. Databases
    1. Using PHP to Access a Database
    2. Relational Databases and SQL
      1. PHP Data Objects
    3. MySQLi Object Interface
      1. Retrieving Data for Display
    4. SQLite
    5. Direct File-Level Manipulation
    6. MongoDB
      1. Retrieving Data
      2. Inserting More Complex Data
  13. 9. Graphics
    1. Embedding an Image in a Page
    2. Basic Graphics Concepts
    3. Creating and Drawing Images
      1. The Structure of a Graphics Program
      2. Changing the Output Format
      3. Testing for Supported Image Formats
      4. Reading an Existing File
      5. Basic Drawing Functions
    4. Images with Text
      1. Fonts
      2. TrueType Fonts
    5. Dynamically Generated Buttons
      1. Caching the Dynamically Generated Buttons
      2. A Faster Cache
    6. Scaling Images
    7. Color Handling
      1. Using the Alpha Channel
      2. Identifying Colors
      3. True Color Indexes
      4. Text Representation of an Image
  14. 10. PDF
    1. PDF Extensions
    2. Documents and Pages
      1. A Simple Example
      2. Initializing the Document
      3. Outputting Basic Text Cells
    3. Text
      1. Coordinates
      2. Text Attributes
      3. Page Headers, Footers, and Class Extension
      4. Images and Links
      5. Tables and Data
  15. 11. XML
    1. Lightning Guide to XML
    2. Generating XML
    3. Parsing XML
      1. Element Handlers
      2. Character Data Handler
      3. Processing Instructions
      4. Entity Handlers
      5. Default Handler
      6. Options
      7. Using the Parser
      8. Errors
      9. Methods as Handlers
      10. Sample Parsing Application
    4. Parsing XML with DOM
    5. Parsing XML with SimpleXML
    6. Transforming XML with XSLT
  16. 12. Security
    1. Filter Input
    2. Cross-Site Scripting
      1. SQL Injection
    3. Escape Output
      1. Filenames
    4. Session Fixation
    5. File Uploads
      1. Distrust Browser-Supplied Filenames
      2. Beware of Filling Your Filesystem
      3. Surviving register_globals
    6. File Access
      1. Restrict Filesystem Access to a Specific Directory
      2. Get It Right the First Time
      3. Don’t Use Files
      4. Session Files
      5. Concealing PHP Libraries
    7. PHP Code
    8. Shell Commands
    9. More Information
    10. Security Recap
  17. 13. Application Techniques
    1. Code Libraries
    2. Templating Systems
    3. Handling Output
      1. Output Buffering
      2. Compressing Output
    4. Error Handling
      1. Error Reporting
      2. Error Suppression
      3. Triggering Errors
      4. Defining Error Handlers
    5. Performance Tuning
      1. Benchmarking
      2. Profiling
      3. Optimizing Execution Time
      4. Optimizing Memory Requirements
      5. Reverse Proxies and Replication
  18. 14. PHP on Disparate Platforms
    1. Writing Portable Code for Windows and Unix
      1. Determining the Platform
      2. Handling Paths Across Platforms
      3. The Server Environment
      4. Sending Mail
      5. End-of-Line Handling
      6. End-of-File Handling
      7. External Commands
      8. Common Platform-Specific Extensions
    2. Interfacing with COM
      1. Background
      2. PHP Functions
      3. Determining the API
  19. 15. Web Services
    1. REST Clients
      1. Responses
      2. Retrieving Resources
      3. Updating Resources
      4. Creating Resources
      5. Deleting Resources
    2. XML-RPC
      1. Servers
      2. Clients
  20. 16. Debugging PHP
    1. The Development Environment
    2. The Staging Environment
    3. The Production Environment
    4. php.ini Settings
    5. Manual Debugging
    6. Error Log
    7. IDE Debugging
    8. Additional Debugging Techniques
  21. 17. Dates and Times
  22. A. Function Reference
    1. PHP Functions by Category
      1. Arrays
      2. Classes and Objects
      3. Date and Time
      4. Directories
      5. Errors and Logging
      6. Program Execution
      7. Filesystem
      8. Data Filtering
      9. Functions
      10. PHP Options/Info
      11. Mail
      12. Math
      13. Miscellaneous Functions
      14. Network
      15. Output Buffering
      16. Session Handling
      17. Streams
      18. Strings
      19. PHP Language Tokenizer
      20. URLs
      21. Variables
    2. Alphabetical Listing of PHP Functions
  23. Index
  24. About the Authors
  25. Colophon
  26. Special Upgrade Offer
  27. Copyright
O'Reilly logo

A Walk Through PHP

PHP pages are generally HTML pages with PHP commands embedded in them. This is in contrast to many other dynamic web page solutions, which are scripts that generate HTML. The web server processes the PHP commands and sends their output (and any HTML from the file) to the browser. Example 1-1 shows a complete PHP page.

Example 1-1. hello_world.php
<html>
  <head>
    <title>Look Out World</title>
  </head>

  <body>
    <?php echo "Hello, world!"; ?>
<html>
  <head>
    <title>Look Out World</title>
  </head>

  <body>
    <?php echo "Hello, world!"; ?>
  </body>
</html>

Save the contents of Example 1-1 to a file, hello_world.php, and point your browser to it. The results appear in Figure 1-2.

Output of hello_world.php
Figure 1-2. Output of hello_world.php

The PHP echo command produces output (the string “Hello, world!” in this case) inserted into the HTML file. In this example, the PHP code is placed between the <?php and ?> tags. There are other ways to tag your PHP code—see Chapter 2 for a full description.

Configuration Page

The PHP function phpinfo() creates an HTML page full of information on how PHP was installed and is currently configured. You can use it to see whether you have particular extensions installed, or whether the php.ini file has been customized. Example 1-2 is a complete page that displays the phpinfo() page.

Example 1-2. Using phpinfo()
<?php phpinfo();?>

Figure 1-3 shows the first part of the output of Example 1-2.

Partial output of phpinfo()
Figure 1-3. Partial output of phpinfo()

Forms

Example 1-3 creates and processes a form. When the user submits the form, the information typed into the name field is sent back to this page. The PHP code tests for a name field and displays a greeting if it finds one.

Example 1-3. Processing a form (form.php)
<html>
  <head>
    <title>Personalized Greeting Form</title>
  </head>

  <body>
    <?php if(!empty($_POST['name'])) {
      echo "Greetings, {$_POST['name']}, and welcome.";
    } ?>

    <form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
      Enter your name: <input type="text" name="name" />
      <input type="submit" />
    </form>
  </body>
</html>

The form and the message are shown in Figure 1-4.

Form and greeting page
Figure 1-4. Form and greeting page

PHP programs access form values primarily through the $_POST and $_GET array variables. Chapter 7 discusses forms and form processing in more detail. For now be sure that you are processing your pages with the REGISTER_GLOBALS value set to off (the default) in the php.ini file.

Databases

PHP supports all the popular database systems, including MySQL, PostgreSQL, Oracle, Sybase, SQLite, and ODBC-compliant databases. Figure 1-5 shows part of a MySQL database query run through a PHP script showing the results of a book search on a book review site. This is showing the book title, the year the book was published, and the book’s ISBN number.

Note

The SQL code for this sample database is in the provided files called library.sql. You can drop this into MySQL after you create the library database, and have the sample database at your disposal for testing out the following code sample as well as the related samples in Chapter 8.

The code in Example 1-4 connects to the database, issues a query to retrieve all available books (with the WHERE clause), and produces a table as output for all returned results through a while loop.

A MySQL book list query run through a PHP script
Figure 1-5. A MySQL book list query run through a PHP script
Example 1-4. Querying the Books database (booklist.php)
<?php

$db = new mysqli("localhost", "petermac", "password", "library");

// make sure the above credentials are correct for your environment
if ($db->connect_error) {
  die("Connect Error ({$db->connect_errno}) {$db->connect_error}");
}

$sql = "SELECT * FROM books WHERE available = 1 ORDER BY title";
$result = $db->query($sql);

?>
<html>
<body>

<table cellSpacing="2" cellPadding="6" align="center" border="1">
  <tr>
    <td colspan="4">
      <h3 align="center">These Books are currently available</h3>
    </td>
  </tr>

  <tr>
    <td align="center">Title</td>
    <td align="center">Year Published</td>
    <td align="center">ISBN</td>
  </tr>
  <?php while ($row = $result->fetch_assoc()) { ?>
    <tr>
      <td><?php echo stripslashes($row['title']); ?></td>
      <td align="center"><?php echo $row['pub_year']; ?></td>
      <td><?php echo $row['ISBN']; ?></td>
    </tr>
  <?php } ?>
</table>

</body>
</html>

Database-provided dynamic content drives the news, blog, and ecommerce sites at the heart of the Web. More details on accessing databases from PHP are given in Chapter 8.

Graphics

With PHP, you can easily create and manipulate images using the GD extension. Example 1-5 provides a text-entry field that lets the user specify the text for a button. It takes an empty button image file, and on it centers the text passed as the GET parameter 'message'. The result is then sent back to the browser as a PNG image.

Example 1-5. Dynamic buttons (graphic_example.php)
<?php
if (isset($_GET['message'])) {
  // load font and image, calculate width of text
  $font = "times";
  $size = 12;
  $image = imagecreatefrompng("button.png");
  $tsize = imagettfbbox($size, 0, $font, $_GET['message']);

  // center
  $dx = abs($tsize[2] - $tsize[0]);
  $dy = abs($tsize[5] - $tsize[3]);
  $x = (imagesx($image) - $dx) / 2;
  $y = (imagesy($image) - $dy) / 2 + $dy;

  // draw text
  $black = imagecolorallocate($im,0,0,0);
  imagettftext($image, $size, 0, $x, $y, $black, $font, $_GET['message']);

  // return image
  header("Content-type: image/png");
  imagepng($image);

  exit;
} ?>
<html>
  <head>
    <title>Button Form</title>
  </head>

  <body>
    <form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="GET">
      Enter message to appear on button:
      <input type="text" name="message" /><br />
      <input type="submit" value="Create Button" />
    </form>
  </body>
</html>

The form generated by Example 1-5 is shown in Figure 1-6. The button created is shown in Figure 1-7.

You can use GD to dynamically resize images, produce graphs, and much more. PHP also has several extensions to generate documents in Adobe’s popular PDF format. Chapter 9 covers dynamic image generation in depth, while Chapter 10 provides instruction on how to create Adobe PDF files.

Button creation form
Figure 1-6. Button creation form
Button created
Figure 1-7. Button created

Now that you’ve had a taste of what is possible with PHP, you are ready to learn how to program in PHP. We start with the basic structure of the language, with special focus given to user-defined functions, string manipulation, and object-oriented programming. Then we move to specific application areas such as the Web, databases, graphics, XML, and security. We finish with quick references to the built-in functions and extensions. Master these chapters, and you will have mastered PHP!

The best content for your career. Discover unlimited learning on demand for around $1/day.