You can conditionally include files, specify which file to include dynamically, or even nest include function calls within included pages.. The include path is a list of directories gene
Trang 1<title>Registration Form</title>
<style type=”text/css”>
label.error {
color: red;
}
</style>
</head>
<body>
<h1>Registration Form</h1>
<p>Please fill out the form below to register for our site Fields
with bold labels are required.</p>
<?php if (!empty($errors)) { ?>
<ul>
<?php foreach (array_values($errors) as $error) { ?>
<li><?= $error ?></li>
<?php } ?>
</ul>
<?php } ?>
<form method=”post” action=”<?= $_SERVER[‘PHP_SELF’] ?>”>
<p>
<?php if (array_key_exists(‘name’, $errors)) { ?>
<label for=”name” class=”error”><b>Name:</b></label>
<?php } else { ?>
<label for=”name”><b>Name:</b></label>
<?php } ?>
<br />
<input name=”name” value=”<?= strip_tags($_POST[‘name’]) ?>” /></p>
<p>
<?php if (array_key_exists(‘age’, $errors)) { ?>
<label for=”age” class=”error”><b>Age:</b></label>
<?php } else { ?>
<label for=”age”><b>Age:</b></label>
<?php } ?>
<br />
<input name=”age” value=”<?= strip_tags($_POST[‘age’]) ?>”/></p>
<p>
<?php if (array_key_exists(‘toys’, $errors)) { ?>
<label class=”error”><b>Toys:</b></label>
<?php } else { ?>
<label><b>Toys:</b></label>
<?php } ?>
<br />
<?php foreach ($toys as $key => $value) { ?>
<label><input type=”checkbox” name=”toys[]”
<?php if (array_key_exists(‘toys’, $_POST) && in_array($key,
Trang 2$_POST[‘toys’])) { echo ‘checked=”checked” ‘; } ?>
value=”<?= $key ?>” /> <?= $value ?></label><br />
<?php } ?>
</p>
<p><input type=”submit” value=”register” /></p>
</form>
</body>
</html>
21
Output
FIGURE 21.2
A form with some
errors that were
caught during
vali-dation.
▲
Using PHP Includes
PHP and all other server-side scripting languages provide the ability to include snippets
of code or markup in pages With PHP, the ability to include files is built into the
lan-guage Because the include statements are part of the language, you don’t need to include
parentheses around the name of the file to be included You can conditionally include
files, specify which file to include dynamically, or even nest include function calls within
included pages Here’s a simple example of an include call:
include “header.php”;
On encountering that function call, PHP will try to read in and process a file named
header.phpin the same directory as the current page If it can’t find this file, it will try
to find the file in each of the directories in its include path, too The include path is a list
of directories (generally specified by the server administrator) where PHP searches for
files to include, and it’s generally set for the entire server in a configuration file
Trang 3Four include-related functions are built in to PHP: require,require_once,include, and
include_once All these functions include an external file in the page being processed
The difference between includeandrequireis how PHP reacts when the file being
included isn’t available If includeorinclude_onceis used, the PHP page prints a
warning and continues on If requireorrequire_onceis used, an unavailable include
file is treated as a fatal error and page processing stops
If you use require_onceorinclude_onceto include a file that was already included on
the page, the function call will be ignored If you use requireorinclude, the file will
be included no matter what
PHP includes are like HTML links in that you can use relative or absolute paths in your
includes The difference is that absolute PHP paths start at the root of file system rather
than the web server’s document root So if you want to include a file using an absolute
path on a computer running Windows, you write the include like this:
require_once ‘c:\stuff\myfile.php’;
That’s almost never a good idea You should always use relative paths where possible In
other words, if the included file is in the directory above the one where the including file
is located, you should use a path like this:
require_once “ /myinclude.php”;
If the file being included is not stored with your other web documents, try to have that
directory added to your server’s include path rather than using absolute paths to access it
Never pass data entered by a user to any include function; it’s a big security risk For example, this would be inappropriate:
require_once $_POST[‘file_to_include’;
PHP includes can be useful even if you don’t plan on doing any programming in PHP
You can turn parts of your website that you use frequently into files to be included,
sav-ing you from havsav-ing to edit the same content in multiple places when you’re worksav-ing on
your site Using PHP includes this way can provide the same advantages that putting
your CSS and JavaScript into external files does For example, you might create a file
calledheader.phpthat looks like this:
<!DOCTYPE html>
<html>
<head>
<title><?= $title ?></title>
<script src=”site.js”></script>
CAUTION
Trang 4<link rel=”stylesheet” href=”site.css”>
</head>
<body>
This file includes all the tags for the start of my page, including links to external
JavaScript and CSS files There’s a PHP short tag in the title that prints out the value of
the$titlevariable That enables you to use the header file for all of your pages and to
specify individual titles for each of them To include this file, you use the following
code:
<?php
$title = “Welcome!”;
include “header.php”;
?>
Choosing Which Include Function to Use
Given these four very similar functions, how do you choose which makes the most sense
to use? The most important factor in making that decision is the content of the file to be
included Generally, there are two types of include files: snippets of markup that will be
presented on your page, and PHP code libraries that provide code you are using on
mul-tiple pages throughout a site
If the file you are including is a library, you just about always want to use require_once
If you’re using code from the library on a page, chances are the page will not work if the
library file is not available, meaning that you should use requirerather than include If
the file contains library code, you’re not going to want to include it more than once Let’s
look at an example You’ve written a library called temperature_converter.php The
contents of the file are shown here:
<?php
function celsiusToFahrenheit($temp = 0) {
return round(($temp * 9/5) + 32);
}
?>
This file contains one function, celsiusToFahrenheit(), which converts a Celsius
tem-perature to Fahrenheit and then rounds the result so that the function returns an integer
Now let’s look at a page that includes this file:
<?php
require_once “temperature_converter.php”;
?>
<html>
<head>
21
Trang 5<title>Current Temperature</title>
</head>
<body>
<p>Current temperature in Fahrenheit: <?= celsiusToFahrenheit(55) ?></p>
</body>
</html>
As you can see, in this case the page won’t have any meaning if the function in the
library page is not available, so using requiremakes sense On this page, it wouldn’t
matter whether I used requireorrequire_oncebecause there are no other includes
Suppose that the page included another file, one that prints the current temperatures
around the world If that page also had a require()call for
temperature_converter.php, the same code would be included twice An error would
cause the page to fail, because each function name can only be declared once Using
require_onceensures that your library code is available and that it is not accidentally
included in your page multiple times
On the other hand, if you’re including content that will be displayed within your page,
thenincludeorrequiremake more sense You don’t have to worry about conflicts, and
if you’re including something to be displayed on the page, chances are you want it to
appear, even if you’ve already included the same thing
Expanding Your Knowledge of PHP
PHP is a full-featured scripting language for creating web applications and even writing
command-line scripts What you’ve seen in this lesson is just a brief introduction to the
language There are more statements, lots more built-in functions, and plenty of other
things about the application for which there isn’t space to discuss in this lesson
Fortunately, an online version of the PHP manual is available that will fill in most of the
blanks for you You can find it at http://www.php.net/docs.php
Also, shelves of books about PHP are available to you Some that you might want to
look into are Sams Teach Yourself PHP, MySQL, and Apache All in One (ISBN
067232976X), and PHP and MySQL Web Development (ISBN 0672317842).
There’s more to PHP than just the core language, too Lots of libraries have been written
by users to take care of common programming tasks that you might run into There’s an
online repository for these libraries called PEAR, which stands for PHP Extension and
Application Repository You can find it at http://pear.php.net/
Trang 6For example, the eBay website provides an API (application programming interface) that
you can use to integrate your own website with eBay You could write the code to use
this API yourself, but a library in PEAR already exists You can find it at
http://pear.php.net/package/Services_Ebay
This is just one of the many libraries you can obtain via PEAR When you’re writing
your applications, make sure to check the PHP manual to ensure there’s not already a
built-in function to take care of whatever you’re doing If there isn’t, check PEAR
As I said before, I left out huge swaths of PHP functionality in this lesson for the sake of
space Here are some areas that you’ll want to look into before developing your own
PHP applications
Database Connectivity
I mentioned CRUD applications already A CRUD application is generally just a front
end for a relational database, which in turn is an application optimized for storing data
within tables Databases can be used to store content for websites, billing information for
an online store, payroll for a company, or anything else that can be expressed as a table
It seems like there’s a relational database providing the storage for just about every
popu-lar website
Because databases play such a huge role in developing web applications, PHP provides a
lot of database-related functionality Most relational databases are applications that can
be accessed over a network, a lot like a web server PHP is capable of connecting to
every popular relational database To communicate with relational databases, you have to
use a language called SQL (the Structured Query Language) That’s another book unto
itself
Regular Expressions
Regular expressions comprise a small language designed to provide programmers with a
flexible way to match patterns in strings For example, the regular expression ^a.*z$
matches a string that starts with a, ends with z, and has some number of characters in
between You can use regular expressions to do much more fine-grained form validation
than I did in Exercise 21.1 They’re also used to extract information from files, search
and replace within strings, parse email addresses, or anything else that requires you to
solve a problem with pattern matching Regular expressions are incredibly flexible, but
the syntax can be a bit complex
PHP actually supports two different varieties of regular expression syntax: Perl style and
POSIX style You can read about both of them in the PHP manual
21
Trang 7Sending Mail
PHP provides functions for sending email For example, you could write a PHP script
that automatically notifies an administrator by email when a user registers for a website,
or sends users a password reminder if they request one when they forget their password
PHP also provides functions that enable your applications to retrieve mail as well as send
it, making it possible to write web-based email clients and other such applications
Object-Oriented PHP
PHP provides features for object-oriented development if you prefer that style of
pro-gramming For more information on object-oriented PHP, refer to the manual
Cookies and Sessions
Cookies are a browser feature that lets websites set values that are stored by your
browser and returned to the server any time you request a page For example, when users
log in to your site, you can set a cookie on their computers to keep track of who they
are so that you don’t have to force them to log in any time they want to see a
password-protected page You can also use cookies to keep track of when visitors return to your
site after their initial visit PHP provides full support for cookies It also provides a
facil-ity called sessions Sessions enable you to store data between requests to the server For
example, you could read a user’s profile into her session when that user logs into the site,
and then reference it on every page without going back and loading it all over again
Generally, cookies are used with sessions so that the server can keep track of which
session is associated with a particular user
File Uploads
In Lesson 11, “Designing Forms,” you learned about file upload fields for forms PHP
can deal with file uploads, enabling the programmer to access and manipulate them
With PHP, file uploads are stored to a temporary location on the server, and it’s up to the
programmer to decide whether to store them permanently and, if so, where to put them
Other Application Platforms
PHP is just one of many programming languages that people use to write web
applica-tions It is the language used to create popular web applications like Drupal, WordPress,
and Expression Engine It’s also the tool used by major web companies like Facebook and
Yahoo! However, other options are available If you’re just diving into web programming,
PHP is probably a good choice, but you might find yourself working on applications
written in another language Here’s a brief overview of the languages you may encounter
Trang 8Microsoft ASP.NET
Microsoft provides the ASP.NET environment for writing web applications that run on
Windows servers ASP.NET is similar to PHP in that it supports embedding server-side
code in HTML pages It supports Visual Basic and C# as programming languages and
runs on Microsoft’s Internet Information Server, which is included with Windows Server
You can read more about ASP.NET and download free tools for developing and running
ASP.NET applications at http://www.asp.net/
Java EE
Java is a programming language originally created by Sun that runs on many operating
systems, including Windows, OS X, and Linux EE stands for Enterprise Edition, an
umbrella under which the server-side Java technologies live Java is widely used by large
companies to build internal and external applications
There are two ways to write web applications in Java—servlets, which are programs that
run on the server and can produce web content as output; and Java Server Pages, which
allow you to embed Java code in HTML pages so that it can be executed on the server
You can read more about it at http://java.sun.com/javaee/
Ruby on Rails
Ruby on Rails is a newer application platform that is gaining popularity because it
enables developers to get a lot done with just a few lines of code It uses the Ruby
pro-gramming language and is designed with the philosophy that applications can be written
quite efficiently if developers adhere to the conventions that the creators of the Ruby on
Rails framework built in to it You can read more about it at http://rubyonrails.org
Summary
This lesson provided a whirlwind tour of the PHP language, and it explained how
server-side scripts are written in general Although the syntax of other languages will differ
from PHP, the basic principles for dealing with user input, processing forms, and
embed-ding scripts in your pages will be quite similar I also listed some other application
plat-forms you might encounter They are all similar to PHP in function, even though the
syntax of the languages they use differ from PHP to varying degrees
In the next lesson, you learn how to take advantage of applications that other people have
written rather than writing them yourself Just as PHP has lots of built-in functions to
take care of common tasks, so too are there many popular applications that you can
download and install rather than writing them from scratch yourself
21
Trang 9Workshop
The following workshop includes questions you might ask about server-side
develop-ment, quizzes to test your knowledge, and three quick exercises
Q&A
Q At work, all of our applications are written using Active Server Pages Why
didn’t you write about that?
A There are a number of popular platforms for writing web applications PHP has the
advantage of running on a number of operating systems, including Windows, Mac
OS X, and Linux Furthermore, support for PHP is offered by many web hosting
providers Finally, as you’ll learn in the next lesson, there are many applications
already written in PHP that you can take advantage of Knowledge of PHP can be
helpful in working with them
Q Do I need a special application to edit PHP files?
A Just as with HTML, PHP files are normal text documents Some text editors have
specialized features that make working with PHP easier, just as there are for
HTML If you’re just starting out, using Notepad or any other regular text editor
will work fine, but you’ll probably want to find a more powerful tool for writing
PHP if you find yourself programming in PHP a lot
Q How do I deploy PHP files to a server?
A There are no special requirements for deploying PHP files You can just transfer
them to the server as you would regular HTML files As long as the server is
con-figured to handle PHP, you should be fine The one thing you do need to be careful
to do is to make sure your directory structure is the same on the server and on your
local computer If you are using includes and directory paths change, your includes
will break
Q Are PHP scripts browser dependent in any way?
A All the processing in PHP scripts takes place on the server They can be used to
produce HTML or JavaScript that won’t work with your browser, but there’s
noth-ing in PHP that will prevent it from worknoth-ing with a browser
Quiz
1 What is the difference between double and single quotes in PHP?
2 How do the include_once andrequire_oncefunctions differ?
3 Which functions can be used to help avoid cross-site scripting attacks?
4 How do you declare an associative array in PHP?
Trang 10Quiz Answers
1 In PHP, strings in double quotes are parsed for variable references and special
characters before they are presented Strings in single quotes are presented as is
2 Theinclude_oncefunction does not return a fatal error if the file being included is
not found With require_once, if the file is not found, a fatal error occurs and the
rest of the page is not processed
3 You can use htmlspecialchars()to escape the characters used to generate HTML
tags for a page You can use strip_tags()to remove any HTML tags from a
string Either approach should prevent users from using malicious input to attempt
a cross-site scripting attack
4 Associative arrays are declared as follows:
$array = (‘key’ => ‘value, ‘key2’ => ‘value2’);
Exercises
1 Get PHP up and running on your own computer
2 Write a script that enables a user to show the current date and time on a web page
3 Go to the PHP manual online and find a built-in function that wasn’t introduced in
this lesson Use it in a script of your own
21