Build Dynamic, Database-Driven Web Sites
PHP is a fully developed, server-side embedded scripting language, and its importance for web application development has grown with the rise of the Apache web server. Are you a novice programmer? This book starts with the basics and takes you wherever you want to go. A seasoned pro? You'll be amazed at how much you can capitalize on PHP's power and object-oriented support, and how it leverages your knowledge of other languages. Finally, if you're a PHP user in search of an authoritative reference, you need look no further. Mastering PHP 4.1 guides you through all levels of real-world web programming problems and provides expert advice on which solutions work best.
- Reading and writing files
- Validating data with regular expressions
- Accessing MySQL and PostgreSQL databases
- Accessing LDAP servers
- Generating images and PDF documents on the fly
- Building authentication and access-control systems
- Sending e-mail and building web-to-e-mail interfaces
- Creating your own classes
- Closing common security holes in PHP scripts
- Parsing and generating XML documents
- Using sessions to store persistent data
- Debugging misbehaving scripts
- Encrypting and decrypting sensitive data
Note: CD-ROM/DVD and other supplementary materials are not included as part of eBook file.
About the Author
Jeremy Allen is an application developer for elliptIQ Inc. in Atlanta. He has been developing software, ranging from multiuser games to corporate intranets, for six years and has been creating programs in PHP since 1997. His wide variety of web applications ranges from content management systems to insurance apps.
Charles Hornberger is a software developer and writer living in Los Angeles. He has been using PHP since 1997 to build online stores, corporate intranets, web news sites, and meta-search engines. He is also a senior software developer for the web development and hosting company Nothing Special Network Services (www.nothingspecial.com).
Read an Excerpt
Mastering PHP 4.1
By Jeremy Allen
John Wiley & SonsISBN: 0-7821-2924-2
Chapter OneBeginning Your Exploration of PHP
Developing applications and sites for the World Wide Web, or for Web-like uses such as intranets, has become one of the most extensive areas of computing and programming work. If it can be done digitally, then somebody, somewhere, is trying to adapt it to a web browser. Understanding the various flavors of web activity-static and dynamic pages, client-side and server-side systems-is a necessary step toward increasing your flexibility as a developer.
PHP builds upon the familiar structure of programming languages such as C, Java, and Perl. It helps create dynamic HTML content by providing the necessary tools to easily manipulate that content. PHP is becoming one of the preeminent tools for increasing the power of web pages because it is easy to use yet powerful. Building a few elementary scripts, testing the two main methods of moving data back and forth, and learning to comment PHP code will demonstrate just how accessible PHP's features are.
Developing for the Web
The term web development paints a wide, long stroke. It is a general term to categorize a large variety of activities. Web development can mean anything from putting a static HTML page on a small World Wide Web site to developing a massive, continent-spanning, corporate intranet that handles mission-critical business communications. But these activities do break down into several manageable categories.
To get into the topic of developing web applications, first we must tackle the term application: What is an application? What should an application do?
An application is any software developed to simplify or perform a task. The level of the task varies from very specific to more general. A program that takes the grades of a student's six classes, averages those grades, and summarizes them in a report is a simple, but limited, application. On the other hand, an application that provides the means to communicate with others, such as an online groupware app (one that allows users to coordinate their workflow), is more complex and achieves a more general goal. Although the scope of the groupware application is much wider than the scope of the grade-averaging program, both are still applications.
Then, what specifically are web applications? A web application, in general, is an application that leverages the ubiquity and ease of communication the Internet provides. A more restricted definition of web application-the one that will be used throughout the book-is an application that uses a web browser as the client. There are many client-side technologies available to most web browsers. In general, the most far-reaching and easily accessed web applications are those that use simple and elegant Hypertext Markup Language (HTML). A few examples that strictly fit the term web application are web-based banking systems, auctions, and news sites.
Static and Dynamic Websites
Static sites have content that does not change until the author updates it, and these sites work well for many people because they allow information to be shared. However, static sites provide no interaction with visitors and do not accomplish any tasks in a programmable way.
Dynamic sites allow user interaction. Although, like a static site, a dynamic one uses HTML for the client interface, it also allows users to take individual and customizable actions, such as reserving and purchasing a particular airline flight or even seat. The purpose behind an online ticketing system is straightforward: an easily usable interface that provides convenience to the user. With such a system globally available to a web terminal, the task of buying a ticket is decentralized and easy to accomplish.
HTML is a text-based markup language. Ideally, HTML is used to define the content and sketch its structure, and cascading style sheets (CSS) are used to position and style the content. Of course, due to backward compatibility and the wide range of clients used, CSS may be a less-than-optimal choice for positioning content. And beyond that, because of the static nature of HTML (meaning it is just a simple, text-based language), it is itself limited when we want to make our content change and evolve.
HTML provides an excellent means of sharing content with a variety of web-based clients, but it has several drawbacks. When an HTML document is requested from a web server, the web server returns the document to the requester-nothing more. This is just a way to publish content, not create, control, organize, or customize it. HTML as it is used today tends to focus on the content's visual quality, not its detailed structure.
Server-Side vs. Client-Side
HTML is a client-side technology, meaning that an HTML document is processed entirely by the client. A web server doesn't behave differently based on the code contained within an HTML document. A web server merely provides requested files; the client browser makes the decisions about rendering them. HTML is not a programming language; it does not provide any constructs for data processing of any kind.
PHP, conversely, is entirely server-side. When a PHP script executes, it doesn't interact directly with the browser; only the final product of the PHP script, which usually is an HTML document, is dealt with by the requesting browser. If a browser were sent an unprocessed PHP script, the browser would attempt to render the PHP script as regular HTML. Browsers cannot execute PHP scripts.
HTML is an integral component to web application development. PHP code can be embedded and mixed directly into HTML. When a client requests an HTML document from a web server, the server responds by directly sending the document to the client. Figure 1.1 shows a client requesting a HTML document and illustrates how the server responds.
Requesting a PHP script works differently. Before the document is sent to the client, the document is processed by PHP, and the PHP engine executes any PHP code found in the document. Figure 1.2 illustrates a client request for a PHP script. The PHP script in this illustration returns a processed HTML document.
Between these two processes lies the difference between PHP and HTML: PHP is executed server-side and is a full-blown programming language; HTML is merely used to publish hypertext and is handled client-side.
Whenever designing an application with a particular programming language, it is critical to understand the full capabilities and limitations of the environment being used. Web development is no different. This section shows how static HTML comes to life with PHP. This initial exploration will lay the foundations for nearly everything learned in this book. To begin the exploration of web development and the environment that is available, you will write your first PHP scripts. You will also be introduced to variables and examine some of the basics of PHP and dynamic content.
Note For a complete guide to installing and configuring PHP, see Appendix A, "A Crash Course on PHP."
Your First PHP Scripts
Before a PHP script will execute, the server must be instructed to execute it. To do so, we must enclose the script block in a special set of tags that lets the server know what is PHP code. When the server encounters a PHP open tag, everything between there and the close tag is executed as PHP. The PHP open tag is this:
and the close tag is this:
Alternatively, ... ?> can be used. The <?php opening tag is the preferred method, as this allows for PHP within XML-conformant code. Generally, either method is accepted, and it is mostly a matter of taste.
Another method will also open and close PHP script: to enable this option, the php.ini file must be modified. The configuration option asp_tags allows the use of ASP-style script blocks, using <% ... %>, to open and close a block of script. In the php.ini file, find the line with asp_tags and change it from asp_tags = Off to asp_tags = On. Using the ASP tags format is also largely a matter of taste and style.
Note The style is the most recommended and is the one we'll use throughout the book.
If you're already experienced with another programming language, especially a scripting language similar to PHP, the next few sections will be very basic review material.
What programming language book would be complete without a "Hello, World!" program? It's generally the first program learned in any language.
We'll write a minimal PHP script that generates "Hello, World!" and sends it to the browser. This script illustrates opening and closing tags and a PHP construct that generates output.
Create a document entitled hello_world.php, enter the code from Listing 1.1 into the document, save it on your web server in the document root, then navigate to the document in your browser.
* On a default Red Hat configuration, the document root can be found in /var/www/html.
* If you used Appendix A as your guide to installing PHP and Apache, then the document root will be /usr/local/apache/htdocs. The full path including the file would then be /usr/local/apache/htdocs/hello_world.php.
Tip For your convenience, copies of all of the book's demonstrated scripts are on the companion CD-ROM. You can view these files in a web browser to see their results, or open them in a text processor to follow along as we build code. The script in Listing 1.1 can be misleadingly simple in appearance. Quite a bit happens upon executing the code. Notice the common HTML entities-the html, head, title, and body tags. However, there are two special PHP entities in the document-the open tag . The web server sends everything between these tags to the PHP interpreter. PHP processes the script block and returns all generated output to the requesting client. After the PHP close tag, the document is sent as regular HTML until another PHP open tag is found.
The PHP script tells the PHP interpreter to send "Hello, World!" and a line break to the browser. The function is started with the function name, in this case print. Next, parentheses are used to mark the beginning and end of the function's argument-in this case, the string "Hello, World!\n". After the function comes a semicolon; this is required to inform PHP that the statement has ended. If the semicolon is omitted from the function call, PHP throws an error.
A string is merely a series of characters. The string passed as an argument to the function is everything between the single quotes. But the \n contained within the string is sent to the browser as one character (a special character called a newline), not two. The newline is an escaped character: a character that represents something other than its usual, literal representation. In this case, the n is "escaped" by a backslash, which means the backslash precedes the n. This backslashed, or escaped, n represents the newline ASCII character 13, not the literal characters \ and n.
To verify that the newline character was indeed sent to the browser, view the source of the document after entering the code. Listing 1.2 shows the source of the document after being parsed in PHP and sent to the client.
After examining the source, it doesn't seem to mean anything special. The PHP tags have been processed and are not sent to the client. What about the \n? What if the newline character were removed from the string? The last few lines of the document source would appear as:
We can verify this statement by removing the newline from our print function call, so that it looks like this:
Sure enough, when we remove the newline, the body tag occurs directly after the Hello, World! in source view.
Who Are You?
Now we will examine a more complicated example program. We'll write two PHP pages: One script will contain an HTML form that can be submitted; the other will be the action page, which is the script the form is submitted to. When a form submits to another page, PHP makes the data from the form available to the action page. The first PHP script will be named who_are_you.php and is a simple HTML page that contains a form. Type the code from Listing 1.3 as who_are_you.php and save to your web server.
There are several important characteristics in Listing 1.3. The script creates an ordinary HTML form, which is submitted to you_are.php (the URL in the form's action attribute).The form contains a single text input field and a Submit button. When the user clicks the button, the form is sent to the action page.
The PHP statement simply outputs the plain text that becomes an HTML text field. The print statement here is the same function used in Listing 1.1, but its result in Listing 1.3 is an input field with the type, name, and other attributes.
The value for the text input is generated by concatenating-that is, "gluing" a string together with a variable and some string literals. The PHP string-concatenation operator is a period ( . ); it tells the interpreter to take the preceding and following items and connect them into a single string.
...value="' . $person . '"...
populates the value attribute with the variable $person, which we create to store the data we're prompting the user to enter. First, the print function's argument string is ended (by the single quote mark). Then the $person variable is concatenated-that is, added to the end of the string (by the first period). After this, the rest of the string is concatenated to the newly modified string (by the second period) so that we end up with the complete text input. When the form is generated by PHP for the first time and loaded into the user's browser, the $person variable is empty, thus populating the field with an empty string. But when the user enters text and returns the form (by clicking Submit), $person carries the text entered ... as you'll see in the next section.
If you are familiar with other programming languages, you noticed that $person was never declared or initialized. Strongly typed languages require a variable to be declared and its type to be defined before the variable can be used to store data. This is not the case with PHP, as you will learn in the next chapter.
Note All PHP variable names start with the dollar sign ($).
Forms and Query Strings
Now that we have created a PHP script that generates an HTML form, we must create the action page for the form to submit to. The HTML form submits to the page you_are.php. Create a PHP script named you_are.php and enter Listing 1.4 into the script.
This listing uses print statements to generate the body of the HTML document. The string-concatenation operator ( . ) is used to assemble the argument strings for two of them. The first statement outputs a message that greets the user with the name that was entered into the $person text input on the previous page. Upon form submission, the action page makes the form fields submitted available as PHP variables. However, there are some peculiarities to be noted with the script in Listing 1.4.
Notice that within the third print statement is an anchor tag that links to who_are_you.php. Following the hyperlink takes the browser back to that page. The neat part is when the link is followed, the text input repopulates itself with the value that was entered in the initial form submission. How would a regular hyperlink populate our form field?
Excerpted from Mastering PHP 4.1 by Jeremy Allen Excerpted by permission.
All rights reserved. No part of this excerpt may be reproduced or reprinted without permission in writing from the publisher.
Excerpts are provided by Dial-A-Book Inc. solely for the personal use of visitors to this web site.
Table of Contents
Part 1: The Basics of PHP.
Chapter 1: Beginning Your Exploration of PHP.
Chapter 2: Variables.
Chapter 3: Operators and Expressions.
Chapter 4: Flow Control and Functions.
Chapter 5: Strings and Arrays.
Part 2: Programming Principles and PHP.
Chapter 6: Object-Oriented Programming.
Chapter 7: Debugging and Errors.
Part 3: Letting the Data Flow.
Chapter 8: SQL and Database Interaction.
Chapter 9: Forms and User Interaction.
Chapter 10: Data Validation.
Chapter 11: Sessions.
Chapter 12: Security.
Chapter 13: Files and Networking.
Part 4: How PHP Is Connected.
Chapter 14: Web Application Development.
Chapter 15: XML and XHTML.
Chapter 16: LDAP.
Part 5: Using PHP in the Real World.
Chapter 17: PDF.
Chapter 18: Generating Graphics.
Chapter 19: E-Mail.
Appendix A: A Crash Course on Installing PHP.
Appendix B: PHP Configuration Options.
Appendix C: XHTML Entities.