Tài liệu PHP and MySQL by Example- P9 pptx

50 454 0
Tài liệu PHP and MySQL by Example- P9 pptx

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

Thông tin tài liệu

& 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 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. Example 10.14. Code&View:& (The HTML File) <html> <head><title>Image Button</title> </head> <body bgColor="#CCFF33"> <font face="verdana"><b> 1 <form method="post" action="image_button.php" > Pick your pizza:<p> 2 <input type="checkbox" name="topping[]" value="tomatoes" />Tomato and Cheese<br /> <input type="checkbox" name="topping[]" value="salami" />Salami<br /> <input type=checkbox name="topping[]" value="pineapple" />Pineapple and Ham<br /> <input type=checkbox name="topping[]" value="Canadian bacon" />Canadian bacon<br /> <input type=checkbox name="topping[]" value="extra cheese" />Plain Cheese<br /> <p><font size="-1"> Press the pizza man to order! <br /> 3 <input type="image" name="pizzas" src="Pizza_chef.jpg" /> <br /><br /> <input type=reset value="Clear the form" /> </form> </body> </html> (The PHP Script) <html><head><title>Finding Pixel Coordinates</title></head> <body bgcolor="8CCCCA"> <br /> <fieldset><legend><b>Pizza Choices</b></legend> <?php 4 if ($_POST['topping']){ Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. print "<ul>"; 5 foreach ( $_POST['topping'] as $value ){ print "<li>$value</li>"; } print "</ul>"; } print "The pixel coordinates of the image are: <br />"; 6 $coord1 = $_POST['pizzas_x']; $coord2 = $_POST['pizzas_y']; print "$coord1, $coord2<br />"; ?> </fieldset> </body> </html> Explanation 1 The&form,&shown&in&Figure&10.23,&is&being&submitted&to&a&PHP&script&using&the& POST&method. 2 The&form&consists&of&a&set&of&check&boxes&that&will&be&passed&to&PHP&as&an&array& called&"topping". 3 Here&is&where&we&create&the&image&button&to&be&used&to&submit&the&form.&It&is& given&a&name&of&"pizzas"&and&the&image&src&is&"Pizza_chef.jpg"&located&in& the&current&working&directory&or&folder.&When&the&user&clicks&on&this&picture,& the&form&will&be&submitted. 4 If&the&user&has&posted&the&form,&there&will&be&a&value&in&the&$_POST&array,&the& expression&will&test&true,&and&the&block&will&be&entered. 5 For&each&of&the&toppings&in&the&$_POST&array,&the&values&will&be&printed.&See& Figure&10.24. 6 The&x/y&coordinates&represent&the&place&in&the&image&(pixel&position)&where& the&user&clicked&his&or&her&mouse&button.&To&check&whether&or&not&the&form& was&submitted,&you&can&test&if&these&variables&are&not&empty&with&the&empty()& function:&if ( ! empty($coord1 ) & Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. Figure 10.23. PHP output after processing multiple selections. & Figure 10.24. Using an image to submit a form. & Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. Figure 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. Example 10.15. Code&View:& <?php 1 if ( isset($_POST['submit'])){ // Was the form submitted? 2 $your_name=$_POST[your_name]; $your_phone=$_POST[your_phone]; 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"> Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. <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"> <p /> <input type="submit" name="submit" value="Send Now"> <input type=reset value="Clear"> </form> <hr> </html> <?php } ?> Explanation 1 The&PHP&isset()&function&checks&to&see&if&the&form&has&been&submitted&using& the&POST&method.&If&it&has,&the&program&continues&at&line&2;&if&not,&then&program& control&goes&to&line&4,&and&the&form&will&be&displayed&in&the&browser. 2 Because&the&form&has&already&been&submitted,&the&values&that&were&entered& into&the&fields&can&be&displayed&as&variables.&See&Figure&10.27. 3 The&superglobal&$_SERVER['SELF']&array&contains&information&about&the&path& where&this&script&is&found&starting&at&the&document&root&of&the&server,&not&the& root&of&the&file&system. 4 If&the&form&has&not&been&submitted,&the&script&jumps&into&this&block&where&we& switch&from&PHP&into&the&HTML&mode&to&produce&the&form.&See&Figure&10.26. 5 The&action&attribute&is&assigned&the&address&of&the&current&script.&The& program&temporarily&switches&back&into&PHP&mode&to&get&the&path&of&the&script& from&the&$_SERVER['PHP_SELF']&variable.&When&the&user&presses&the&submit& button,&this&same&script&will&be&reexecuted,&this&time&to&process&the&form&data. 6 The&user&is&presented&with&two&text&boxes,&as&shown&in&Figure&10.26. Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. Figure 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. Code&View:& <html><head><title>Hidden Fields</title></head> <body bgcolor="#ff66ff"> Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. <font face="verdana"> <div align="center"> <b> <?php 1 if (isset($_POST['feedback1']) && ($_POST['feedback1'] == 'process_form1')){ process_form1(); } 2 else{ display_form1(); } 3 function display_form1(){ 4 echo <<<EOF 5 <form action="$_SERVER[PHP_SELF]" method="post"> Rate this page <br /><b /r> <input type="radio" name="rating" value="excellent" />Really kewl <input type="radio" name="rating" value="average" />OK <input type="radio" name="rating" value="poor" />Boring <input type="radio" name="rating" value="hopeless" />Totally hopeless 6 <input type="hidden" name="feedback1" value="process_form1"> 7 <input type="hidden" name="creation_date" value="Feb. 2006" /> <p> <input type="submit" value="submit rating" /> <input type="reset" value="clear" /> </form> 8 EOF; } 9 function process_form1(){ echo "So you think this page is $_POST[rating]!"; } ?> </b> </div> </body> </html> & & & Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. Explanation 1 The&isset()&function&will&check&to&see&if&the&variable&$_POST['feedback1']& has&been&set&and&if&it&contains&the&value&assigned&to&the&hidden&field.&If&both& conditions&are&true,&then&the&form&has&already&been&displayed&on&the&browser& and&sent&back&to&this&PHP&script.&Because&the&page&has&already&been&displayed& and&submitted,&it&is&now&time&to&process&the&form.&The&userYdefined&function,& process_form(),&is&called. 2 If&the&test&on&line&1&fails,&then&the&form&has&not&been&previously&displayed.&The& userYdefined&function,&display_form(),&is&called. 3 The&function&display_form()&will&be&responsible&for&creating&the&form&and& displaying&it&in&the&browser. 4 This&is&the&start&of&a&hereYdoc&used&to&print&out&the&HTML&form&and&interpolate& any&variables.&Remember&that&when&in&a&hereYdoc&you&are&essentially&in&a& quoted&block&of&text.&Adding&additional&quotes&to&the&array&elements&will& produce&an&error. 5 The&$_SERVER['PHP_SELF']&is&a&reference&to&the&current&script.&When&the&user& presses&the&submit&button,&the&action&is&specified&to&call&this&same&script&again. 6 The&hidden&field&is&set&as&an&input&type&of&the&<form>&tag.&Although&it&will&not& be&visible&when&the&form&is&displayed,&its&name&and&value&will&be&sent&to&the& PHP&script,&along&with&the&name&and&value&of&the&radio&button&selected&by&the& user. 7 The&hidden&field&is&assigned&the&month&and&year&when&this&form&was&created.& No&one&needs&to&see&this&information,&except&maybe&you&if&you&are&trying&to& keep&track&of&the&development&of&this&page. 8 The&userYdefined&terminator,&EOF,&for&marking&the&end&of&the&hereYdoc,&cannot& have&spaces&on&either&side;&that&is,&it&must&be&butted&up&against&the&left&margin,& immediately&followed&by&a&newline. 9 After&the&user&has&filled&out&the&form,&this&function&processes&the&input& received&from&the&server. Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. Figure 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.) Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. Figure 10.30. The header must be sent first. & Example 10.17. <?php echo "You are going to be redirected to a new page!<br />"; // Wrong! header("Location: /www/ellieq.com"); ?> Explanation 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.” Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. [...]... 64 PHP  License  information  See  also  the  license  FAQ INFO_ALL –1 Shows  all  of  the  above  This  is  the  default  value   [a] From http://us2 .php. net/phpinfo For a complete list and definitions see http://us3 .php. net/manual/en/reserved.variables .php 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. .. What  is  meant by  a  “sticky”  form?   16 How  can  you  get  information  about  your  server  from PHP?   10.4.2 What’s Next? Much of what you do in PHP will deal with files In Chapter 11, “Files and Directories,” we talk about files and how to open and close them, read from them and write to them, copy them, lock them, upload them, compress them, and more, all from within a PHP script Chapter... files and directories can be done at the command line or from within a PHP script We start with the chmod command at the command line (Keep in mind that if the PHP script is being executed by the server, the permissions are limited to what a server can do, whereas if you are running the script at the command line, the program, permissions will apply to what you, the user, can do Because ownership and. .. command line with the attrib command     11.2 The Web Server, PHP, and Permissions Like all processes running in a UNIX environment, PHP programs run on behalf of a particular user If you run a PHP script from the command line (for instance, as a shell script), it will run with the permissions set for you, the user, who started the script More typically, however, PHP scripts will be executed by your... thing ?>   Table 10.4 phpinfo() Options[a] Name  (Constant) Value Description INFO_GENERAL 1 The  configuration  line, php. ini  location,  build  date,  Web   server,  system, and  more INFO_CREDITS 2 PHP  credits  See  also  phpcredits() INFO_CONFIGURATION 4 Current  local and  master  values  for PHP  directives  See  also   ini_get() INFO_MODULES 8 Loaded  modules and  their  respective... group is assigned 5, and the others are assigned 5, the combined value is 755 Table 11.2 displays the numeric values that will represent each class of users By adding the values for the owner, group, and others, the resulting number is the permission mode Read is represented by 4, write by 2, execute by 1, and none of the permissions is 0 If you want the user to have read, write, and execute, add up... attribute to specify that a file is executable DOS and Windows NT file systems identify executable files by giving them the extensions exe, com, cmd, or bat You can also display and change the attributes of a file from the command line with the DOS attrib command by going to the Start menu and clicking Run In the cmd.exe window type the following and you will see a window similar to that shown in Figure... by you and the group to which you belong You can change the owner of a file with the chown command; that is, if you own it or you are root, the superuser (Check your version of UNIX/Linux) Changing the group to which a file belongs is done with the chgrp command PHP provides built-in functions of the same name as the UNIX/Linux commands allowing you to mimic these operating system commands from a PHP. .. password by comparing it to the password initially created by md5(): $password=md5($password);   Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark Chapter 11 Files and Directories 11.1 Files After the browser sends data to the server and PHP processes the information, a database management system such as MySQL or Oracle will normally store or retrieve the data But PHP might... myfolder 2 $ chmod 777 * 3 $ chmod 644 filex Explanation 1 Grant  read,  write, and  execute  to  the  owner,  read and  execute  to  the  group and   the  others  (world) 2 Set  all  to  read,  write, and  execute  on  all  files and  in  the  current  working   directory 3 User  gets  read and  write,  group and  others  get  read 11.1.3 Windows Permissions Originally, DOS was not intended . (The PHP Script upload_file .php) < ?php 6 $handle=fopen($_FILES['user_file']['tmp_name'], "r"); 7 while(!feof($handle)){. 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

Ngày đăng: 21/01/2014, 09:20

Từ khóa liên quan

Mục lục

  • PHP & MySQL by Example

  • Copyright

    • Preface

    • Acknowledgments

    • Chapter 1

      • 1.1. From Static to Dynamic Web Sites

        • 1.1.1. Static Web Sites

        • 1.1.2. Dynamic Web Sites

        • 1.1.3. What Is Open Source?

        • 1.2. About PHP

          • 1.2.1. Where to Get PHP and Documentation

          • 1.3. About MySQL

            • 1.3.1. Where to Get MySQL and Documentation

            • 1.3.2. Features of MySQL

            • 1.3.3. How to Install MySQL and PHP

            • 1.3.4. Advantages of MySQL and PHP

            • 1.4. Chapter Summary

              • 1.4.1. What You Should Know

              • 1.4.2. What’s Next?

              • Chapter 2

                • 2.1. The Life Cycle of a Web Page

                  • 2.1.1. Analysis of a Web Page

                  • 2.2. The Anatomy of a PHP Script

                    • 2.2.1. The Steps of Writing a PHP Script

                    • 2.3. Some Things to Consider

                      • 2.3.1. PHP and HTML Are Different Languages

                      • 2.3.2. Statements, Whitespace, and Line Breaks

                      • 2.3.3. Comments

                      • 2.3.4. Using PHP Functions

                      • 2.4. Review

                        • 2.4.1. PHP on the Command Line

Tài liệu cùng người dùng

  • Đang cập nhật ...

Tài liệu liên quan