Medium 9780596101015

PHP Cookbook

Views: 2222
Ratings: (0)

When it comes to creating dynamic web sites, the open source PHP language is red-hot property: used on more than 20 million web sites today, PHP is now more popular than Microsoft's ASP.NET technology. With our Cookbook's unique format, you can learn how to build dynamic web applications that work on any web browser. This revised new edition makes it easy to find specific solutions for programming challenges.

PHP Cookbook has a wealth of solutions for problems that you'll face regularly. With topics that range from beginner questions to advanced web programming techniques, this guide contains practical examples -- or "recipes" -- for anyone who uses this scripting language to generate dynamic web content. Updated for PHP 5, this book provides solutions that explain how to use the new language features in detail, including the vastly improved object-oriented capabilities and the new PDO data access extension. New sections on classes and objects are included, along with new material on processing XML, building web services with PHP, and working with SOAP/REST architectures. With each recipe, the authors include a discussion that explains the logic and concepts underlying the solution.

List price: $35.99

Your Price: $28.79

You Save: 20%

Remix
Remove
 

26 Slices

Format Buy Remix

1. Strings

ePub

Strings in PHP are sequences of bytes, such as We hold these truths to be self-evident or Once upon a time or even 111211211. When you read data from a file or output it to a web browser, your data are represented as strings.

PHP strings are binary-safe (i.e., they can contain null bytes) and can grow and shrink on demand. Their size is limited only by the amount of memory that is available to PHP.

Usually, PHP strings are ASCII strings. You must do extra work to handle non-ASCII data like UTF-8 or other multibyte character encodings, see Chapter19.

Similar in form and behavior to Perl and the Unix shell, strings can be initialized in three ways: with single quotes, with double quotes , and with the here document (heredoc) format. With single-quoted strings, the only special characters you need to escape inside a string are backslash and the single quote itself. Example1-1 shows four single-quoted strings.

Example1-1.Single-quoted strings

 

2. Numbers

ePub

In everyday life, numbers are easy to identify. Theyre 3:00 P.M., as in the current time, or $1.29, as in the cost of a pint of milk. Maybe theyre like , the ratio of the circumference to the diameter of a circle. They can be pretty large, like Avogadros number, which is about 6 1023. In PHP, numbers can be all these things.

However, PHP doesnt treat all these numbers as numbers. Instead, it breaks them down into two groups: integers and floating-point numbers. Integers are whole numbers, such as 4, 0, 5, and 1,975. Floating-point numbers are decimal numbers, such as 1.23, 0.0, 3.14159, and 9.9999999999.

Conveniently, most of the time PHP doesnt make you worry about the differences between the two because it automatically converts integers to floating-point numbers and floating-point numbers to integers. This conveniently allows you to ignore the underlying details. It also means 3/2 is 1.5, not 1, as it would be in some programming languages. PHP also automatically converts from strings to numbers and back. For instance, 1+"1" is 2.

 

3. Dates and Times

ePub

Displaying and manipulating dates and times seems simple at first but gets more difficult depending on how diverse and complicated your users are. Do your users span more than one time zone? Probably so, unless you are building an intranet or a site with a very specific geographical audience. Is your audience frightened away by timestamps that look like 2002-07-20 14:56:34 EDT or do they need to be calmed with familiar representations like Saturday July 20, 2000 (2:56 P.M.)? Calculating the number of hours between today at 10 A.M. and today at 7 P.M. is pretty easy. How about between today at 3 A.M. and noon on the first day of next month? Finding the difference between dates is discussed in Recipes 3.5 and 3.6.

These calculations and manipulations are made even more hectic by daylight saving (or summer) time (DST). Because of DST, there are times that dont exist (in most of the United States, 2 A.M. to 3 A.M. on a day in the spring) and times that exist twice (in most of the United States, 1 A.M. to 2 A.M. on a day in the fall). Some of your users may live in places that observe DST, some may not. Recipes 3.11 and 3.12 provide ways to work with time zones and DST.

 

4. Arrays

ePub

Arrays are lists: lists of people, lists of sizes, lists of books. To store a group of related items in a variable, use an array. Like a list on a piece of paper, the elements in array have an order. Usually, each new item comes after the last entry in the array, but just as you can wedge a new entry between a pair of lines already in a paper list, you can do the same with arrays in PHP.

