SakhaliaNetHome PageSahara TerritoryVorKutaAcceptance of cookiesAcceptance of cookies

PHP Tutorial :: Forms (VI)

PHP Example #69

Validating data in forms

One of the threats for websites that take user input through forms is the presence of source code (HTML or Javascript) in the strings that are passed to the form. These codes can provoke an undesired manipulation of the webpage that will display the input data, leading to the page not being able to load, stealing of cookies or redirection of the visitors towards websites, often malicious. This happens because the code included in these input strings is treated by the client browsers as if it were part of the source code of the webpage itself (and in fact it is!), so for avoiding this, we must perform a particular method of validation. Fortunately, PHP provides two handy functions to solve this problem with ease...

The first one, strip_tags(), will remove automatically the HTML source code that a string could contain, leaving intact the remaining characters. The second one, htmlentities(), will replace any HTML tags found in a string by their equivalent HTML entities; this allows to display the source code as innofensive text, that will not be executed by a browser. The usage of one or the other depends on the needs of the website; if the website is intended for displaying only regular text, the first one would be the way to go, while for websites that need to display source codes (like this one!) the second one is required.

This example provides two different text fields, one for each of the forementioned functions. Paste the following string on both and submit it: I <b>love</b> sweet <div class="fancy">rice</div> & tea.

<?php
if (! array_key_exists('_submit_check', $_POST)) {
$_POST['_submit_check'] = 0;
}
if ($_POST['_submit_check']) {
if ($form_errors = validate_form()) {
show_form($form_errors);
} else {
process_form();
}
} else {
$comments1 = '';
$comments2 = '';
show_form();
}
function process_form() {
print $GLOBALS['comments1'] . '<br/>';
print $GLOBALS['comments2'];
}
function show_form($errors = '') {
if ($errors) {
print 'Please correct these errors: <ul><li>';
print implode('</li><li>', $errors);
print '</li></ul>';
}
print '<form method="post" action="' . $_SERVER['PHP_SELF'] . '">';
print 'Your comments here will be passed to strip_tags():<br/>';
print '<input type="text" name="text1" maxlength="300" size="76"/><br/>';
print 'Your comments here will be passed to htmlentities():<br/>';
print '<input type="text" name="text2" maxlength="300" size="76"/><br/>';
print '<input type="submit" value="Submit!"/>';
print '<input type="hidden" name="_submit_check" value="1"/>';
print '</form>';
}
function validate_form() {
$errors = array();
$GLOBALS['comments1'] = strip_tags($_POST['text1']);
$GLOBALS['comments2'] = htmlentities($_POST['text2']);
if (strlen($GLOBALS['comments1']) < 10) {
$errors[] = 'The comment must have at least 10 characters long.';
}
if (strlen(trim($GLOBALS['comments1'])) == 0) {
$errors[] = 'You must enter a comment.';
}
if (strlen($GLOBALS['comments2']) < 10) {
$errors[] = 'The comment must have at least 10 characters long.';
}
if (strlen(trim($GLOBALS['comments2'])) == 0) {
$errors[] = 'You must enter a comment.';
}
return $errors;
}
?>
Your comments here will be passed to strip_tags():

Your comments here will be passed to htmlentities():

PHP Example #70

Default values of a form

Sometimes we want some values to be already present in a form before the user types on it; also, when a form is shown again because of errors, it is useful to display again the input data just sent by the user. This example is a remake of the previous form that includes additional code for showing these default messages. Apart from that, it works samely than the previous one, but this time the default string is already present in the text fields when the form is shown for the first time; besides, when the user inputs some data, this data will replace the default strings and will be displayed if the form has to be shown again.

Note that htmlentities() is used when returning to the text fields the default values, to prevent the injection of malicious code into the source code of the very webpage.

<?php
if (! array_key_exists('_submit_check2', $_POST)) {
$_POST['_submit_check2'] = 0;
}
if ($_POST['_submit_check2']) {
$defaults = $_POST;
if ($form_errors2 = validate_form2()) {
show_form2($form_errors2);
} else {
process_form2();
}
} else {
$defaults = array('text12' => 'I <b>love</b> sweet <div class="fancy">rice</div> & tea.',
'text22' => 'I <b>love</b> sweet <div class="fancy">rice</div> & tea.');
$comments12 = $defaults['text12'];
$comments22 = $defaults['text22'];
show_form2();
}
function process_form2() {
print $GLOBALS['comments12'] . '<br/>';
print $GLOBALS['comments22'];
}
function show_form2($errors = '') {
if ($errors) {
print 'Please correct these errors: <ul><li>';
print implode('</li><li>', $errors);
print '</li></ul>';
}
print '<form method="post" action="' . $_SERVER['PHP_SELF'] . '">';
print 'Your comments here will be passed to strip_tags():<br/>';
print '<input type="text" name="text12" maxlength="300"
value="' . htmlentities($GLOBALS['defaults']['text12']) . '" size="76"/><br/>';
print 'Your comments here will be passed to htmlentities():<br/>';
print '<input type="text" name="text22" maxlength="300"
value="' . htmlentities($GLOBALS['defaults']['text22']) . '" size="76"/><br/>';
print '<input type="submit" value="Submit!"/>';
print '<input type="hidden" name="_submit_check2" value="1"/>';
print '</form>';
}
function validate_form2() {
$errors = array();
$GLOBALS['comments12'] = strip_tags($_POST['text12']);
$GLOBALS['comments22'] = htmlentities($_POST['text22']);
if (strlen($GLOBALS['comments12']) < 10) {
$errors[] = 'The comment must have at least 10 characters long.';
}
if (strlen(trim($GLOBALS['comments12'])) == 0) {
$errors[] = 'You must enter a comment.';
}
if (strlen($GLOBALS['comments22']) < 10) {
$errors[] = 'The comment must have at least 10 characters long.';
}
if (strlen(trim($GLOBALS['comments22'])) == 0) {
$errors[] = 'You must enter a comment.';
}
return $errors;
}
?>
Your comments here will be passed to strip_tags():

Your comments here will be passed to htmlentities():