Docsity
Docsity

Prepare-se para as provas
Prepare-se para as provas

Estude fácil! Tem muito documento disponível na Docsity


Ganhe pontos para baixar
Ganhe pontos para baixar

Ganhe pontos ajudando outros esrudantes ou compre um plano Premium


Guias e Dicas
Guias e Dicas


Programming PHP 2002, Notas de estudo de Análise de Sistemas de Engenharia

Programming PHP 2002

Tipologia: Notas de estudo

Antes de 2010

Compartilhado em 20/08/2010

luciana-sampaio-10
luciana-sampaio-10 🇧🇷

4.5

(20)

68 documentos

1 / 508

Toggle sidebar

Esta página não é visível na pré-visualização

Não perca as partes importantes!

bg1
Programming PHP
,TITLE.18349 Page i Wednesday, March 13, 2002 11:52 AM
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe
pff
pf12
pf13
pf14
pf15
pf16
pf17
pf18
pf19
pf1a
pf1b
pf1c
pf1d
pf1e
pf1f
pf20
pf21
pf22
pf23
pf24
pf25
pf26
pf27
pf28
pf29
pf2a
pf2b
pf2c
pf2d
pf2e
pf2f
pf30
pf31
pf32
pf33
pf34
pf35
pf36
pf37
pf38
pf39
pf3a
pf3b
pf3c
pf3d
pf3e
pf3f
pf40
pf41
pf42
pf43
pf44
pf45
pf46
pf47
pf48
pf49
pf4a
pf4b
pf4c
pf4d
pf4e
pf4f
pf50
pf51
pf52
pf53
pf54
pf55
pf56
pf57
pf58
pf59
pf5a
pf5b
pf5c
pf5d
pf5e
pf5f
pf60
pf61
pf62
pf63
pf64

Pré-visualização parcial do texto

Baixe Programming PHP 2002 e outras Notas de estudo em PDF para Análise de Sistemas de Engenharia, somente na Docsity!

Programming PHP

Programming PHP by Rasmus Lerdorf and Kevin Tatroe with Bob Kaehms and Ric McGredy

Copyright © 2002 O’Reilly & Associates, Inc. All rights reserved. Printed in the United States of America.

Published by O’Reilly & Associates, Inc., 1005 Gravenstein Highway North, Sebastopol, CA 95472.

O’Reilly & Associates books may be purchased for educational, business, or sales promotional use. Online editions are also available for most titles ( safari.oreilly.com ). For more information, contact our corporate/institutional sales department: (800) 998-9938 or [email protected].

Editors: Nathan Torkington and Paula Ferguson

Production Editor: Rachel Wheeler

Cover Designer: Ellie Volckhausen

Interior Designer: Melanie Wang

Printing History:

March 2002: First Edition.

Nutshell Handbook, the Nutshell Handbook logo, and the O’Reilly logo are registered trademarks of O’Reilly & Associates, Inc. Many of the designations used by manufacturers and sellers to distinguish their products are claimed as trademarks. Where those designations appear in this book, and O’Reilly & Associates, Inc. was aware of a trademark claim, the designations have been printed in caps or initial caps. The association between the image of a cuckoo and PHP is a trademark of O’Reilly & Associates, Inc.

While every precaution has been taken in the preparation of this book, the publisher and authors assume no responsibility for errors or omissions, or for damages resulting from the use of the information contained herein.

ISBN: 1-56592-610- [M]

About the Authors

Rasmus Lerdorf was born in Godhavn/Qeqertarsuaq on Disco Island, off the coast of Greenland, in 1968. He has been dabbling with Unix-based solutions since 1985. He is known for having gotten the PHP project off the ground in 1995, and he can be blamed for the ANSI-92 SQL-defying LIMIT clause in mSQL 1.x, which has now, at least conceptually, crept into both MySQL and PostgreSQL.

Rasmus tends to deny being a programmer, preferring to be seen as a techie who is adept at solving problems. If the solution requires a bit of coding and he can’t trick somebody else into writing the code, he will reluctantly give in and write it himself. He currently lives near San Francisco with his wife Christine.

Kevin Tatroe has been a Macintosh and Unix programmer for 10 years. Being lazy, he’s attracted to languages and frameworks that do much of the work for you, such as the AppleScript, Perl, and PHP languages and the WebObjects and Cocoa programming environments.

Kevin, his wife Jenn, his son Hadden, and their two cats live on the edge of the rural plains of Colorado, just far away enough from the mountains to avoid the worst snowfall, and just close enough to avoid tornadoes. The house is filled with LEGO creations, action figures, and numerous other toys.