In many languages, there is only one type of array: this is called a numerical array (or just an array). In a numerical array, if you want to find an entry, you need to know its position within the array, known as an index. Positions are identified by numbers: they start at 0 and work upward one by one.

In some languages, there is also another type of array: an associative array, also known as a hash. In an associative array, indexes arent integers, but strings. So in a numerical array of U.S. presidents, Abraham Lincoln might have index 16; in the associative-array version, the index might be Honest. However, while numerical arrays have a strict ordering imposed by their keys, associative arrays frequently make no guarantees about the key ordering. Elements are added in a certain order, but theres no way to determine the order later.

 

5. Variables

ePub

Along with conditional logic, variables are the core of what makes computer programs powerful and flexible. If you think of a variable as a bucket with a name that holds a value, PHP lets you have plain old buckets, buckets that contain the name of other buckets, buckets with numbers or strings in them, buckets holding arrays of other buckets, buckets full of objects, and just about any other variation on that analogy you can think of.

A variable is either set or unset. A variable with any value assigned to it, true or false, empty or nonempty, is set. The function isset() returns true when passed a variable thats set. To turn a variable thats set into one thats unset, call unset() on the variable or assign null to the variable. Scalars, arrays, and objects can all be passed to unset(). You can also pass unset() multiple variables to unset them all:

If a variable is present in the query string of a URL, even if it has no value assigned to it, it is set. Thus:

 

6. Functions

ePub

Functions help you create organized and reusable code. They allow you to abstract out details so your code becomes more flexible and more readable. Without functions, it is impossible to write easily maintainable programs because youre constantly updating identical blocks of code in multiple places and in multiple files.

With a function you pass a number of arguments in and get a value back:

Declare a function using the function keyword, followed by the name of the function and any parameters in parentheses. To invoke a function, simply use the function name, specifying argument values for any parameters to the function. If the function returns a value, you can assign the result of the function to a variable, as shown in the previous example.

You dont need to predeclare a function before you call it. PHP parses the entire file before it begins executing, so you can intermix function declarations and invocations. You cant, however, redefine a function in PHP. If PHP encounters a function with a name identical to one its already found, it throws a fatal error and dies.

 

7. Classes and Objects

ePub

PHP 5 has significantly improved support for object-oriented programming (OOP). This is a major change and a key reason to upgrade your code from PHP 4. If youre a fan of OOP, you will be very happy with the tools PHP 5 provides you.

Early versions of PHP were strictly procedural: you could define functions, but not objects. PHP 3 introduced an extremely rudimentary form of objects, written as a late-night hack. Back in 1997, nobody expected the explosion in the number of PHP programmers, or that people would write large-scale programs in PHP. Therefore, these limitations werent considered a problem.

Over the years, PHP gained additional object-oriented features; however, the development team never redesigned the core OO code to gracefully handle objects and classes. As a result, although PHP 4 improved overall performance, writing complex OO programs with it is still difficult, if not nearly impossible.

PHP 5 fixes these problems by using Zend Engine 2 (ZE2). ZE2 enables PHP to include more advanced object-oriented features, while still providing a high degree of backward compatibility to the millions of PHP scripts already written.

 

8. Web Basics

ePub

Web programming is probably why youre reading this book. Its why the first version of PHP was written and what continues to make it so popular today. With PHP, its easy to write dynamic web programs that do almost anything. Other chapters cover various PHP capabilities, like graphics, regular expressions, database access, and file I/O. These capabilities are all part of web programming, but this chapter focuses on some web-specific concepts and organizational topics that will make your web programming stronger.

Recipes 8.1, 8.2, and 8.3 show how to set, read, and delete cookies. A cookie is a small text string that the server instructs the browser to send along with requests the browser makes. Normally, HTTP requests arent stateful; each request cant be connected to a previous one. A cookie, however, can link different requests by the same user. This makes it easier to build features such as shopping carts or to keep track of a users search history.

 

9. Form

ePub

The genius of PHP is its seamless integration of form variables into your programs. It makes web programming smooth and simple, speeding the cycle from web form to PHP code to HTML output.

With that convenience, however, comes the responsibility to make sure that the user-provided information that flows so easily into your program contains appropriate content. External input can never be trusted, so its imperative always to validate all incoming data. Recipes 9.2 through 9.9 show how to validate common kinds of information as well as providing general guidelines on arbitrary form validation you might need to do. Recipe9.10 discusses escaping HTML entities to allow the safe display of user-entered data. Recipe9.14 covers how to process files uploaded by a user.

