Even though there is only one image, when the user clicks somewhere on it, the accompanying form will be sent to the server with the location of where the user clicked his or her mouse o
Trang 1Even though there is only one image, when the user clicks somewhere on it, the accompanying form will be sent to the server with the location of where the user clicked his or her mouse on the picture; that is, the pixel coordinates
represented as two variables in the PHP script, image_name_x and image_name_y (image_name is the name assigned to the name attribute of the image input type; that is, toy_x and toy_y) The actual variable names sent by the browser contain a period rather than an underscore (toy.x and toy.y) but, as we discussed earlier in this chapter, PHP will automatically convert a period (or space) to an underscore because periods (and spaces) are not legal
characters in PHP variable names In the following example, after the user clicks on any of the check boxes, he or she will then click on the picture of the pizza man This causes the form to be submitted with an array of values selected from the check boxes, as well as the x/y coordinates of where the user clicked on the image button
1 <form method="post" action="image_button.php" >
Pick your pizza:<p>
<html><head><title>Finding Pixel Coordinates</title></head> <body bgcolor="8CCCCA">
<br />
<fieldset><legend><b>Pizza Choices</b></legend>
<?php
4 if ($_POST['topping']){
Trang 3Figure 10.23 PHP output after processing multiple selections
Figure 10.24 Using an image to submit a form
Trang 4Figure 10.25 After the form input has been processed, the user’s choices are listed as well as the pixel positions
of the image button (the pizza man)
10.3.10 Self-Processing HTML Forms
Rather than creating a separate HTML document to display a form and another PHP script to process the user input, you might want to combine the HTML document containing the form and the PHP script that processess it all into one script This is done by assigning the $_SERVER['PHP_SELF'] array to the action attribute of the HTML
<form> tag as shown in Example 10.15 When the user submits the form information by pressing the submit button, the action attribute of the form references the URL of the same page that displayed the form Because both the HTML form data and the PHP processing code are in the same script, you will need a conditional check in your PHP program to see if the form has been submitted For example, you can check to see if a field has a value, the submit button has been clicked, or check the request method used The following examples demonstrate how this is done
Checking If the Form Was Submitted
Example 10.15 shows the script that checks whether a form was submitted
print "<b>Your name is $your_name<br />";
print "Your phone is $your_phone<br />";
3 print "The path to this file is: "
$_SERVER['PHP_SELF']."<br />";
}
4 else{ ?>
<html><head><title>First HTML Form</title></head>
<body bgcolor="lightblue"><font size="+1">
5 <form action="<?php echo $_SERVER['PHP_SELF']; ?>"
method="POST">
Trang 5<p />
6 Please enter your name: <br />
<input type="text" size=50 name="your_name">
<p />
Please enter your phone: <br />
<input type="text" size=50 name="your_phone">
$_SERVER['SELF']
action
$_SERVER['PHP_SELF']
Trang 6Figure 10.26 The script displays the form
Figure 10.27 The same script processes the form
10.3.11 Using Hidden Fields
If your Web page contains multiple forms, you can use hidden fields to help identify what form needs to be processed
by giving each form its own name By checking the existence and value of the hidden field, you can determine which form should be displayed and when it should be processed
You can also use hidden fields to include information that can be used when processing the form but is not something that you do not care to display, such as the date the form was created, your name, and so on
Example 10.16
<html><head><title>Hidden Fields</title></head>
<body bgcolor="#ff66ff">
Trang 75 <form action="$_SERVER[PHP_SELF]" method="post">
Rate this page
<p>
<input type="submit" value="submit rating" />
<input type="reset" value="clear" />
Trang 8Explanation
process_form()
display_form()display_form()
$_SERVER['PHP_SELF']
<form>
user
EOF
Trang 9Figure 10.28 Using hidden fields to determine when to process this form Output from Example 10.16
Figure 10.29 Output based on what radio button was selected in Figure 10.28
10.3.12 Redirecting the User
What if your Web site has moved to a new location? Now when your users go to the old site, you want to redirect them
to the new one What if you want to send the user to a different page depending on some condition: Is the user logged on? Did he or she forget his or her password? What language does he or she speak? Is it a holiday?
The Location Header
Redirecting a user to another page is easy and quick with PHP It is done with the built-in header() function to modify the HTTP response header sent by the server The location header can be changed by sending an HTTP Location followed by the URL of the new location
<?php header( 'Location: http://www.mysite.com/new_page.html' ) ; ?>
The header information must be sent to the browser before any HTML and text; therefore, it is important that the header() function is executed first The following example would be wrong because the program is trying to send the echo output before the header information The warning is displayed in Figure 10.30 (See “Buffering and HTTP Headers” on page 689 if you want to move the header after other output lines.)
Trang 10Figure 10.30 The header must be sent first
After being redirected, a user’s Back button will take the user where he or she was before the redirection
page, not back to the redirection page itself
Using the Correct URI for Redirection
The Location can be assigned the absolute URI of the redirection page such as the scheme, host name, and absolute path Then the server will return a “redirect” header to the browser to retrieve the specified page directly
Location: http://marakana.com/company.html
If you want to reference another file on your own server, you can output a partial URL, such as the following:
Location: /tutorial/PHP/index.html
You can make use of PHP’s $_SERVER array variables to specify an absoute path For example, the
$_SERVER['HTTP_HOST'], the $_SERVER['PHP_SELF'], and the path of the the current script returned by the dirname() function can be concatenated together to make an absolute URL from a relative one The following PHP code defines a header described in the PHP manual:
<?php header("Location: http://" $_SERVER['HTTP_HOST'])
dirname($_SERVER['PHP_SELF']) "/my_newpage.php"); ?>
If you are redirecting a user to a new Web site, it is also a good idea to let him or her know what is happening by adding
a line such as “Our site has moved You will automatically be redirected there.”
Trang 11<b>
Select a search engine<br />
</b>
2 <select name="new_url">
<option value="http://www.google.com" />Google
<option value="http://www.yahoo.com" /> Yahoo!
<option value="http://www.lycos.com" /> Lycos
<option value="/index.php" /> PHP Index
Trang 12Figure 10.31 The HTML Web page before viewing the menu and selecting an option
Figure 10.32 The user selects “PHP Index” from the drop-down menu and presses “Get the Web Page!” to
redirect to that site
Trang 1310.3.13 Uploading Files
In an HTML form, users can upload files from a browser to a Web server The files might be text files, binary files
(such as images or compressed files), spreadsheets, or other data (see http://www.faqs.org/rfcs/rfc1867.html) Being
able to upload files is also useful if the information is easier to handle from a separate file, such as a registration form or
a résumé To upload files, you will need to create a form using the "file" type
Attributes for the <Form> Tag and the file Type
To upload files the <form> tag has three attributes:
• The action attribute of the <form> tag specifies the PHP script that will process the form
• The enctype attribute determines how the form data is encoded by the browser The default value is application/x-www-form-urlencoded, which is the default for almost any kind of form data
However, if you are going to upload files then you must specify that the data is of enctype part/form-data The browser encodes form data differently for application/x-www-form-urlencoded and multipart/form-data
multi-• The method attribute should be "POST"
4 <input type="hidden" name="MAX_FILE_SIZE" value="30000" />
5 Choose a file to upload: <input name="uploadfile" type="file"
/>
<input type="submit" value="Send File" />
</form>
In addition to the three attributes, the form’s input type is "file"; for example:
<input type="file" name="uploadfile"
With an input type of type "file", the browser might show a display of (previously selected) file names, and a
Browse button or selection method Selecting the Browse button would cause the browser to enter into a file selection
mode, allowing you to select from a list of files from different directories or folders See Figure 10.34
You can also specify the MAX_FILE_SIZE field size, the maximum number of bytes that will be accepted, but this
only advises what size the file should be This cannot be larger than upload_max_filesize defined in the
php.ini file (default 2MB) Note also that this hidden field must precede the file input field in the HTML
Files will, by default, be stored in the server’s default temporary directory, unless another location has been given with
the upload_tmp_dir directive in php.ini You can use the built-in move_uploaded_file() function to
store an uploaded file somewhere permanently (see Example 10.21)
From the php.ini file:
; File Uploads ; ;;;;;;;;;;;;;;;; ; Whether to allow HTTP file uploads
file_uploads = On ; Temporary directory for HTTP uploaded files (will use
system default if not ; specified) upload_tmp_dir = "c:/wamp/tmp" ; Maximum
allowed size for uploaded files upload_max_filesize = 2M
Trang 14PHP’s $_FILES Array
When the file is sent to the server, PHP stores all the uploaded file information in the $_FILES superglobal array (see Table 10.3), a two-dimensional array that contains the name of the file input device as the first index and one of the attributes of the file type as the second index
Table 10.3 The $_FILES Superglobal Array
Trang 15Explanation
enctype data"
Trang 16Figure 10.34 The user selects the Browse button in the form
Figure 10.35 The user then selects a file
Moving the Uploaded File
PHP provides the move_uploaded_file() function to move an uploaded file to a new location
Trang 17Format
bool move_uploaded_file ( string filename, string destination )
This function checks to ensure that the file designated by filename is a valid upload file (meaning that it was uploaded using the POST method) If the file is valid, it will be moved to the filename given as a destination
If the filename is not a valid upload file, then no action will occur, and move_uploaded_file() function will return FALSE with a warning
Browse and select the picture you want to upload: <br />
2 <input name="picture_file" type="file" />
3 $uploadFile = $directory $filename;
echo "The moved file is: $uploadFile<br />";
Trang 18<br />
<img src=<?php
echo "/exemples/formsphp/picture_uploads/$filename";?> width="250" height="175" border="3">
Trang 193 validate_input(); // Check for empty fields
4 if(count($errors) != 0){ // If there are errors,
// redisplay the form
What is your name? <br />
12 <input type="text" name="name"
value="<?php echo $_POST[name]; ?>">
Trang 20<br />
13 <?php echo $errors['name']; ?>
<br />
What is your phone number?<br />
<input type="text" name="phone"
value="<?php echo $_POST[phone]; ?>"> <br />
Trang 22Figure 10.38 The user left one field empty
Figure 10.39 The user left both fields empty
10.3.15 Where to Get Information About Superglobal Arrays
As we have seen throughout this chapter, PHP superglobal arrays (also called autoglobal), such as _GET and _POST are defined as part of the global namespace of your PHP script and used to store the user input coming from HTML forms Other superglobals, such as the server’s configuration, cookies, or information about the environment are also accessible in your PHP script in superglobal arrays These predefined arrays are referred collectively as EGPCS
(Environment, GET, POST, Cookie, and Server information) They are called superglobals because they are available in every part of your program (Cookies are discussed in Chapter 16, “Cookies and Sessions.”)
The phpinfo() Function
To see the available predefined variables on your system, you can use the phpinfo() function that includes not only all of the EGPCS information, but a huge amount of information about PHP, such as version, operating system,
environment, compilation options, server information, HTTP headers, and so on Table 10.4 lists arguments used to
Trang 23customize the output of the phpinfo() function You can use either the constant value in column 1 or the number value in column 2 Column 3 describes the output In the following example phpinfo() displays the EGPCS
predefined variables
<?php phpinfo(INFO_VARIABLES); // phpinfo(32) does the same thing ?>
Table 10.4 phpinfo() Options [a]
10.3.16 How to Get Server Information
We have been working with HTML forms and PHP, going back and forth between the server and browser PHP makes information about your server available to your scripts The Web server assigns values to the PHP superglobal
$_SERVER array such as header, path, script locations, and version information All servers are not consistent in the information they provide Table 10.5 defines some of the superglobals (from the PHP manual) you will encounter in the following chapters See Figure 10.40 for a partial output
Table 10.5 Retrieving Server Information
$_SERVER
PHP_SELF
$_SERVER['PHP_SELF']
http://example.com/test.php/foo.bar /test.php/foo.bar FILE
Trang 24Table 10.5 Retrieving Server Information
REMOTE_HOST
REMOTE_ADDRREMOTE_PORT
Trang 25Table 10.5 Retrieving Server Information
$_SERVER
SCRIPT_FILENAME
file.php /file.php $_SERVER['SCRIPT_FILENAME']