Bob Kaehms has spent most of his professional career working with computers. After a prolonged youth that he stretched into his late 20s as a professional scuba diver, ski patroller, and lifeguard, he went to work as a scientific programmer for Lockheed Missiles and Space Co. Frustrations with the lack of information-sharing within the defense industry led him first to groupware and then to the Web.

Bob helped found the Internet Archive, where as Director of Computing he was responsible for the first full backup of all publicly available data on the Internet. Bob also served as Editor in Chief of Web Techniques Magazine , the leading technical magazine for web developers. He is presently CTO at Media Net Link, Inc. Bob has a degree in applied mathematics, and he uses that training to study the chaos that exists around his house.

Ric McGredy founded Media Net Link, Inc. in 1994, after long stints at Bank of America, Apple Computer, and Sun Microsystems, to pursue excellence in customer- focused web-service construction and deployment. While he has been known to crank out a line or two of code, Ric prides himself first and foremost as being busi- ness-focused and on integrating technology into the business enterprise with high reliability at a reasonable cost.

Ric received a BA in French from Ohio Wesleyan University and has been involved in the accounting and information-technology disciplines for over 25 years. Ric lives near San Francisco with his wife Sally and five children.

v

Table of Contents

    1. Introduction to PHP Preface ix
    • What Does PHP Do?
    • A Brief History of PHP
    • Installing PHP
    • A Walk Through PHP
    1. Language Basics
    • Lexical Structure
    • Data Types
    • Variables
    • Expressions and Operators
    • Flow-Control Statements
    • Including Code
    • Embedding PHP in Web Pages
    1. Functions
    • Calling a Function
    • Defining a Function
    • Variable Scope
    • Function Parameters
    • Return Values
    • Variable Functions
    • Anonymous Functions
    1. Strings
    • Quoting String Constants
    • Printing Strings
    • Accessing Individual Characters vi | Table of Contents
    • Cleaning Strings
    • Encoding and Escaping
    • Comparing Strings
    • Manipulating and Searching Strings
    • Regular Expressions
    • POSIX-Style Regular Expressions
    • Perl-Compatible Regular Expressions
    1. Arrays
    • Indexed Versus Associative Arrays
    • Identifying Elements of an Array
    • Storing Data in Arrays
    • Multidimensional Arrays
    • Extracting Multiple Values
    • Converting Between Arrays and Variables
    • Traversing Arrays
    • Sorting
    • Acting on Entire Arrays
    • Using Arrays
    1. Objects
    • Terminology
    • Creating an Object
    • Accessing Properties and Methods
    • Declaring a Class
    • Introspection
    • Serialization
    1. Web Techniques
    • HTTP Basics
    • Variables
    • Server Information
    • Processing Forms
    • Setting Response Headers
    • Maintaining State
    • SSL
      1. Databases Table of Contents | vii
      • Using PHP to Access a Database
      • Relational Databases and SQL
      • PEAR DB Basics
      • Advanced Database Techniques
      • Sample Application
      1. Graphics
      • Embedding an Image in a Page
      • The GD Extension
      • Basic Graphics Concepts
      • Creating and Drawing Images
      • Images with Text
      • Dynamically Generated Buttons
      • Scaling Images
      • Color Handling
    1. PDF
      • PDF Extensions
      • Documents and Pages
      • Text
      • Images and Graphics
      • Navigation
      • Other PDF Features
    1. XML
      • Lightning Guide to XML
      • Generating XML
      • Parsing XML
      • Transforming XML with XSLT
      • Web Services
    1. Security
      • Global Variables and Form Data
      • Filenames
      • File Uploads
      • File Permissions
        • Concealing PHP Libraries viii | Table of Contents
        • PHP Code
        • Shell Commands
        • Security Redux
      1. Application Techniques
        • Code Libraries
        • Templating Systems
        • Handling Output
        • Error Handling
        • Performance Tuning
      1. Extending PHP
        • Architectural Overview
        • What You’ll Need
        • Building Your First Extensions
        • The config.m4 File
        • Memory Management
        • The pval/zval Data Type
        • Parameter Handling
        • Returning Values
        • References
        • Global Variables
        • Creating Variables
        • Extension INI Entries
        • Resources
        • Where to Go from Here
      1. PHP on Windows
        • Installing and Configuring PHP on Windows
        • Writing Portable Code for Windows and Unix
        • Interfacing with COM
        • Interacting with ODBC Data Sources
      • A. Function Reference
      • B. Extension Overview
  • Index

This is the Title of the Book, eMatter Edition Copyright © 2002 O’Reilly & Associates, Inc. All rights reserved.

ix

Preface

Now, more than ever, the Web is a major vehicle for corporate and personal commu- nications. Web sites carry photo albums, shopping carts, and product lists. Many of those web sites are driven by PHP, an open source scripting language primarily designed for generating HTML content.