HTTP is a stateless protocolit has no built-in mechanism that helps you to save information from one page so you can access it in other pages. Recipes 9.11, 9.12, and 9.13 all show ways to work around the fundamental problem of figuring out which user is making which requests to your web server.

 

10. Database Access

ePub

Databases are central to many web applications. A database can hold almost any collection of information you may want to search and update, such as a user list, a product catalog, or recent headlines. One reason why PHP is such a great web programming language is its extensive database support. PHP can interact with (at last count) more than 20 different databases, some relational and some not. The relational databases it can talk to are Apache Derby, DB++, FrontBase, IBM Cloudscape, IBM DB2, Informix, Interbase, Ingres II, Microsoft SQL Server, mSQL, MySQL, MySQL MaxDB, Oracle, Ovrimos SQL Server, PostgreSQL, SQLite, and Sybase. The nonrelational databases it can talk to are dBase, filePro, HyperWave, Paradox, and the DBM family of flat-file databases. It also has ODBC support, so even if your favorite database isnt in the list, as long as it supports ODBC, you can use it with PHP.

DBM databases, discussed in Recipe10.1, are simple, robust, and efficient flat files but limit the structure of your data to key/value pairs. If your data can be organized as a mapping of keys to values, DBM databases are a great choice.

 

11. Sessions and Data Persistence

ePub

As web applications have matured, the need for statefulness has become a common requirement. Stateful web applications, meaning applications that keep track of a particular visitors information as he travels throughout a site, are now so common that they are taken for granted.

Given the prevalence of web applications that keep track of things for their visitorssuch as shopping carts, online banking, personalized home page portals, and social networking community sitesit is hard to imagine the Internet we use every day without stateful applications.

HTTP, the protocol that web servers and clients use to talk to each other, is a stateless protocol by design. However, since PHP 4.0, developers whove built applications with PHP have had a convenient set of session management functions that have made the challenge of implementing statefulness much easier. This chapter focuses on several good practices to keep in mind while developing stateful applications.

 

12. XML

ePub

XML has gained popularity as a data-exchange and message-passing format. As web services become more widespread, XML plays an even more important role in a developers life. With the help of a few extensions, PHP lets you read and write XML for every occasion.

XML provides developers with a structured way to mark up data with tags arranged in a tree-like hierarchy. One perspective on XML is to treat it as CSV on steroids. You can use XML to store records broken into a series of fields. But instead of merely separating each field with a comma, you can include a field name, a type, and attributes alongside the data.

Another view of XML is as a document representation language. For instance, this book was written using XML. The book is divided into chapters; each chapter into recipes; and each recipe into Problem, Solution, and Discussion sections. Within any individual section, we further subdivide the text into paragraphs, tables, figures, and examples. An article on a web page can similarly be divided into the page title and headline, the authors of the piece, the story itself, and any sidebars, related links, and additional content.

 

13. Web Automation

ePub

Most of the time, PHP is part of a web server, sending content to browsers. Even when you run it from the command line, it usually performs a task and then prints some output. PHP can also be useful, however, playing the role of a web client, retrieving URLs and then operating on the content. Most recipes in this chapter cover retrieving URLs and processing the results, although there are a few other tasks in here as well, such as cleaning up URLs and some JavaScript-related operations.

