intTypePromotion=1
zunia.vn Tuyển sinh 2024 dành cho Gen-Z zunia.vn zunia.vn
ADSENSE

PHP and MySQL by Example- P9

Chia sẻ: Thanh Cong | Ngày: | Loại File: PDF | Số trang:50

78
lượt xem
13
download
 
  Download Vui lòng tải xuống để xem tài liệu đầy đủ

Tham khảo tài liệu 'php and mysql by example- p9', công nghệ thông tin, kỹ thuật lập trình phục vụ nhu cầu học tập, nghiên cứu và làm việc hiệu quả

Chủ đề:
Lưu

Nội dung Text: PHP and MySQL by Example- P9

  1.   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) Image Button 1 Pick your pizza: 2 Tomato and Cheese Salami Pineapple and Ham Canadian bacon Plain Cheese Press the pizza man to order! 3 ------------------------------------------------------------------ (The PHP Script) Finding Pixel Coordinates Pizza Choices
  2. print ""; 5 foreach ( $_POST['topping'] as $value ){ print "$value"; } print ""; } print "The pixel coordinates of the image are: "; 6 $coord1 = $_POST['pizzas_x']; $coord2 = $_POST['pizzas_y']; print "$coord1, $coord2"; ?> 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.
  3. 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.
  4. 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 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:   First HTML Form 5
  5. 6 Please enter your name: Please enter your phone: 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.
  6. 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:   Hidden Fields Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
  7.       Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
  8. 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  user-­‐defined  function,   process_form(),  is  called. 2 If  the  test  on  line  1  fails,  then  the  form  has  not  been  previously  displayed.  The   user-­‐defined  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  here-­‐doc  used  to  print  out  the  HTML  form  and  interpolate   any  variables.  Remember  that  when  in  a  here-­‐doc  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    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  user-­‐defined  terminator,  EOF,  for  marking  the  end  of  the  here-­‐doc,  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.
  9. 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.   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.
  10. Figure 10.30. The header must be sent first.   Example 10.17. 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:
  11. Example 10.18. Code  View:   (The HTML File) Redirecting the User 1 Select a search engine 2 Google Yahoo! Lycos PHP Index 3 ------------------------------------------------------------------ (The PHP Script) Explanation 1 The  form’s  action  attribute  is  assigned  the  path  to  the  PHP  script  that  will  handle  the   redirect  once  the  form  is  submitted.  The  HTML  form  is  shown  in  Figure  10.31. 2 The  HTML  select  menu  will  give  the  user  options  to  choose  from. 3 As  soon  as  the  user  clicks  the  submit  button,  the  form  information  will  be  sent  to  the   server  and  handled  by  the  PHP  script  listed  in  the  form’s  action  attribute. 4 If  the  user  did  not  select  anything,  the  value  of  $_POST[new_url]  will  be  empty,  and  the   script  will  exit. 5 If  the  user  selected  one  of  the  search  engines  in  the  menu  (Figure  10.32),  he  or  she  will   be  directed  to  that  Web  site  with  the  PHP  header()  function.  The  value  of   $_POST[new_url]  is  the  address  of  the  selected  Web  site;  for  example,   http://www.lycos.com.  Once  the  user  is  redirected,  he  or  she  can  use  the  brower’s  Back   button  to  go  back  to  the  page  where  the  selection  was  made. Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
  12. button  to  go  back  to  the  page  where  the  selection  was  made.   Figure 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. Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
  13. 10.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 Tag and the file Type To upload files the tag has three attributes: • The action attribute of the 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 multi- part/form-data. The browser encodes form data differently for application/x-www-form- urlencoded and multipart/form-data. • The method attribute should be "POST". Example 10.19. (Sample File Upload Form Values) 1 4 5 Choose a file to upload: In addition to the three attributes, the form’s input type is "file"; for example:
  14. PHP’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 Array Description $_FILES['userfile']['name'] The  original  name  of  the  file  on  the  client  machine. $_FILES['userfile']['type'] The  MIME  type  of  the  file,  if  the  browser  provided  this   information.  An  example  would  be  "image/gif". $_FILES['userfile']['size'] The  size,  in  bytes,  of  the  uploaded  file. $_FILES['userfile']['tmp_name'] The  temporary  filename  of  the  file  in  which  the   uploaded  file  was  stored  on  the  server. $_FILES['userfile']['error'] The  error  code  associated  with  this  file  upload.   ['error']  was  added  in  PHP  4.2.0.   Example 10.20. Code  View:   (The HTML File) Uploading Files Uploading Files 1 Type the name of the file to upload: 5 -------------------------------------------------- (The PHP Script--upload_file.php) Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
  15. Explanation 1 The  form  starts  here  and  is  displayed  in  Figure  10.33. 2 The  attribute  to  the  form  type  is  enctype  and  assigned  "multipart/form- data".  This  encoding  type  is  used  to  send  data  from  files. 3 The  action  attribute  specifies  the  PHP  script  that  will  process  the  uploaded   files. 4 Uploaded  files  must  be  sent  via  the  POST  method. 5 The  input  device  is  of  type  "file"  and  will  be  assigned  the  name  "user_file".   The  name  is  how  the  uploaded  file  will  be  identified  in  the  PHP  file,  not  the   real  name  of  the  file.  See  Figure  10.35. 6 The  $_FILES['user_file']['tmp_name']  array  holds  the  name  of  the   temporary  file  that  PHP  gave  to  the  uploaded  file.  The  fopen()  function  will   open  that  file  for  reading  and  return  a  filehandle  that  allows  access  to  the  file.   (See  “The  fopen()  Function”  on  page  448.) Figure 10.33. The file upload form from Example 10.20 in the browser.         Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
  16.     Figure 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. Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
  17. Format 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. Example 10.21. Code  View:   (The HTML Form) Uploading Pictures Uploading Files Browse and select the picture you want to upload: 2 --------------------------------------------------------------- (The PHP Script) File Uploads Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
  18. 10.3.14. Sticky Forms A sticky form is a form that remembers the values you typed in the input fields. A typical example is when you fill out a form to purchase some products or fill out a registration form and you left out a field or typed the credit card information wrong. When you submit the order, the page comes back with the form and tells you what you did wrong and asks you to resubmit the order. If the order form is long and contains lots of boxes, how many times will you resubmit it, if you have to start all over again? With a sticky form, the input data can be saved so that when the form is redisplayed, the data is still there. The following example checks if the user left any fields empty and if he or she did, redisplays the form with an error showing what fields need to filled. The fields that had data in them still contain the data. (For a complete discussion on form validation, see Chapter 12, “Regular Expressions and Pattern Matching.”) Example 10.22. Code  View:   Empty Fields Validating Input
  19. 13 What is your phone number? Explanation 1 The  $errors  array  is  initialized.  It  will  be  used  to  build  a  string  error   message. 2 If  the  isset()  function  returns  true,  the  user  has  already  submitted  the  form   and  program  control  will  go  to  line  3. 3 The  user-­‐defined  function,  validate_input(),  is  called. 4 If  the  PHP  count()  function  finds  that  the  $errors  array  is  not  empty,  the   display_form()  function  is  called  and  the  same  form  is  displayed  again  with   the  error  messages  displayed  in  red.  See  Figures  10.38  and  10.39. 5 If  there  are  no  errors,  then  the  form  will  be  processed.  We  do  not  do  any  real   processing  here,  but  if  we  did,  this  is  where  the  code  would  go. 6 If  line  1  is  false  (i.e.,  the  form  has  not  yet  been  displayed),  the  form  will  be   shown  in  the  browser  for  the  first  time. 7 This  is  a  user-­‐defined  function  that  will  determine  whether  or  not  the  user   filled  in  the  required  fields. 8 The  global  keyword  makes  this  array  available  within  the  function. 9 If  the  user  did  not  fill  the  "name"  field,  the  $errors  array  will  be  assigned  a   string  of  text  as  its  value.  The  key  'name'  is  the  name  of  the  text  box. 10 This  function  displays  the  form,  as  displayed  in  Figure  10.37. Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
ADSENSE

CÓ THỂ BẠN MUỐN DOWNLOAD

 

Đồng bộ tài khoản
2=>2