Review
Product Description
PHP is a simple yet powerful open source scripting language that has become a big player in web development. Over a million web sites, from large corporate sites to small personal sites, are using PHP to serve dynamic web content. PHP's broad feature set, approachable syntax, and support for different operating systems and web servers make it an ideal language for rapid web development.
The PHP Cookbook is a collection of problems, solutions, and practical examples for PHP programmers. The book contains a unique and extensive collection of best practices for everyday PHP programming dilemmas. For every problem addressed in the book, there's a worked-out solution or "recipe" -- short, focused pieces of code that you can insert directly into your applications. But this book offers more than cut-and-paste code. You also get explanations of how and why the code works, so you can learn to adapt the problem-solving techniques to similar situations.
The recipes in the PHP Cookbook range from simple tasks, such as sending a database query and fetching URLs, to entire programs that demonstrate complex tasks, such as printing HTML tables and generating bar charts. This book contains over 250 recipes on the following topics:
- Working with basic data types, including strings, numbers, dates and times, and arrays
- PHP building blocks, such as variables, functions, classes, and objects
- Web programming, including forms, database access, and XML
- Useful features like regular expressions, encryption and security, graphics, internationalization and localization, and Internet services
- Working with files and directories
- Command-line PHP and PHP-GTK
- PEAR, the PHP Extension and Application Repository
From the Publisher
About the Author
is an independent software development and strategic technology consultant. He was a co-founder and the Chief Technology Officer of Student.Com and TVGrid.Com. At both companies, David oversaw the architecture and development of varied systems to deliver personalized dynamic content to users around the world. After discovering PHP as a solution to his web programming needs in 1996, he created the PX (http://px.sklar.com/), which enables PHP users to exchange programs. Since then, he has continued to rely on PHP for personal and professional projects. When away from the computer, David eats mini-donuts, plays records, and likes to cook. He lives in New York City and has a degree in Computer Science from Yale University.
Adam Trachtenberg has an MBA from Columbia Business School. At business school, he focused on general management and operations, with an emphasis on the field of technology. Adam also has a BA from Columbia University. As an undergraduate, he majored in mathematics and his other studies included computer science and Chinese. Before returning to school, he co-founded and served as Vice President for Development at two companies, Student.Com and TVGrid.Com. At both firms, he led the front- and middle-end web site design and development, worked on corporate planning and strategy, and served as liaison between the product and marketing teams. During study breaks, Adam enjoys playing squash, reading fiction, and eating in New York City's many wonderful restaurants. He wishes he was a better at playing pool, knew the constellations, and was handy around the house.
Excerpted from PHP Cookbook by David Sklar, Adam Trachtenberg. Copyright © 2002. Reprinted by permission. All rights reserved.
8.0 Introduction
Web programming is probably why you re reading this book.It s 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.
Recipe 8.4 shows how to redirect users to a different web page than the one they requested. Recipe 8.5 explains the session module, which lets you easily associate persistent data with a user as he moves through your site. Recipe 8.6 demonstrates how to store session information in a database, which increases the scalability and flexibility of your web site. Discovering the features of a users browser is shown in Recipe 8.7. Recipe 8.8 shows the details of constructing a URL that includes a GET query string, including proper encoding of special characters and handling of HTMLentities.
The next two recipes demonstrate how to use authentication, which lets you protect your web pages with passwords. PHPs special features for dealing with HTTP Basic authentication are explained in Recipe 8.9. Sometimes its a better idea to roll your own authentication method using cookies, as shown in Recipe 8.10.
The three following recipes deal with output control.Recipe 8.11 shows how to force output to be sent to the browser. Recipe 8.12 explains the output buffering functions. Output buffers enable you to capture output that would otherwise be printed or delay output until an entire page is processed. Automatic compression of output is shown in Recipe 8.13.
Recipes 8.14 to 8.19 cover error handling topics, including controlling where errors are printed, writing custom functions to handle error processing, and adding debugging assistance information to your programs. Recipe 8.18 includes strategies for avoiding the common "headers already sent "error message, such as using the output buffering discussed in Recipe 8.12.
The next four recipes show how to interact with external variables:environment variables and PHP configuration settings. Recipes 8.20 and 8.21 discuss environment variables,while Recipes 8.22 and 8.23 discuss reading and changing PHP configuration settings. If Apache is your web server, you can use the techniques in Recipe 8.24 to communicate with other Apache modules from within your PHP programs.
Recipe 8.25 demonstrates a few methods for profiling and benchmarking your code. By finding where your programs spend most of their time,you can focus your development efforts on improving the code that has the most noticeable speed-up effect to your users.
This chapter also includes two programs that assist in web site maintenance. Program 8.26 validates user accounts by sending an email message with a customized link to each new user. If the user doesnt visit the link within a week of receiving the message, the account is deleted. Program 8.27 monitors requests in real time on a per-user basis and blocks requests from users that flood your site with traffic.
8.1 Setting Cookies
Problem
You want to set a cookie.
Solution
Use setcookie():
setcookie('flavor','chocolate chip');
Discussion
Cookies are sent with the HTTP headers,so setcookie()must be called before any output is generated.
You can pass additional arguments to setcookie()to control cookie behavior. The third argument to setcookie() is an expiration time, expressed as an epoch time-stamp. For example, this cookie expires at noon GMT on December 3,2004:
setcookie('flavor','chocolate chip',1102075200);
If the third argument to setcookie()is missing (or empty), the cookie expires when the browser is closed. Also, many systems cant handle a cookie expiration time greater than 2147483647, because thats the largest epoch timestamp that fits in a 32-bit integer,as discussed in the introduction to Chapter 3.
The fourth argument to setcookie()is a path. The cookie is sent back to the server only when pages whose path begin with the specified string are requested. For example, the following cookie is sent back only to pages whose path begins with /products/:
setcookie('flavor','chocolate chip','','/products/');
The page thats setting this cookie doesnt have to have a URL that begins with /products/, but the following cookie is sent back only to pages that do.