Presentation is loading. Please wait.

Presentation is loading. Please wait.

Lecture 7 – Form processing (Part 2) SFDV3011 – Advanced Web Development 1.

Similar presentations


Presentation on theme: "Lecture 7 – Form processing (Part 2) SFDV3011 – Advanced Web Development 1."— Presentation transcript:

1 Lecture 7 – Form processing (Part 2) SFDV3011 – Advanced Web Development 1

2 2 Validating Form Data  First check that form data was submitted, usually by using array_key_exists() to check for the submit button name  Creating functions can be helpful for validation, especially when the validation needs to be done in different places or on forms: <?php function validate_price($value) { // Ensure that $value is a valid price if( !isset($errors)) $errors = array(); // init array if not defined already if( !is_numeric($value) ) $errors['not_number'] = "not numeric"; if( $value - round($value, 2) != 0 ) $errors['not_dollar'] = "not a dollar amount"; if( $value < 0 ) $errors['not_non-negative'] = "price cannot be negative"; return $errors; } ?>

3 3 Validating Form Data  Often it is convenient to make an error array global so that it is accessible inside and outside of functions. Note how no return values are needed here. function validate_price($value) { // Ensure that $value is a valid price global $errors; // init array if not defined already if(!isset($errors)) $errors = array(); if( !is_numeric($value) ) $errors['not_number'] = "not numeric"; if( $value - round($value, 2) != 0 ) $errors['not_dollar'] = "not a dollar amount"; if( $value < 0 ) $errors['not_non-negative'] = "price cannot be negative"; }

4 4 Validating Form Data  Validation can be a bit subtle at times given that values from forms are always passed as strings. Here's how you would test that a number input as a string is actually numeric: ctype_digit($a)  Why won't is_int($a) work here?  is_int( $integer_type) will only return true, if the TYPE is int, not the value  ctype_digit( $string_type) will only return true if the TYPE is string, and its value is int

5 5 Different input types  Text  Password  Hidden  Radio  Checkbox  Submit  Button  Reset In addition, the compound types: 

6 6 Passing Hidden Post values  To pass a value from one page to another you can use the hidden input type o Only string values can be passed => must convert everything to a string o The urlencode(), serialize() functions may be useful for converting compound values such as arrays into stings. o Use urldecode(), unserialize() to recover the original value from the string passed into the $_POST or $_GET array

7 7 Hidden Input Type " method='POST'> ' > After submitting… $_POST['secret'] = ??? $_POST['stuff'] = ?? $purchase = unserialize(urldecode($_POST['purchase'] ));

8 8 Variables  Information from a web server is made available through EGPCS  Environment, GET, POST, Cookies, Server  PHP will create arrays with EGPCS information  $HTTP_COOKIE_VARS, $HTTP_GET_VARS, $HTTP_POST_VARS, etc.  The 'HTTP' and '_VARS' can be dropped if desired  These arrays are 'global' even inside functions  PHP also will define $_SERVER['PHP_SELF'] that refers to the current script file which is useful for self-processing forms

9 9 Server Info  A ton of information about the server and current browser is made available in the $_SERVER array  SERVER_NAME  REQUEST_METHOD  QUERY_STRING  REMOTE_ADDR  PHP_SELF  ….

10 10 Review: Request Methods  There are two basic methods for getting data from an HTML form into PHP  GET and POST  What's the difference?  GET will encode all data into a query string that is passed with the URL to the action page. This allows data to be bookmarked by the user.  POST will pass data via the server’s environment variables. Data is not seen directly by the user

11 11 HTTP Basics  Web pages are requested by a browser by sending HTTP request messages  Includes a header and a body  Uses a method such as GET or POST  Asks for an address of a file (usually a path)  Sample HTTP request: GET /index.html HTTP/1.1

12 12 Header Modification  Sometimes you will need to intercept and modify the GET HTTP request before it is processed. Use the header() function to do this  Be sure no output is displayed before sending headers or you'll get a message something like this : Warning: Cannot modify header information - headers already sent by (output started at D:\Program Files\nusphere\phpED\Projects\oldpage.php:3)

13 13 Example: Header Forwarding  You can forward (redirect) users to a different page using the header() function. header('Location: http://mysite.com/myfile.php');  This will substitute the current header with 'Location: http://mysite.com/myfile.php'  Effect is that the page myfile.php will be loaded  Tip: always include the protocol such as http:// or file:// to be sure you specify exactly what you want

14 14 More Header Examples  Passing values into the $_GET array during a redirect header('Location:myfile.php?name=Frankie&score=98&grade=A');  To deny access to a page if not authorized header('WWW-Authenticate:Basic realm="My Website"'); header('HTTP/1.0 401 Unauthorized');

15 15 Implementing Back Buttons  Also notice the different ways of using back buttons  Hyperlink ">BACK  Submit Button '>  Java script history action on button

16 16 Opening New Window  Sometimes you want to have the Action of a form open a new window rather than replace the existing one./action_process.php  What do you think would happen if you used " method="POST" target="_blank">

17 17 Arrays in HTML forms  Naming form elements within the same form with the same names and []'s will make an array (any input type). Elements are only those values that are non-empty. " method='post'> <? var_dump($_POST); ?>

18 18 Associative Array of Input Types  Even better: specifying index values inside the []'s will be keys for the array (useful for directly associating selection with array data ) " method='post'> <? var_dump($_POST); ?>

19 19 Using Indexed Arrays to Generate Form Elements  Using particular integer values inside the []'s will explicitly associate an index with the value in the array (this is really the same as an associative array) ” method='post'> <?php var_dump($_POST); $size = 10; for($i=0; $i<$size; $i++){ echo " checkbox $i "; } ?>  Useful for when you want to know exactly which input items are non-empty (in the above example, which checkboxes were checked)

20 20 Making HTML Forms 'Sticky'  Whenever a is processed, the values of its elements are initially empty  Sometimes you want to keep a form element value around after a submit (e.g. for fixing a user-entry error or for remembering a user’s preferences)  To make a form value 'sticky' you must get the information submitted and set it as the value for the form element: ” method='post'> <input type='TEXT' name='textbox' value= “ ”>

21 21 Example Advanced HTML Form Processing: Checkbox Array $value) if ($selections[$key] == 'on') echo " you selected box $key"; exit; } ?> ” method='post'> checkbox $i "; } ?>

22 22 Putting Errors in Their Place MAX_PASS_LEN ) $errors['password_long'] = 'Enter a shorter password'; } $username = 'user‘; $password = 'pass'; $errors = array(); if (array_key_exists('form_data', $_POST)) { // The user entered a password; check it check_pass($_POST['password']); if (count($errors) == 0 && $_POST['username'] == $username && $_POST['password'] == $password) { die('correct!!'); } else { echo 'wrong user or password!'; } } ?>

23 23 Putting Errors in Their Place ' method= 'POST'> Username: "> Password: {$errors['password_short']} "; if (isset($errors['password_long'])) echo " {$errors['password_long']} "; ?>


Download ppt "Lecture 7 – Form processing (Part 2) SFDV3011 – Advanced Web Development 1."

Similar presentations


Ads by Google