A static variable is local to the function, meaning it is not visible outside of the function, but it does not die when the function ends.. The outer function, also called the parent fun
Trang 18 foreach ( $company_records as $key=>$value){
9 foreach( $value as $field_key=>$val){
print "$field_key => $val<br />";
Shippers
mysql_fetch_assoc()
Shippers
Trang 2$company_list
foreach
foreachShippers
Figure 9.13 A function that returns an associative array Output from Example 9.10
9.1.4 Using Callback Functions
A callback function is one that is not directly invoked in the program; instead it is invoked by another function What that means is that one function takes another function, called the callback function, as its argument Callback functions are often used to perform some arbitrary task on each item in a list of items One function traverses the list, and the other provides the code to represent the task that will be performed on each item PHP provides a number of array functions that utilize “callbacks.” Some of these functions are preg_replace(), array_filter(),
array_map(), and so on (Callback functions cannot only be simple functions, but also object methods including static class methods See Chapter 17, “Objects.”)
A PHP function is simply passed by its name as a string You can pass any built-in or user-defined function with the exception of array(), echo(), empty(), eval(), exit(), isset(), list(), print(), and unset()
The array_map() Function
The following example uses PHP’s array_map() function to demonstrate the use of a callback function The array_map() function returns an array containing all the elements of the original array after applying the callback function to each element The number of parameters that the callback function accepts should match the number of arrays passed to array_map()
Trang 3Format
array array_map ( callback callback, array arr1 [, array ] )
Example:
function square($n){ // User-defined callback function return $n * $n; }
$numbers=array(1,4,6,8); $squared_list = array_map("square", "$numbers");
foreach ($before_prices as $value){
5 printf("\$%.2f ",$value);
}
echo "\n<br /><br />";
print "After map: ";
foreach ($after_prices as $value){
Trang 4Figure 9.14 A callback function Output from Example 9.11
The array_walk_recursive() Function
The array_walk_recursive() applies a user-defined callback function to every element of an array and will
recurse into nested arrays Normally the array_walk_recursive() function takes two arguments: the first one
the array being walked over, and the second one the value of the key or index of the array A third, optional argument is
an additional value that you can send to the callback function The functon returns true on success and false on failure
If your callback function needs to be working with the actual values of the array, specify the first parameter of the
callback as a reference Then, any changes made to those elements will be made in the original array itself
Trang 6Figure 9.15 Using a callback function Output from Example 9.12
Local Scope
By default, all variables declared within functions are local to the function; that is, they are not visible outside the function and die when the function exits In computer jargon, these variables are pushed onto a stack when the function starts and popped off when the function ends
4 who(); // Function call
5 print "Out of the function, your friend is $friend.<br.>"; ?>
Trang 7From within a function you cannot access variables that were declared outside the function unless you pass the variable
to the function as an argument, by reference If you need to access an external variable within a function without passing it by reference, then you can use the global statement By placing the global keyword in front of a variable name, the variable that was defined outside the function can now be accessed
Trang 8Figure 9.17 Global scope Output from Example 9.14
The $GLOBALS() Array
The other way to access a global variable within a function is with the $GLOBALS[] array It contains all the variables that have global scope in the script (i.e., any variables declared outside of functions)
Trang 92 Congratulations! Your new salary is $<?=$salary?>.<br />
The variables declared within functions normally disappear when the function ends They are local to the function
They are created when the function is called and die when it ends A static variable is local to the function, meaning it is not visible outside of the function, but it does not die when the function ends Once initialized a static variable will not lose its value between function calls It “remembers” the value it held from one call to the next
Trang 10Explanation
$counttrackme()
Figure 9.19 Static variables Output from Example 9.16
Trang 129.1.6 Nesting Functions
PHP supports nesting functions A nested function is defined and called from within another function The outer function, also called the parent function, has to be invoked for the nested function to become available to the program Nested functions are rarely used
1 function outer ($a, $b){
print "Greetings from outer()\n<br />";
2 function square($x) { // Nested function
print "Greetings from square()\n<br />";
3 return $x * $x;
}
4 return square($a) + square($b);
}
5 $sum=outer(5,8); // Call to outer()
echo "The sum of the squares is: $sum\n<br";
Trang 13Figure 9.21 Using nested functions
Figure 9.22 Output from Example 9.18
Once the outer or parent function has been executed, the nested function is defined and accessible from anywhere within the current program just like any other function You can only execute the parent function once if it contains nested functions; otherwise, PHP will generate a fatal error as shown in Figure 9.23
Example 9.19
<?php
function outer ($a, $b){
print "Greetings from outer()\n<br />";
function square($x){ // Nested function
print "Greetings from square()\n<br />";
return $x * $x;
}
return square($a) + square($b);
}
Trang 14$sum=outer(5,8);
echo "The sum of the squares is: $sum\n<br";
$sum=outer(10,2); // Wrong! Will cause square() to be redeclared
?>
Figure 9.23 Output from Example 9.19
9.1.7 Recursive Functions
A recursive function is a function that calls itself Recursive functions are often used to handle certain types of
mathematical problems; traverse directories, linked lists, and binary trees; crack passwords; create anagrams, and magic squares; and so on If a task is a smaller version of an original base task, then the problem can be solved by writing a recursive function When you first encounter recursion, it might seem a little confusing, like being in a house of mirrors When a function calls itself, the program starts up the same function again, executes the function statements, and when
it returns, picks up where it left off in the function that called it The recursion can go on indefinitely, so you must be careful to create a condition that, at some point, stops it
An example often used to describe recursion can be demonstrated with a function to produce a Fibonacci number (see Example 9.20) What is that? Well before getting started, read this little bit of history, if you have the time or interest
In the beginnning of the 13th century an Italian mathemetician, Leonardo Fibonacci, came up with a formula, called the Fibonacci sequence, to solve the following problem presented at a mathematical competition in Pisa: How many rabbits would be produced in a year if, beginning with a single pair of rabbits, every month each pair reproduces a new pair of rabbits, which become productive when they are one month old, and none of them die, and so on?
Fibonacci came up with a formula, named after himself, to answer the rabbit question The Fibonacci sequence
normally starts with 0 and 1, and then produces the next Fibonacci number by adding the two previous Fibonacci numbers together: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597, 2584, 4181, 6765, 10946 Thus, to get the next value after 21, add 13 to 21 resulting in the next Fibonacci number, which is 34 So the number of pairs of rabbits at the start of each month is 1, 1, 2, 3, 5, 8, 13, 21, 34, and so on
Trang 16call 1 fib(4) 3 Returns 3 call 2 fib(3) + call 7 fib(2) 2 + 1 Returns 3 call 8 fib(1) + call 9 fib(0) 1 + 0 Returns 1 call 3 fib(2) + call 6 fib(1) 1 + + Returns 2 call 4 fib(1) + call 5 fib(0) 1 + 0 Returns 1
for
fib()
fib()fib()
fib()
Figure 9.24 Recursive function Output from Example 9.20
9.1.8 Function Libraries—Requiring and Including
If you have a function or set of functions that you will reuse in other PHP programs, then you can save the functions in
a file, called a library When you are ready to use the functions, just include the library in the current script with the include() or require() built-in functions Suppose, for example, you have two functions: one called total()
to calculate the total of a set of numbers, and another called ave() to calculate the average of a set of numbers We will store these user-defined functions in a library file called mylibrary.php shown in Figure 9.25:
Trang 17Figure 9.25 The library file
The require() and include() Constructs
PHP provides the require() and include() constructs to allow you to use the functions from the library file in a PHP script as shown here:
-<?php
include("mylibrary.php");
echo "The average is ", ave(array(11,3,5,7,34));
?>
The include() and require() constructs cause a specified file to be included and evaluated in your script, similar
to pasting the contents of a file in your script at the line where they were requested When you place a function within
an external file that will later be included, be sure to enclose the function within PHP tags, because, when a file is included, if the PHP tags are missing, PHP automatically starts processing the included file as an HTML document The only difference between include() and require() is how they deal with failure The include() produces
a warning and allows the script to continue executing while require() produces a fatal error For PHP to find the file you want to include, it searches an include_path defined in the php.ini file[1], and if the file is not in the path, this would cause an error (Files for including are first looked for in the include_path relative to the current
working directory and then in the include_path relative to the directory of current script If a filename begins with / or /, it is looked for only in include_path relative to the current working directory.)
[1] To change include_path from your program, use the built-in ini_set function described in the PHP manual: http://www.php.net/manual/en/function.ini-set.php
With require() the missing file would cause the script to exit, whereas with include(), the program will
continue to run You can also use an absolute path such as require('C:\pub\library\file.php') or include('/usr/htdocs/file.php')
Just like require() and include(), the require_once() and include_once() statements, respectively, include and evaluate the specified file during the execution of the script, but require_once() and
include_once() will only include a file once, even if you have more require or include statements
throughout the script
Trang 18Include files are often used to help manage the content of a Web site The files are external to the program and included
as needed For a discussion on content management, see “Managing Content with Include Files” on page 487
echo "Welcome to you!\n<br />";
11 echo "<font color=$color>"."What a $mood $color
welcome()
$color "purple"
Trang 209.2 Chapter Summary
9.2.1 What You Should Know
Now that you have finished this chapter you should be able to answer the following questions:
Chapter 9 Lab
1
Trang 21upper lower title
print converter("title", $string);
Output should look similar to the following:
3
P= L[c(1 + c)] n/ [(1 + c) n– 1]
Trang 22Chapter 10 More on PHP Forms
10.1 Introduction
We discussed forms briefly in Chapter 3, “PHP Quick Start,” and now we are ready to delve into a more thorough discussion about how PHP handles form information The first part of this chapter is a review of how to set up HTML forms, the HTTP (HyperText Transmission Protocol) methods, and how form information is transmitted from the browser to the server and back If you browse through the following HTML review section and feel comfortable with the information provided there, then you might want to skip this section and go directly to “PHP and Forms” on page
390
10.2 Review of HTML Forms
Forms are essential to any Web page that communicates with users When you order a book or a pillow, register for a course, sign up for a cruise, pay bills online, get directions to a street address, you fill out a form Once you have filled out the form, you push an Order now! or Submit type button, and the form is submitted The information you entered is collected by the browser, URL encoded, and sent to a server The server might then send the encoded information to a program for processing Traditionally the server would start up a CGI program to process the information, but PHP makes this processing much easier PHP will decode and process the information according to the instructions in the PHP program that gets it It might send an e-mail back to the user, store or update the information in a database, save preferences in a cookie, session, and so on
Working with forms is a two-step process:
10.2.1 The Browser’s Role
HTML forms are created in a text file and displayed in a browser window They consist of fields or buttons that request user interaction (see Figure 10.1) After the user fills out the form, the form data is URL encoded[1] by the browser and submitted to a server for further processing Example 10.1 shows a really simple HTML form consisting of two input fields, a text box, and a submit button Figures 10.2 and 10.3 are screen shots of the form before and after it is filled out
[1] For a complete discussion on URL encoding, see Chapter 9, “User-Defined Functions,” or go to
http://www.blooberry.com/indexdot/html/topics/urlencoding.htm
Figure 10.1 Working with HTML forms
Trang 23Example 10.1
<html><title><Simple Form></title>
<body>
<form>
What is your name?
<input type=text name="myname"><br />
<input type=submit>
</form>
</body>
</html>
Figure 10.2 A simple HTML form
Figure 10.3 The user fills out the form
There are different ways of sending this data to the server called HTTP request methods (HTTP is the standard way of sending documents over the Web.[2]) The GET and POST methods are the two most common request types Essentially these methods perform the same function but how they handle the input data is different
[2] To learn more about HTTP, go to http://www.w3.org/Protocols/rfc2616/rfc2616-sec1.html#sec1
The GET Method
If the processing of a form has no lasting observable effect on the state of the world, then the form method should be GET[3] (i.e., it handles requests where the response page will never change) The GET method is the simplest type of method and is used mainly for the simple retrieval of static HTML documents, images, or results of a database query as shown in the URL of Google’s search engine in Figure 10.4
[3] Quoted from http://www.cs.tut.fi/~jkorpela/forms/methods.html#fund
Trang 24Figure 10.4 URL using the GET method The query string is encoded, visible, and can be bookmarked
If a method is not supplied as an attribute of the <form> tag, the GET method is the default The GET method sends submitted data to the server by attaching it to the end of the URL in what is called the query string After the user presses the submit button, the browser encodes the content, and appends it to the current URL as a set of key–value pairs (prepended with a question mark) The key is the name given to the input device, and the value (URL encoded) is whatever the user typed in that field In the URL shown next, the form information has been highlighted; that is, the string appended to the question mark The name of the text field is “myname” and the value typed into the field by the user is “Joe H Shmoe” The browser, Mozilla Firefox in this example, encoded the spaces in Joe’s name with + signs See Figure 10.5
Figure 10.5 The GET method and the URL
http://localhost/exemples/ch4variables/form_simple.html?myname=Joe+H.+Shmoe
Disadvantages of the GET method are that all the form data is sent via the URL, which is visible to the user and limited
in size Servers often have size limitations on the length of the URL For example, UNIX servers limit the size to 1240 bytes If a lot of information is being passed to the server, the POST method should be used Another disadvantage is that the input data might be cached, and the browser might pull previous request results from its cache instead of the most recent one
The POST Method
The POST method is used if the processing of a form causes side effects, like the modification of a database, updating a shopping cart, or sending an e-mail message When the POST method is used, the browser does not put the encoded data in a query string, but rather bundles up the data and puts it into an HTTP header message body Unlike the query string created by the GET method, the message body does not have size restrictions, is not visible in the Location box of the browser, and cannot be bookmarked Because the POST method does not append input to the URL, it is often used
in processing forms where there is a lot of data being transferred and will send data to a database, send e-mail, or change something The form data is URL encoded but not limited in size as it was with the GET method It cannot be bookmarked and is not visible in the URL
The POST is invoked by adding a METHOD attribute to the <FORM> tag in your HTML document as shown in Example 10.2 The variables sent are sorted and available to the PHP script in the same way as with GET, but the query string is not set The form is shown in the browser in Figure 10.6
Example 10.2
<html><title><Simple Form></title>
<body>
<form METHOD="POST">
What is your name?
<input type=text name="myname"><br />
<input type=submit>
</form>
</body>
</html>
Trang 25Figure 10.6 A simple HTML form created using the POST method Output from Example 10.2
10.2.2 The Server’s Role
When the browser requests a Web page from the server, it establishes a TCP/IP connection and sends a request in an HTTP format The server examines the request and responds The first line of the HTTP request might look like this: GET /file.php HTTP/1.1
This line specifies that the method to handle the incoming data is GET, that the file to retrieve is file.php, and that the version of HTTP is 1.1 PHP runs as part of the server and has access to the form data passed from the browser to the server After the server gets the file, it sends it to PHP to be processed PHP knows how the form was sent and provides special variables to hold both GET and POST data as well as variables containing information about the environment, such as server, browser, and so on PHP automatically converts the names of the form elements into PHP variables and executes any PHP statements, substituting the output within the HTML document (discussed in Chapter 9,
“User-Defined Functions”) After PHP has finished handling the form data, the server will send back a response header and send the processed information back to the browser
A server response looks like this:
HTTP/1.1 200 OK Content-type: text/html <Contents of HTML Document>
When the browser receives the page, it renders the HTML code and then displays the page in the browser
10.2.3 Creating HTML Forms
Before getting PHP to process the form, you might need a short refresher course on how to create forms, the types of forms, how the information is passed from the browser to the server, and so on This section reviews basic HTML form creation To create an HTML form, you start in an editor with a filename ending in html or htm A form starts with a
<form> tag and its attributes, followed by the input devices you will need, such as text fields, buttons, check boxes, and so on, a submission button, and ends with the closing </form> tag.[4] (The HTML file is normally stored under the server’s root in a directory called htdocs.) Let’s start by displaying an HTML form that contains text fields, radio buttons, check boxes, and pop-up menus (see Figure 10.7) After displaying the form, we look at the HTML code that produced it in Example 10.3
[4] For a complete introduction to forms, see http://www.w3.org/TR/REC-html40/interact/forms.html#h-17.2