There are many ways retrieve a remote URL in PHP. Choosing one method over another depends on your needs for simplicity, control, and portability. The three methods discussed in this chapter are standard file functions, the cURL extension, and the HTTP_Request class from PEAR. These three methods can generally do everything you need and at least one of them should be available to you whatever your server configuration or ability to install custom extensions. Other ways to retrieve remote URLs include the pecl_http extension (http://pecl.php.net/package/pecl_http), which, while still in development, offers some promising features, and using the fsockopen() function to open a socket over which you send an HTTP request that you construct piece by piece.

 

14. Consuming Web Services

ePub

Web services allow you to exchange information over HTTP using XML. When you want to find out the weather forecast for New York City, the current stock price of IBM, or the cost of a flat screen TV on eBay, you can write a short script to gather that data in a format you can easily manipulate. From a developers perspective, its as if youre calling a local function that returns a value.

The key behind web services is platform-independent communication. Your PHP script running on Linux can talk to someone elses IIS server on a Windows box using ASP without any communication problems. Likewise, you can talk to a box running Solaris, Apache, and JSP using the same sets of tools and interfaces.

There are two major types of web services: REST and SOAP. A REST request is relatively straightforward, as they involve making an HTTP request of a server and processing an XML document thats returned as the response. Since most developers are familiar with HTTP and XML, the learning curve for REST is short and shallow.

 

15. Building Web Services

ePub

This chapter covers building web services. If youre unfamiliar with the fundamental concepts of web services, including REST, SOAP, and XML-RPC, jump back a chapter and read through Chapter14. It provides the building blocks for the web services servers described here.

Recipe15.1 covers building a REST method. With a REST server, you accept an HTTP request, process the incoming data, and reply, usually with XML.

From there, the chapter moves to SOAP. Recipes 15.2 and 15.3 show how to serve a SOAP method with and without input arguments.

Recipe15.4 breaks the bad news that PHP cannot automatically generate WSDL files from PHP classes, while Recipe15.5 shows how to throw SOAP faults.

SOAP headers are the topic of the next two recipes. First, in Recipe15.6, you learn how to process a SOAP header. Then, Recipe15.7 shows how to generate a SOAP header.

The SOAP portion concludes with a discussion on how to combine authentication with SOAP in Recipe15.8.

 

16. Internet Services

ePub

Before there was HTTP, there was FTP, NNTP, IMAP, POP3, and a whole alphabet soup of other protocols. Many people quickly embraced web browsers because the browser provided an integrated program that let them check their email, read newsgroups, transfer files, and view documents without worrying about the details surrounding the underlying means of communication. PHP provides functions, both natively and through PEAR, to use these other protocols. With them, you can use PHP to create web frontend applications that perform all sorts of network-enabled tasks, such as looking up domain names or sending web-based email. While PHP simplifies these jobs, it is important to understand the strengths and limitations of each protocol.

Recipes 16.1 to 16.3 cover the most popular feature of all: email. Recipe16.1 shows how to send basic email messages. Recipe16.2 describes MIME-encoded email, which enables you to send plain text and HTML-formatted messages. The IMAP and POP3 protocols, which are used to read mailboxes, are discussed in Recipe16.3.

 

17. Graphics

ePub

With the assistance of the GD library, you can use PHP to create applications that use dynamic images to display stock quotes, reveal poll results, monitor system performance, and even create games. However, its not like using Photoshop or GIMP; you cant draw a line by moving your mouse. Instead, you need to precisely specify a shapes type, size, and position.

GD has an existing API, and PHP tries to follows its syntax and function-naming conventions. So if youre familiar with GD from other languages, such as C or Perl, you can easily use GD with PHP. If GD is new to you, it may take a few minutes to figure it out, but soon youll be drawing like Picasso.

The feature set of GD varies greatly depending on which version of GD youre running and which features were enabled during configuration. GD can support GIFs, JPEGs, PNGs, and WBMPs. GD reads in PNGs and JPEGs with almost no loss in quality. Also, GD supports PNG alpha channels, which allow you to specify a transparency level for each pixel.

 

18. Security and Encryption

ePub

Web application security is an important topic thats gaining more attention from both the developers who create web applications, and the attackers who try to exploit them. As a PHP developer, your applications are sure to be the target of many attacks, and you need to be prepared.

A large number of web application vulnerabilities are due to a misplaced trust in data provided by third parties. Such data is known as input, and it should be considered tainted until proven otherwise. If you display tainted data to your users, you create cross-site scripting (XSS) vulnerabilities. Recipe18.4 explains how to avoid these by escaping your output. If you use tainted data in your SQL queries, you can create SQL injection vulnerabilities. Recipe18.5 shows you how to eliminate these.

When using data provided by third parties, including the data provided by your users, it is important to first verify that it is valid. This process is known as filtering, and Recipe18.3 shows you how to guarantee that all input is filtered.

 

Load more


Details

Print Book
E-Books
Slices

Format name
ePub
Encrypted
No
Sku
B000000025446
Isbn
9780596101015
File size
1.85 MB
Printing
Allowed
Copying
Allowed
Read aloud
Allowed
Format name
ePub
Encrypted
No
Printing
Allowed
Copying
Allowed
Read aloud
Allowed
Sku
In metadata
Isbn
In metadata
File size
In metadata