Since its inception in 1994, PHP has swept over the Web. The millions of web sites powered by PHP are testament to its popularity and ease of use. It lies in the sweet spot between Perl/CGI, Active Server Pages (ASP), and HTML. Everyday people can learn PHP and can build powerful dynamic web sites with it.

The core PHP language features powerful string- and array-handling facilities, as well as support for object-oriented programming. With the use of standard and optional extension modules, a PHP application can interact with a database such as MySQL or Oracle, draw graphs, create PDF files, and parse XML files. You can write your own PHP extension modules in C—for example, to provide a PHP interface to the functions in an existing code library. You can even run PHP on Windows, which lets you control other Windows applications such as Word and Excel with COM, or interact with databases using ODBC.

This book is a guide to the PHP language. When you finish this book, you will know how the PHP language works, how to use the many powerful extensions that come standard with PHP, and how to design and build your own PHP web applications.

Audience for This Book

PHP is a melting pot of cultures. Web designers appreciate its accessibility and con- venience, while programmers appreciate its flexibility and speed. Both cultures need a clear and accurate reference to the language.

If you’re a programmer, this book is for you. We show the big picture of the PHP language, then discuss the details without wasting your time. The many examples

This is the Title of the Book, eMatter Edition Copyright © 2002 O’Reilly & Associates, Inc. All rights reserved.

Preface | xi

Chapter 12, Security , provides valuable advice and guidance for programmers in cre- ating secure scripts. You’ll learn best-practices programming techniques here that will help you avoid mistakes that can lead to disaster.

Chapter 13, Application Techniques , talks about the advanced techniques that most PHP programmers eventually want to use, including error handling and perfor- mance tuning.

Chapter 14, Extending PHP , is an advanced chapter that presents easy-to-follow instructions for building a PHP extension in C.

Chapter 15, PHP on Windows , discusses the tricks and traps of the Windows port of PHP. It also discusses the features unique to Windows, such as COM and ODBC.

Appendix A, Function Reference , is a handy quick reference to all the core functions in PHP.

Appendix B, Extension Overview , describes the standard extensions that ship with PHP.

Conventions Used in This Book

The following typographic conventions are used in this book:

Italic Used for file and directory names, email addresses, and URLs, as well as for new terms where they are defined.

Constant Width Used for code listings and for keywords, variables, functions, command options, parameters, class names, and HTML tags where they appear in the text.

Constant Width Bold Used to mark lines of output in code listings.

Constant Width Italic Used as a general placeholder to indicate items that should be replaced by actual values in your own programs.

Comments and Questions

Please address comments and questions concerning this book to the publisher:

O’Reilly & Associates, Inc. 1005 Gravenstein Highway North Sebastopol, CA 95472 (800) 998-9938 (in the United States or Canada) (707) 829-0515 (international/local) (707) 829-0104 (fax)

This is the Title of the Book, eMatter Edition Copyright © 2002 O’Reilly & Associates, Inc. All rights reserved.

xii | Preface

There is a web page for this book, which lists errata, examples, or any additional information. You can access this page at:

http://www.oreilly.com/catalog/progphp/

To comment or ask technical questions about this book, send email to:

[email protected]

For more information about books, conferences, Resource Centers, and the O’Reilly Network, see the O’Reilly web site at:

http://www.oreilly.com

Acknowledgments

All of the authors would like to thank the technical reviewers for their helpful com- ments on the content of this book: Shane Caraveo, Andi Gutmans, and Stig Bakken. We’d also like to thank Andi Gutmans, Zeev Suraski, Stig Bakken, Shane Caraveo, and Randy Jay Yarger for their contributions to early drafts of material for this book.

Rasmus Lerdorf

I would like to acknowledge the large and wonderfully boisterous PHP community, without which there would be no PHP today.

Kevin Tatroe

I’ll err on the side of caution and thank Nat Torkington for dragging me into this project. (“You don’t want to write a book, it’s a miserable experience... Hey, want to write a book?”) While I was writing, the denizens of Nerdsholm and 3WA were always quick with help and/or snarky commentary, both of which contributed to the book’s completion. Without twice-monthly game sessions to keep me sane, I would surely have given up well before the last chapter was delivered: thank you to my fel- low players, Jenn, Keith, Joe, Keli, Andy, Brad, Pete, and Jim.

Finally, and most importantly, a huge debt of gratitude is owed to Jennifer and Had- den, both of whom put up with more neglect over the course of the past year than any good people deserve.

Bob Kaehms

Thanks to my wife Janet and the kids (Jenny, Megan, and Bobby), to Alan Brown for helping me understand the issues in integrating COM with PHP, and to the staff at Media Net Link for allowing me to add this project to my ever-expanding list of extracurricular activities.

