ITM 352 Introduction to Applications Programming Prof. Daniel Port.
ITM 352 - © Port, Kazman1 ITM 352 More on Forms Processing.
-
Upload
pauline-simon -
Category
Documents
-
view
228 -
download
2
Transcript of ITM 352 - © Port, Kazman1 ITM 352 More on Forms Processing.
ITM 352 - © Port, Kazman 1
ITM 352
More on Forms Processing
ITM 352 - © Port, Kazman 2
Different Input Types
Here are the HTML form element input types you can use
Text Password Hidden Radio Checkbox Submit Button Reset
In addition, the compound types: <select> <textarea> <listbox>
ITM 352 - © Port, Kazman 3
Login Program with Functions $usernames = array (
'Moe' =>'stooge1','Larry' => 'stooge2','Curly' => 'stooge3'
);
if (array_key_exists('submit_button', $_POST)) {if(process_login($usernames) == TRUE) {
print "logged in " . $_POST['username'];}else {
print 'Incorrect password for ' . $_POST['username'] . '<br>';
display_login($usernames);}
} else {display_login($usernames);
}
ITM 352 - © Port, Kazman 4
Display Login Function/* * Displays a login for with a select box of usernames taken from $users */function display_login($users) {
?><form action = "<?= $_SERVER['PHP_SELF'] ?>"
method = 'post'><select name='username'><?php
foreach ($users as $user => $pass) {printf('<option>%s</option>', $user);
}?></select><input type = 'password' name = 'password'><input type = 'submit' name = 'submit_button'
value = 'login'></form><?php
}
ITM 352 - © Port, Kazman 5
Process Login Function/* * checks the posted form to see if password * entered matches the password for the username *(info in $users) selected in the form. Returns * TRUE if there is a match, FALSE otherwise */function process_login($users) {
if( $users[ $_POST['username'] ] == $_POST['password'])
return TRUE;else
return FALSE;}
Do functions simplify or complicate? Why?What are the additional benefits of using functions?
ITM 352 - © Port, Kazman 6
Recap: Tips and Hints
Use single ' ' on the inside, " " around the outside or vice versa
Take advantage of PHP by using for/while/foreach to generate multiple form elements and compound types
Quotes must be used around anything with spaces
ITM 352 - © Port, Kazman 7
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:
<?phpfunction validate_price($value){ 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();}?>
ITM 352 - © Port, Kazman 8
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){global $errors; 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";}
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?
Do Exercise 1
ITM 352 - © Port, Kazman 9
Different Input Types
Text Password Hidden Radio Checkbox Submit Button Reset
In addition, the compound types: <select> <textarea> <listbox>
ITM 352 - © Port, Kazman 10
Passing Hidden Post valuesTo pass a value from one page to another
use the hidden input type Only string values can be passed
Must convert everything to a stringThe urlencode(), serialize()
functions may be useful for converting compound values such as arrays into stings. Use urldecode(), unserialize() to recover the original value from the string passed into the $_POST or $_GET array
ITM 352 - © Port, Kazman 11
Hidden Input Type
<?php $things = array('one thing', 'two thing'); ?>
<form action= "<?= $_SERVER['PHP_SELF'] ?>" method='POST'>
<input type='hidden' name='secret' value=96>
<input type='hidden' name='stuff' value='<?= urlencode(serialize($things)) ?> ' >
<input type='submit'>
</form>
After submitting…
$_POST['secret'] = ???
$_POST['stuff'] = ??
$things = unserialize(urldecode($_POST['stuff'] ));
Do Exercise 2
ITM 352 - © Port, Kazman 12
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
ITM 352 - © Port, Kazman 13
Server InfoA 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 ….
ITM 352 - © Port, Kazman 14
Review: Request MethodsThere 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
ITM 352 - © Port, Kazman 15
HTTP BasicsWeb 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
ITM 352 - © Port, Kazman 16
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)
ITM 352 - © Port, Kazman 17
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
ITM 352 - © Port, Kazman 18
More Header ExamplesPassing values into the $_GET array during
a redirectheader('Location:myfile.php?name=Dan&score=98&grade=A');
To deny access to a page if not authorized (more on this in later classes)header('WWW-Authenticate:Basic realm="My Website"');
header('HTTP/1.0 401 Unauthorized');
Do Exercise 3
ITM 352 - © Port, Kazman 19
Implementing Back Buttons
Also notice the different ways of using back buttons Hyperlink
<A href="<?= $_SERVER['HTTP_REFERER'] ?>">BACK</A>
Submit Button <form action='<?= $_SERVER['HTTP_REFERER'] ?>'>
<INPUT TYPE="SUBMIT" value="back"></form>
Java script history action on button <FORM>
<INPUT TYPE="button" VALUE="Back!" onClick="history.go(-1)"></FORM>
ITM 352 - © Port, Kazman 20
Opening New Window Sometimes you want to have the Action of a form
open a new window rather than replace the existing one
<FORM action="./action_process.php" method="POST" target="_blank">
<INPUT TYPE="TEXT" name="stuff_input_field"><INPUT TYPE="SUBMIT" value="Open New Window"></FORM>
./action_process.php<?php echo 'You entered ' . $_POST['stuff_input_field']; ?>
What do you think would happen if you used<FORM action="<?= $_SERVER['PHP_SELF'] ?>" method="POST"
target="_blank">
ITM 352 - © Port, Kazman 21
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.
<FORM action="<?= $_SERVER['PHP_SELF'] ?>" method='post'><INPUT TYPE="TEXT" name="line[]"><INPUT TYPE="TEXT" name="line[]"><INPUT TYPE="TEXT" name="line[]"><INPUT TYPE="SUBMIT">
</FORM>
<?var_dump($_POST);
?>
ITM 352 - © Port, Kazman 22
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)
<FORM action="<?= $_SERVER['PHP_SELF'] ?>" method='post'><INPUT TYPE="TEXT" name="product[name]"><INPUT TYPE="TEXT" name="product[price]"><INPUT TYPE="TEXT" name="product[description]"><INPUT TYPE="SUBMIT">
</FORM>
<?var_dump($_POST);
?>
ITM 352 - © Port, Kazman 23
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 the same as an associative array where the keys are integers)
<FORM action='<?= $_SERVER['PHP_SELF'] ?>' method='post'><?phpvar_dump($_POST);$size = 10;for($i=0; $i<$size; $i++){
echo "<br>checkbox $i <INPUT TYPE='CHECKBOX' name='a[$i]'>";
}?><INPUT TYPE="SUBMIT"></FORM>
Useful for when you want to know exactly which input items are non-empty (in the above example, which checkboxes were checked)
ITM 352 - © Port, Kazman 24
Making HTML Forms 'Sticky' Whenever a <form> 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:
<FORM action='<?= $_SERVER['PHP_SELF'] ?>' method='post'> <br> <input type='TEXT' name='textbox' value= '<?php if(isset($_POST['textbox']))
echo $_POST['textbox'] ?>'> <INPUT TYPE="SUBMIT"></FORM>
ITM 352 - © Port, Kazman 25
Example Advanced HTML Form Processing: Checkbox Array
<?php if(array_key_exists('a', $_POST)) { $selections = $_POST['a']; foreach($selections as $key => $value) if ($selections[$key] == 'on') echo "<br>you selected box $key"; exit;}
?><FORM action='<?= $_SERVER['PHP_SELF'] ?>' method='post'><?php$size = 10;for($i=0; $i<$size; $i++){
echo "<br>checkbox $i <INPUT TYPE='CHECKBOX' name='a[$i]'>";} ?><br><INPUT TYPE="SUBMIT"></FORM>
ITM 352 - © Port, Kazman 26
Putting Errors in Their Place<?php
define('MIN_PASS_LEN', 3); define('MAX_PASS_LEN', 10);
function check_pass($pword) { global $errors; if (strlen($pword) < MIN_PASS_LEN ) $errors['password_short'] = 'Enter a longer
password'; if (strlen($pword) > MAX_PASS_LEN ) $errors['password_long'] = 'Enter a shorter
password';}
$username = 'user‘; $password = 'pass'; $errors = array();
if (array_key_exists('form_data', $_POST)) { check_pass($_POST['password']); if (count($errors) == 0 && $_POST['username'] == $username &&
$_POST['password'] == $password) { die('correct!!'); } else { echo 'wrong'; }}
?>
ITM 352 - © Port, Kazman 27
Putting Errors in Their Place<form action = '<?= $_SERVER['PHP_SELF'] ?>' method= 'POST'>
Username: <br><INPUT TYPE="TEXT" name="username" value = "<?php if(isset($_POST['username'])) echo $_POST['username'] ?>"><br>Password: <br><INPUT TYPE="password" name = 'password'><?phpif (isset($errors['password_short'])) echo " <font color='red'>{$errors['password_short']}</font>";if (isset($errors['password_long'])) echo " <font color='red'>{$errors['password_long']}</font>";?><br><br><INPUT TYPE="HIDDEN" name = 'form_data' value='submitted'><INPUT TYPE="SUBMIT" name = 'submit'>
</form>