Chapter Two: HTML Forms and Server Side Scripting 11/28/2019 BantamlakDejene,Information Technology 1
Create a Simple Form using Php Handling an HTML form with PHP is perhaps the most important process in any dynamic Web site. Two steps are involved: first you create the HTML form itself, and then you create the corresponding PHP script that will receive and process the form data. An HTML form is created using the form tags and various elements for taking input. The form tags look like <form action="script.php" method="post"></form> 11/28/2019 BantamlakDejene,Information Technology 2
Cont.…. In terms of PHP, the most important attribute of your form tag is action, which dictates to which page the form data will be sent. The second attribute method has its own, but post is the value you’ll use most frequently. The different inputs be the text boxes, radio buttons, select menus, check boxes, etc. are placed within the opening and closing form tags. As you’ll see in the next section, what kinds of inputs your form has makes little difference to the PHP script handling it. You should, however, pay attention to the names you give your form inputs, as they’ll be of critical importance when it comes to your PHP code. 11/28/2019 BantamlakDejene,Information Technology 3
Receive Data from a Form in Php Now that the HTML form has been created, it’s time to write a bare- bones PHP script to handle it. To say that this script will be handling the form means that the PHP page will do something with the data it receives (which is the data the user entered into the form). In this chapter, the scripts will simply print the data back to the Web browser. In later examples, form data will be stored in a MySQL database, compared against previously stored values, sent in emails, and more. 11/28/2019 BantamlakDejene,Information Technology 4
Cont.…. The beauty of PHP and what makes it so easy to learn and use is how well it interacts with HTML forms. PHP scripts store the received information in special variables. For example, say you have a form with an input defined like so: <input type="text" name="city" /> Whatever the user types into that input will be accessible via a PHP variable named $_REQUEST['city']. It is very important that the spelling and capitalization match exactly! PHP is case-sensitive when it comes to variable names, so $_REQUEST['city'] will work, but $_Request['city'] and $_REQUEST['City'] will have no value. 11/28/2019 BantamlakDejene,Information Technology 5
Cont.…. Element Name Variable Name Name $_REQUEST['name'] Email $_REQUEST['email'] comments $_REQUEST['comments'] Age $_REQUEST['age'] Gender $_REQUEST['gender'] Submit $_REQUEST['submit'] 11/28/2019 BantamlakDejene,Information Technology 6
Cont.…. All of those examples use two separate files: one that displays the form and another that receives its submitted data. While there’s certainly nothing wrong with this approach, there are advantages to putting the entire process into one script. To have one page both display and handle a form, a conditional must check which action (display or handle) should be taken: if (/* form has been submitted */) { // Handle the form. } else { // Display the form. } 11/28/2019 BantamlakDejene,Information Technology 7
Cont.…. The question, then, is how to determine if the form has been submitted. The answer is simple, after a bit of explanation. When you have a form that uses the POST method and gets submitted back to the same page, two different types of requests will be made of that script. The first request, which loads the form, will be a GET request. This is the standard request made of most Web pages. When the form is submitted, a second request of the script will be made, this time a POST request (as long as the form uses the POST method). With this in mind, you can test for a form’s submission by checking the request method, found in the $_SERVER array: if ($_SERVER['REQUEST_METHOD'] = = 'POST') { // Handle the form. } else { // Display the form. } 11/28/2019 BantamlakDejene,Information Technology 8
Cont.…. If you want a page to handle a form and then display it again (e.g., to add a record to a database and then give an option to add another), drop the else clause: if ($_SERVER['REQUEST_METHOD'] = = 'POST') { // Handle the form. } // Display the form. 11/28/2019 BantamlakDejene,Information Technology 9
Validate Form Data A critical concept related to handling HTML forms is that of validating form data. In terms of both error management and security, you should absolutely never trust the data being submitted by an HTML form. Whether erroneous data is purposefully malicious or just unintentionally inappropriate, it’s up to you the Web architect to test it against expectations. Validating form data requires the use of conditionals and any number of functions, operators, and expressions. One standard function to be used is isset(), which tests if a variable has a value. You saw an example of this in the preceding script. One issue with the isset() function is that an empty string tests as true, meaning that isset() is not an effective way to validate text inputs and text boxes from an HTML form. To check that a user typed something into textual elements, you can use the empty() function. It checks if a variable has an empty value: an empty string, 0, NULL, or FALSE. 11/28/2019 BantamlakDejene,Information Technology 10
Use Conditionals and Operators PHP’s three primary terms for creating conditionals are if, else, and elseif (which can also be written as two words, else if). Every conditional begins with an if clause: if (condition) { // Do something! } An if can also have an else clause: if (condition) { // Do something! } else { // Do something else! } 11/28/2019 BantamlakDejene,Information Technology 11
Cont.…. Symbol Meaning Type Example = = is equal to Comparison $x = = $y != is not equal to Comparison $x != $y < less than Comparison $x < $y > Greater than Comparison $x > $y <= less than or equal to Comparison $x <= $y >= Greater than or equal to Comparison $x >= $y ! not Logical !$x && and Logical $x && $y AND and Logical $x and $y || or Logical $x || $y OR or Logical $x or $y XOR and not logical $x XOR $y 11/28/2019 BantamlakDejene,Information Technology 12
Cont.…. A condition can be true in PHP for any number of reasons. To start, these are true conditions: $var, if $var has a value other than 0, an empty string, FALSE, or NULL. isset($var), if $var has any value other than NULL, including 0, FALSE, or an empty string TRUE, true, True, etc. In the second example, a new function, isset(), is introduced. This function checks if a variable is “set,” meaning that it has a value other than NULL (as a reminder, NULL is a special type in PHP, representing no set value). You can also use the comparative and logical operators in conjunction with parentheses to make more complicated expressions. 11/28/2019 BantamlakDejene,Information Technology 13
Use For and While Loops The other two types of loops you’ll use are for and while. The while loop looks like this: while (condition) { // Do something. } As long as the condition part of the loop is true, the loop will be executed. Once it becomes false, the loop is stopped. If the condition is never true, the loop will never be executed. The while loop will most frequently be used when retrieving results from a database. The for loop has a more complicated syntax: for (initial expression; condition; closing expression) { // Do something. } 11/28/2019 BantamlakDejene,Information Technology 14
Work with Forms and Arrays of Data Now it’s time to learn about another type, the array. Unlike strings and numbers, an array can hold multiple, separate pieces of information. An array is therefore like a list of values, each value being a string or a number or even another array. Arrays are structured as a series of key value pairs, where one pair is an item or element of that array. For each item in the list, there is a key (or index) associated with it. PHP supports two kinds of arrays: indexed, which use numbers as the keys, and associative, which use strings as keys. As in most programming languages, with indexed arrays, arrays will begin with the first index at 0, unless you specify the keys explicitly. 11/28/2019 BantamlakDejene,Information Technology 15
Cont.…. An array follows the same naming rules as any other variable. This means that you might not be able to tell that $var is an array as opposed to a string or number. The important syntactical difference arises when accessing individual array elements. To refer to a specific value in an array, start with the array variable name, followed by the key within square brackets: $band = $artists[0]; // The Mynabirds echo $states['MD']; // Maryland You can see that the array keys are used like other values in PHP: numbers (e.g., 0) are never quoted, whereas strings (MD) must be. Because arrays use a different syntax than other variables, and can contain multiple values, printing them can be trickier. This will not work: echo "My list of states: $states"; 11/28/2019 BantamlakDejene,Information Technology 16
Introduction to Regular Expressions Sometimes you want to check for a specific structure as opposed to a specific value. Regular expressions allow this type of matching. Besides the few examples below and the inclusion of some regular expression syntax, no tutorial on regular expressions is given here. 11/28/2019 BantamlakDejene,Information Technology 17
Cont.…. ^ Start of string $ End of string . Any single character ( ) Group of expressions [] Item range (e.g. [afg] means a, f, or g) [^] Items not in range ( e.g. [^cde] means not c, d, or e ) - (dash) character range within an item range (e.g. [a-z] means a through z) | (pipe) Logical or ( e.g. (a|b) means a or b ) ? Zero or one of preceding character/item range * Zero or more of preceding character/item range + One or more of preceding character/item range {integer} Exactly integer of preceding character/item range ( e.g. a{2} ) 11/28/2019 BantamlakDejene,Information Technology 18
Cont.…. {integer,} Integer or more of preceding character/item range ( e.g. a{2,} ) {integer, integer} From integer to integer (e.g. a{2,4} means 2 to four of a ) Escape character [:punct:] Any punctuation [:space:] Any space character [:blank:] Any space or tab [:digit:] Any digit: 0 through 9 [:alpha:] All letters: a-z and A-Z [:alnum:] All digits and letters: 0-9, a-z, and A-Z [:xdigit:] Hexadecimal digit [:print:] Any printable character [:upper:] All uppercase letters: A-Z [:lower:] All lowercase letters: a-z 11/28/2019 BantamlakDejene,Information Technology 19
Cont.…. c Control character s Whitespace S Not whitespace d Digit (0-9) D Not a digit w Letter (a-z, A-Z) W Not a letter x Hexadecimal digit O Octal digit 11/28/2019 BantamlakDejene,Information Technology 20 Character classes:–
Cont.…. 11/28/2019 BantamlakDejene,Information Technology 21 I Case-insensitive S Period matches newline M ^ and $ match lines U Ungreedy matching E Evaluate replacement X Pattern over several lines Modifiers:–
THANK YOU 11/28/2019 BantamlakDejene,Information Technology 22

html forms and server side scripting

  • 1.
    Chapter Two: HTML Formsand Server Side Scripting 11/28/2019 BantamlakDejene,Information Technology 1
  • 2.
    Create a SimpleForm using Php Handling an HTML form with PHP is perhaps the most important process in any dynamic Web site. Two steps are involved: first you create the HTML form itself, and then you create the corresponding PHP script that will receive and process the form data. An HTML form is created using the form tags and various elements for taking input. The form tags look like <form action="script.php" method="post"></form> 11/28/2019 BantamlakDejene,Information Technology 2
  • 3.
    Cont.…. In terms ofPHP, the most important attribute of your form tag is action, which dictates to which page the form data will be sent. The second attribute method has its own, but post is the value you’ll use most frequently. The different inputs be the text boxes, radio buttons, select menus, check boxes, etc. are placed within the opening and closing form tags. As you’ll see in the next section, what kinds of inputs your form has makes little difference to the PHP script handling it. You should, however, pay attention to the names you give your form inputs, as they’ll be of critical importance when it comes to your PHP code. 11/28/2019 BantamlakDejene,Information Technology 3
  • 4.
    Receive Data froma Form in Php Now that the HTML form has been created, it’s time to write a bare- bones PHP script to handle it. To say that this script will be handling the form means that the PHP page will do something with the data it receives (which is the data the user entered into the form). In this chapter, the scripts will simply print the data back to the Web browser. In later examples, form data will be stored in a MySQL database, compared against previously stored values, sent in emails, and more. 11/28/2019 BantamlakDejene,Information Technology 4
  • 5.
    Cont.…. The beauty ofPHP and what makes it so easy to learn and use is how well it interacts with HTML forms. PHP scripts store the received information in special variables. For example, say you have a form with an input defined like so: <input type="text" name="city" /> Whatever the user types into that input will be accessible via a PHP variable named $_REQUEST['city']. It is very important that the spelling and capitalization match exactly! PHP is case-sensitive when it comes to variable names, so $_REQUEST['city'] will work, but $_Request['city'] and $_REQUEST['City'] will have no value. 11/28/2019 BantamlakDejene,Information Technology 5
  • 6.
    Cont.…. Element Name VariableName Name $_REQUEST['name'] Email $_REQUEST['email'] comments $_REQUEST['comments'] Age $_REQUEST['age'] Gender $_REQUEST['gender'] Submit $_REQUEST['submit'] 11/28/2019 BantamlakDejene,Information Technology 6
  • 7.
    Cont.…. All of thoseexamples use two separate files: one that displays the form and another that receives its submitted data. While there’s certainly nothing wrong with this approach, there are advantages to putting the entire process into one script. To have one page both display and handle a form, a conditional must check which action (display or handle) should be taken: if (/* form has been submitted */) { // Handle the form. } else { // Display the form. } 11/28/2019 BantamlakDejene,Information Technology 7
  • 8.
    Cont.…. The question, then,is how to determine if the form has been submitted. The answer is simple, after a bit of explanation. When you have a form that uses the POST method and gets submitted back to the same page, two different types of requests will be made of that script. The first request, which loads the form, will be a GET request. This is the standard request made of most Web pages. When the form is submitted, a second request of the script will be made, this time a POST request (as long as the form uses the POST method). With this in mind, you can test for a form’s submission by checking the request method, found in the $_SERVER array: if ($_SERVER['REQUEST_METHOD'] = = 'POST') { // Handle the form. } else { // Display the form. } 11/28/2019 BantamlakDejene,Information Technology 8
  • 9.
    Cont.…. If you wanta page to handle a form and then display it again (e.g., to add a record to a database and then give an option to add another), drop the else clause: if ($_SERVER['REQUEST_METHOD'] = = 'POST') { // Handle the form. } // Display the form. 11/28/2019 BantamlakDejene,Information Technology 9
  • 10.
    Validate Form Data Acritical concept related to handling HTML forms is that of validating form data. In terms of both error management and security, you should absolutely never trust the data being submitted by an HTML form. Whether erroneous data is purposefully malicious or just unintentionally inappropriate, it’s up to you the Web architect to test it against expectations. Validating form data requires the use of conditionals and any number of functions, operators, and expressions. One standard function to be used is isset(), which tests if a variable has a value. You saw an example of this in the preceding script. One issue with the isset() function is that an empty string tests as true, meaning that isset() is not an effective way to validate text inputs and text boxes from an HTML form. To check that a user typed something into textual elements, you can use the empty() function. It checks if a variable has an empty value: an empty string, 0, NULL, or FALSE. 11/28/2019 BantamlakDejene,Information Technology 10
  • 11.
    Use Conditionals andOperators PHP’s three primary terms for creating conditionals are if, else, and elseif (which can also be written as two words, else if). Every conditional begins with an if clause: if (condition) { // Do something! } An if can also have an else clause: if (condition) { // Do something! } else { // Do something else! } 11/28/2019 BantamlakDejene,Information Technology 11
  • 12.
    Cont.…. Symbol Meaning TypeExample = = is equal to Comparison $x = = $y != is not equal to Comparison $x != $y < less than Comparison $x < $y > Greater than Comparison $x > $y <= less than or equal to Comparison $x <= $y >= Greater than or equal to Comparison $x >= $y ! not Logical !$x && and Logical $x && $y AND and Logical $x and $y || or Logical $x || $y OR or Logical $x or $y XOR and not logical $x XOR $y 11/28/2019 BantamlakDejene,Information Technology 12
  • 13.
    Cont.…. A condition canbe true in PHP for any number of reasons. To start, these are true conditions: $var, if $var has a value other than 0, an empty string, FALSE, or NULL. isset($var), if $var has any value other than NULL, including 0, FALSE, or an empty string TRUE, true, True, etc. In the second example, a new function, isset(), is introduced. This function checks if a variable is “set,” meaning that it has a value other than NULL (as a reminder, NULL is a special type in PHP, representing no set value). You can also use the comparative and logical operators in conjunction with parentheses to make more complicated expressions. 11/28/2019 BantamlakDejene,Information Technology 13
  • 14.
    Use For andWhile Loops The other two types of loops you’ll use are for and while. The while loop looks like this: while (condition) { // Do something. } As long as the condition part of the loop is true, the loop will be executed. Once it becomes false, the loop is stopped. If the condition is never true, the loop will never be executed. The while loop will most frequently be used when retrieving results from a database. The for loop has a more complicated syntax: for (initial expression; condition; closing expression) { // Do something. } 11/28/2019 BantamlakDejene,Information Technology 14
  • 15.
    Work with Formsand Arrays of Data Now it’s time to learn about another type, the array. Unlike strings and numbers, an array can hold multiple, separate pieces of information. An array is therefore like a list of values, each value being a string or a number or even another array. Arrays are structured as a series of key value pairs, where one pair is an item or element of that array. For each item in the list, there is a key (or index) associated with it. PHP supports two kinds of arrays: indexed, which use numbers as the keys, and associative, which use strings as keys. As in most programming languages, with indexed arrays, arrays will begin with the first index at 0, unless you specify the keys explicitly. 11/28/2019 BantamlakDejene,Information Technology 15
  • 16.
    Cont.…. An array followsthe same naming rules as any other variable. This means that you might not be able to tell that $var is an array as opposed to a string or number. The important syntactical difference arises when accessing individual array elements. To refer to a specific value in an array, start with the array variable name, followed by the key within square brackets: $band = $artists[0]; // The Mynabirds echo $states['MD']; // Maryland You can see that the array keys are used like other values in PHP: numbers (e.g., 0) are never quoted, whereas strings (MD) must be. Because arrays use a different syntax than other variables, and can contain multiple values, printing them can be trickier. This will not work: echo "My list of states: $states"; 11/28/2019 BantamlakDejene,Information Technology 16
  • 17.
    Introduction to RegularExpressions Sometimes you want to check for a specific structure as opposed to a specific value. Regular expressions allow this type of matching. Besides the few examples below and the inclusion of some regular expression syntax, no tutorial on regular expressions is given here. 11/28/2019 BantamlakDejene,Information Technology 17
  • 18.
    Cont.…. ^ Start ofstring $ End of string . Any single character ( ) Group of expressions [] Item range (e.g. [afg] means a, f, or g) [^] Items not in range ( e.g. [^cde] means not c, d, or e ) - (dash) character range within an item range (e.g. [a-z] means a through z) | (pipe) Logical or ( e.g. (a|b) means a or b ) ? Zero or one of preceding character/item range * Zero or more of preceding character/item range + One or more of preceding character/item range {integer} Exactly integer of preceding character/item range ( e.g. a{2} ) 11/28/2019 BantamlakDejene,Information Technology 18
  • 19.
    Cont.…. {integer,} Integer ormore of preceding character/item range ( e.g. a{2,} ) {integer, integer} From integer to integer (e.g. a{2,4} means 2 to four of a ) Escape character [:punct:] Any punctuation [:space:] Any space character [:blank:] Any space or tab [:digit:] Any digit: 0 through 9 [:alpha:] All letters: a-z and A-Z [:alnum:] All digits and letters: 0-9, a-z, and A-Z [:xdigit:] Hexadecimal digit [:print:] Any printable character [:upper:] All uppercase letters: A-Z [:lower:] All lowercase letters: a-z 11/28/2019 BantamlakDejene,Information Technology 19
  • 20.
    Cont.…. c Control character sWhitespace S Not whitespace d Digit (0-9) D Not a digit w Letter (a-z, A-Z) W Not a letter x Hexadecimal digit O Octal digit 11/28/2019 BantamlakDejene,Information Technology 20 Character classes:–
  • 21.
    Cont.…. 11/28/2019 BantamlakDejene,Information Technology 21 I Case-insensitive S Periodmatches newline M ^ and $ match lines U Ungreedy matching E Evaluate replacement X Pattern over several lines Modifiers:–
  • 22.