This is the Title of the Book, eMatter Edition Copyright © 2002 O’Reilly & Associates, Inc. All rights reserved.

17

Chapter 2 (^) CHAPTER 2

Language Basics

This chapter provides a whirlwind tour of the core PHP language, covering such basic topics as data types, variables, operators, and flow control statements. PHP is strongly influenced by other programming languages, such as Perl and C, so if you’ve had experience with those languages, PHP should be easy to pick up. If PHP is one of your first programming languages, don’t panic. We start with the basic units of a PHP program and build up your knowledge from there.

Lexical Structure

The lexical structure of a programming language is the set of basic rules that governs how you write programs in that language. It is the lowest-level syntax of the lan- guage and specifies such things as what variable names look like, what characters are used for comments, and how program statements are separated from each other.

Case Sensitivity

The names of user-defined classes and functions, as well as built-in constructs and keywords such as echo, while, class, etc., are case-insensitive. Thus, these three lines are equivalent:

echo("hello, world"); ECHO("hello, world"); EcHo("hello, world");

Variables, on the other hand, are case-sensitive. That is, $name, $NAME, and $NaME are three different variables.

Statements and Semicolons

A statement is a collection of PHP code that does something. It can be as simple as a variable assignment or as complicated as a loop with multiple exit points. Here is

This is the Title of the Book, eMatter Edition Copyright © 2002 O’Reilly & Associates, Inc. All rights reserved.

Lexical Structure | 19

Comments

Comments give information to people who read your code, but they are ignored by PHP. Even if you think you’re the only person who will ever read your code, it’s a good idea to include comments in your code—in retrospect, code you wrote months ago can easily look as though a stranger wrote it.

Good practice is to make your comments sparse enough not to get in the way of the code itself and plentiful enough that you can use the comments to tell what’s hap- pening. Don’t comment obvious things, lest you bury the comments that describe tricky things. For example, this is worthless:

$x = 17; // store 17 into the variable $x

whereas this may well help whoever will maintain your code:

// convert &#nnn; entities into characters $text = preg_replace('/&#([0-9])+);/e', "chr('\1')", $text);

PHP provides several ways to include comments within your code, all of which are bor- rowed from existing languages such as C, C++, and the Unix shell. In general, use C- style comments to comment out code, and C++-style comments to comment on code.

Shell-style comments

When PHP encounters a hash mark (#) within the code, everything from the hash mark to the end of the line or the end of the section of PHP code (whichever comes first) is considered a comment. This method of commenting is found in Unix shell scripting languages and is useful for annotating single lines of code or making short notes.

Because the hash mark is visible on the page, shell-style comments are sometimes used to mark off blocks of code:

#######################

Cookie functions

#######################

Sometimes they’re used before a line of code to identify what that code does, in which case they’re usually indented to the same level as the code:

if ($double_check) {

create an HTML form requesting that the user confirm the action

echo confirmation_form( ); }

Short comments on a single line of code are often put on the same line as the code:

$value = $p * exp($r * $t); # calculate compounded interest

When you’re tightly mixing HTML and PHP code, it can be useful to have the clos- ing PHP tag terminate the comment:

Then another Then another 4

This is the Title of the Book, eMatter Edition Copyright © 2002 O’Reilly & Associates, Inc. All rights reserved.

20 | Chapter 2: Language Basics

C++ comments

When PHP encounters two slash characters (//) within the code, everything from the slashes to the end of the line or the end of the section of code, whichever comes first, is considered a comment. This method of commenting is derived from C++. The result is the same as the shell comment style.

Here are the shell-style comment examples, rewritten to use C++ comments:

//////////////////////// // Cookie functions ////////////////////////

if ($double_check) { // create an HTML form requesting that the user confirm the action echo confirmation_form( ); }

$value = $p * exp($r * $t); // calculate compounded interest

Then another Then another 4

C comments

While shell- and C++-style comments are useful for annotating code or making short notes, longer comments require a different style. As such, PHP supports block com- ments, whose syntax comes from the C programming language. When PHP encoun- ters a slash followed by an asterisk (/), everything after that until it encounters an asterisk followed by a slash (/) is considered a comment. This kind of comment, unlike those shown earlier, can span multiple lines.

Here’s an example of a C-style multiline comment:

/* In this section, we take a bunch of variables and assign numbers to them. There is no real reason to do this, we're just having fun. */ $a = 1; $b = 2; $c = 3; $d = 4;

Because C-style comments have specific start and end markers, you can tightly inte- grate them with code. This tends to make your code harder to read, though, so it is frowned upon:

/* These comments can be mixed with code too, see? / $e = 5; / This works just fine. */

C-style comments, unlike the other types, continue past end markers. For example:

Some stuff you want to be HTML.