PHP Arrays and HTML Forms
PHP Arrays and HTML Forms
2
Introduction
• An array is traditionally defined as a group of items that share certain
characteristics, such as similarity (car models, football teams, types of
fruit, etc.) and type (e.g., all strings or integers).
• Each item is distinguished by a special identifier known as a key (also
referred to as index), which is used to access the item in the array
• Some arrays are referenced by numeric indices; others allow
alphanumeric identifiers.
• PHP has Built-in functions that let you sort them, add or remove
sections, and process them to handle each item through a special
kind of loop.
3
Numerically indexed arrays [1/6]
• Assume that you have been tasked with creating a simple website for
a local office-supply company and you are currently working on the
section devoted to paper.
• One way to manage the various items of stock in this category would
be to place them in a numeric array.
• The simplest way of doing so is shown on next slide.
4
Numerically indexed arrays [2/6]
<?php
$paper[] = "Copier";
$paper[] = "Inkjet";
$paper[] = "Laser";
$paper[] = "Photo";
print_r($paper);
?>
• In this example, each time a value is assigned to the array $paper, the
first empty location within that array is used to store the value, and a
pointer internal to PHP is incremented to point to the next free
location, ready for future insertions.
5
Numerically indexed arrays [3/6]
• The previous code could also have been written as shown below,
where the exact location of each item within the array is specified.
<?php
$paper[0] = "Copier";
$paper[1] = "Inkjet";
$paper[2] = "Laser";
$paper[3] = "Photo";
print_r($paper);
?>
• The output from these examples is identical
6
Numerically indexed arrays [4/6]
• The print_r function (which prints out the contents of a variable,
array, or object) prints out the following:
Array
(
[0] => Copier
[1] => Inkjet
[2] =>Laser
[3] =>Photo
)
• Note that the print_r function is not appropriate for printing out
elements on a developed website. The function is meant for the
programmer to learn about a variable.
7
Numerically indexed arrays [5/6]
• Below is an example of how to print out the elements of the array
using a for loop:
<?php
$paper[] = "Copier";
$paper[] = "Inkjet";
$paper[] = "Laser";
$paper[] = "Photo";
for ($j = 0 ; $j < 4 ; ++$j)
echo "$j: $paper[$j]<br>";
?>
• Task: what is the output of the above code?
8
Numerically indexed arrays [6/6]
• This example prints out the following:
0: Copier
1: Inkjet
2: Laser
3: Photo
• Keeping track of array elements by index works just fine but can
require extra work in terms of remembering which number refers to
which product.
• It can also make code hard for other programmers to follow.
• The next slide introduces the alternative to numerically indexed
arrays.
9
Associative arrays [1/3]
• Using associative arrays, items can be referenced by name rather than by
number.
• The following example expands on the previous code by giving each
element in the array an identifying name and a longer, more explanatory
string value.
<?php
$paper['copier'] = "Copier & Multipurpose";
$paper['inkjet'] = "Inkjet Printer";
$paper['laser'] = "Laser Printer";
$paper['photo'] = "Photographic Paper";
echo $paper['laser'];
?>
• Task: determine the output of the above code
10
Associative arrays [2/3]
• In the previous slide, in place of a number (which doesn’t convey any
useful information, aside from the position of the item in the array),
each item now has a unique name that can be used to reference it
elsewhere.
• The echo statement in the example prints out: Laser Printer.
• The names (copier, inkjet, and so on) are called indexes or keys, and
the items assigned to them (such as Laser Printer) are called values.
11
Associative arrays [3/3]
• This feature of PHP is often used when extracting information from
XML and HTML. For example, an HTML parser such as those used by a
search engine could place all the elements of a web page into an
associative array whose names reflect the page’s structure:
$html['title'] = "My web page";
$html['body'] = "... body of web page ...";
• This kind of program would also probably break down all the links
found within a page into another array, and all the headings and
subheadings into another.
• Generally using associative rather than numeric arrays, the code to
refer to the items is easier to write and debug.
12
Assignment using the array keyword
• Another method of assigning array values is to use the array keyword.
• The array keyword can be used for both numeric and an associative array
assignment as shown below:
<?php
$p1 = array("Copier", "Inkjet", "Laser", "Photo");
13
Assignment using the array keyword
• In the previous example, the first line assigns the old, shortened
product descriptions to the array $p1. There are four items assigned
to $p1, so they will occupy slots 0 through 3. Therefore, the echo
statement prints out the following:
p1 element: Laser
• In the second half of the code, $p2 is assigned values using
associative identifiers and accompanying longer product
descriptions using the format index => value.
• The use of => is similar to the regular = assignment operator, except
that the value is assigned to an index and not to a variable.
14
Assignment using the array keyword
• The index is then inextricably linked with that value, unless it is
assigned a new value.
• The second echo command in the previous code therefore prints out
this:
p2 element: Inkjet Printer
• You can verify that $p1 and $p2 are different types of array, because
both of the following commands, when appended to the code, will
cause an Undefined index or Undefined offset error, as the array
identifier for each is incorrect:
echo $p1['inkjet']; // Undefined index
echo $p2[3]; // Undefined offset
15
<intentionally left blank>
16
The foreach...as loop [1/7]
• The foreach...as loop is a PHP loop provided especially for arrays.
• It can be used to step through array elements, one at a time.
• Below is an example of how foreach...as can be used:
<?php
$paper = array("Copier", "Inkjet", "Laser", "Photo");
$j = 0;
foreach($paper as $item)
{
echo "$j: $item<br>";
++$j;
}
?>
17
The foreach...as loop [2/7]
• The process starts with the first item and ends with the last one, so
no need to even know how many items there are in an array.
• When PHP encounters a foreach statement, it takes the first item of
the array and places it in the variable following the as keyword; and
each time control flow returns to the foreach, the next array element
is placed in the as keyword.
• In the previous example, the variable $item is set to each of the four
values in turn in the array $paper. Once all values have been used,
execution of the loop ends.
18
The foreach...as loop [3/7]
• The output from this code is as follows:
0: Copier
1: Inkjet
2: Laser
3: Photo
• Below is an example of how foreach works with an associative array:
<?php
$paper = array('copier' => "Copier & Multipurpose",
'inkjet' => "Inkjet Printer",
'laser' => "Laser Printer",
'photo' => "Photographic Paper");
foreach($paper as $item => $description)
echo "$item: $description<br>";
?>
19
The foreach...as loop [4/7]
• Remember that associative arrays do not require numeric indexes, so
the variable $j is not used in this example.
• Instead, each item of the array $paper is fed into the key/value pair of
variables $item and $description, from which they are printed out.
• The displayed result of this code is as follows:
copier: Copier & Multipurpose
inkjet: Inkjet Printer
laser: Laser Printer
photo: Photographic Paper
20
The foreach...as loop [5/7]
• As an alternative syntax to foreach...as, you can use the list function in conjunction with
the each function, as shown below
<?php
$paper = array('copier' => "Copier & Multipurpose",
'inkjet' => "Inkjet Printer",
'laser' => "Laser Printer",
'photo' => "Photographic Paper");
21
The foreach...as loop [6/7]
• The list function takes an array as its argument (in this case, the
key/value pair returned by the function each) and then assigns the
values of the array to the variables listed within parentheses.
• To understand how list works a little more clearly consider the
example in next slide, where an array is created out of the two strings
Alice and Bob and then passed to the list function, which assigns
those strings as values to the variables $a and $b.
22
The foreach...as loop [7/7]
• Using the list function:
<?php
list($a, $b) = array('Alice', 'Bob');
echo "a=$a b=$b";
?>
• The output from this code is as follows:
a=Alice b=Bob
• When working with arrays, you can use the foreach...as, or use the
each function and create your own method of looping.
23
<intentionally left blank>
24
Multidimensional arrays [1/10]
• PHP’s array syntax makes it possible to create arrays of more than one
dimension.
• Multidimensional arrays are created by including an entire array as a
part of another one.
• The dimensions can be as many as desired, however most application
do not require going further than three dimensions.
• The next slide gives code snippet, an extension of the previous
example to show how multidimensional arrays work.
25
Multidimensional arrays [2/10]
$products = array(
'paper' => array(
'copier' => "Copier & Multipurpose",
'inkjet' => "Inkjet Printer",
'laser' => "Laser Printer",
'photo' => "Photographic Paper"),
'pens' => array(
'ball' => "Ball Point",
'hilite' => "Highlighters",
'marker' => "Markers"),
'misc' => array(
'tape' => "Sticky Tape",
'glue' => "Adhesives",
'clips'=> "Paperclips"
)
);
26
Multidimensional arrays [3/10]
• In this example (previous slide), the main array is now called $products.
Within this array, there are three items, namely paper, pens, and misc -
each of which contains another array with key/value pairs.
• Once the array data has been assigned, a pair of nested foreach...as loops
can be used to print out the various values a shown below:
echo "<pre>";
foreach($products as $section => $items)
foreach($items as $key => $value)
echo "$section:\t$key\t($value)<br>";
echo?> "</pre>";
27
Multidimensional arrays [4/10]
• The important thing to remember is that each level of the array works
the same way (it’s a key/value pair). With that in mind you can easily
write code to access any element at any level.
• In the previous code snippet, The echo statement makes use of the
PHP escape character \t, which outputs a tab.
• Tabs are normally not significant to the browser. Therefore, notice the
use of <pre>...</pre> tags, which tells the web browser to format the
text as preformatted and monospaced, and not to ignore whitespace
characters such as tabs and line feeds.
28
Multidimensional arrays [5/10]
The output from this code looks like the following:
paper: copier (Copier & Multipurpose)
paper: inkjet (Inkjet Printer)
paper: laser (Laser Printer)
paper: photo (Photographic Paper)
pens: ball (Ball Point)
pens: hilite (Highlighters)
pens: marker (Markers)
misc: tape (Sticky Tape)
misc: glue (Adhesives)
misc: clips (Paperclips)
29
Multidimensional arrays [6/10]
• A particular element of the array can be accessed directly by using
square brackets as shown below:
echo $products['misc']['glue'];
• This outputs the value: Adhesives.
• Alternatively numeric multidimensional arrays can be created that are
accessed directly by indexes rather than by alphanumeric identifiers.
• The example in the next slide creates the board for a chess game with
the pieces in their starting positions.
30
Multidimensional arrays [7/10]
Example: creating a multidimensional numeric array.
$chessboard = array(
array('r', 'n', 'b','q','k','b','n','r'),
array('p','p', 'p','p','p','p','p','p'),
array(' ', ' ', ' ',' ',' ',' ',' ',' '),
array(' ', ' ', ' ',' ',' ',' ',' ',' '),
array(' ', ' ', ' ',' ',' ',' ',' ',' '),
array(' ', ' ', ' ',' ',' ',' ',' ',' '),
array('P', 'P', 'P','P','P','P','P','P'),
array('R','N', 'B','Q','K','B','N','R'),
);
31
Multidimensional arrays [8/10]
• In this example, the lowercase letters represent white pieces, and the
uppercase black. The key is r = rook, n = knight, b = bishop, k = king, q =
queen, and p = pawn.
• Again, a pair of nested foreach...as loops can be used to step through the
array and displays its contents as shown below.
echo "<pre>";
foreach($chessboard as $row)
{
foreach ($row as $piece)
echo "$piece ";
echo "<br>";
}
echo "</pre>
32
Multidimensional arrays [9/10]
• In the previous code snippet, the outer loop processes each row into
the variable $row, which itself is an array, because the $chessboard
array uses a subarray for each row. This loop has two statements
within it, so curly braces enclose them.
• The inner loop then processes each square in a row, outputting the
character ($piece) stored in it, followed by a space (to square up the
printout). This loop has a single statement, so curly braces are not
required to enclose it.
• The <pre> and </pre> tags ensure that the output displays correctly.
33
Multidimensional arrays [10/10]
• The output looks like this:
rnbqkbnr
pppppppp
PPPPPPPP
RNBQKBNR
• Any element within this array can be accessed by using square
brackets as shown below:
echo $chessboard[7][3];
• This statement outputs the uppercase letter Q, the eighth element
down and the fourth along (remembering that array indexes start at
0, not 1).
34
Using array functions [1/10]
• Besides the list and each functions, PHP comes with numerousother
functions for handling arrays.
is_array
• Arrays and variables share the same namespace. This means that you
cannot have a string variable called $fred and an array also called $fred.
• When in doubt and the code needs to check whether a variable is an array,
the is_array function can be used, like this:
echo (is_array($fred)) ? "Is an array" : "Is not an array";
• Note that if $fred has not yet been assigned a value, an Undefined variable
message will be generated.
35
Using array functions [2/10]
count
• The count function can be used to count all the elements in the top
level of an array as follows:
echo count($fred);
• To know how many elements there are altogether in a
multidimensional array, count can be used as follows:
echo count($fred, 1);
• The second parameter is optional and sets the mode to use. It should
be either a 0 to limit counting to only the top level, or 1 to force
recursive counting of all subarray elements too.
36
Using array functions [3/10]
sort
• The sort function is used to sort elements of an array. In its simplest
form, it can be used as follows:
sort($fred);
• Unlike some other functions, sort will act directly on the supplied
array rather than returning a new array of sorted elements.
• To force sorting to be made either numerically or as strings:
sort($fred, SORT_NUMERIC);
sort($fred, SORT_STRING);
37
Using array functions [4/10]
rsort
• The rsort function is a variant of sort. It can be used to sort an array in
reverse order as shown below:
rsort($fred, SORT_NUMERIC);
rsort($fred, SORT_STRING);
shuffle
• The shuffle function can be used to put elements of an array in
random order. Usage: shuffle($cards);
• Like sort, shuffle acts directly on the supplied array and returns TRUE
on success or FALSE on error.
38
Using array functions[5/10]
explode
• Given a string containing several items separated by a single character (or
string of characters), the explode function can be used to take such a string
and place each of the items into an array.
• One handy example is to split up a sentence into an array containing all its
words, as below:
<?php
$temp = explode(' ', "This is a sentence with seven words");
print_r($temp);
?>
• The first parameter specifies the character(s) separating the item. In this
example, the items are separated by space hence the ' '
39
Using array functions [6/10]
extract
• The extract function is used to turn the key/value pairs from an array into
PHP variables. Assuming we have an associative array called $_GET, the
extract function can be used as follows:
extract($_GET);
• One danger with this approach is that, if any extracted variables conflict
with ones that you have already defined, your existing values will be
overwritten. To avoid this possibility, one of the many additional
parameters available to this function can be used, like this:
extract($_GET, EXTR_PREFIX_ALL, 'fromget');
• In this case, all the new variables will begin with the given prefix string
followed by an underscore. So in this example $q will become $fromget_q.
40
Using array functions [7/10]
compact
• The compact function does the inverse of extract function: it creates
an array
$fname = "Doctor";
$sname = "Who";
$planet = "Gallifrey";
$system = "Gridlock";
$constellation ="Kasterborous";
$contact = compact('fname', 'sname', 'planet', 'system', 'constellation');
• Note how compact requires the variable names to be supplied in
quotes, not preceded by a $ symbol.
41
Using array functions [8/10]
reset
• When the foreach...as construct or the each function walks through
an array, it keeps an internal PHP pointer that makes a note of which
element of the array it should return next.
• If the code ever needs to return to the start of an array, reset can be
issued, which also returns the value of that element.
• Examples of how to use this function are as follows:
reset($fred); // Throw away return value
$item = reset($fred); // Keep first element of the array in $item
42
Using array functions [9/10]
end
• The end function can be used to move PHP’s internal array pointer to
the final element in an array, which also returns the value of the
element.
• Examples of how to use it is as follows:
end($fred);
$item = end($fred);
43
Using array functions [10/10]
Note
The array functions looked at so far are just some of the fundamental
ones. For the full list, visit http://tinyurl.com/arraysinphp
44
<intentionally left blank>
45
Form handling
• Web forms provide a way to interact with the user.
• Forms are used to collect data from a user, which can then be passed
to PHP for further processing.
• Handling forms is a multipart process: first a form is created, into
which a user can enter the required details. This data is then sent to
the web server, where it is interpreted, often with some error
checking. If the PHP code identifies one or more fields that require
reentering, the form may be redisplayed with an error message.
• When the code is satisfied with the accuracy of the input, it takes
some action
46
Creating forms[1/4]
• To build a form, the following elements are required:
- An opening <form> and closing </form> tag
- A submission type specifying either a Get or Post method
- One or more input fields
- The destination URL to which the form data is to be submitted
• The next slide shows a very simple form created with PHP, which you
should type in and save as formtest.php.
47
Creating forms [2/4]
A simple PHP form handler
<?php // formtest.php
echo <<<_END
<html>
<head>
<title>Form Test</title>
</head>
<body>
<form method="post" action="formtest.php">
What is your name?
<input type="text" name="name">
<input type="submit">
</form>
</body>
</html>
_END;
?>
48
Creating forms [3/4]
• The first thing to notice in the example(next slide) is the use of the echo
<<<_END..._END construct. It is used whenever multiline HTML must be
output.
• Inside of this multiline output is some standard code for commencing an
HTML document, displaying its title, and starting the body of the
document.
• This is followed by the form, which is set to send its data using the Post
method to the PHP program formtest.php, which is the name of the
program itself.
• The rest of the program just closes all the items it opened: the form, the
body of the HTML document, and the PHP echo <<<_END statement
49
Creating forms [4/4]
• The result of opening formtest.php in a web browser is shown.
50
Retrieving submitted data [1/4]
• As formtest.php is, if a name is entered and the Submit Query button
is clicked, nothing happens other than the form being redisplayed.
• To expand on the previous example, type in the example on next slide
and save it as formtest2.php, and try running it.
51
Retrieving submitted data [2/4]
Updated version of formtest.php
<?php // formtest2.php
echo <<<_END
<html >
<hea d>
<title>Form Test</title>
</hea d>
<body>
<input type="submit">
</form>
</body>
</html >
_END;
52
?>
Retrieving submitted data [3/4]
• Notice the few changes made to formtest.php: a couple of lines at the
start that check the $_POST associative array for the field name
having been submitted.
• $_POST is associative array, which contains an element for each field
in an HTML form.
• In the example, the input name used was name and the form method
was Post, so element name of the $_POST array contains the value in
$_POST['name'].
• Note that post is an inbuilt method used when working with forms
53
Retrieving submitted data [4/4]
• The PHP isset function is used to test whether $_POST['name'] has
been assigned a value. If nothing was posted, the program assigns the
value "(Not entered)"; otherwise, it stores the value that was entered.
• Then a single line has been added after the <body> statement to
display that value, which is stored in $name.
• Notice how the <input> elements in this example do not use the />
form of self-closing, because in this version of HTML, this style is
optional.
54
Default values [1/4]
• Sometimes it is convenient to offer users a default value in a web
form.
• For example, suppose you put up a loan repayment calculator widget
on a real estate website. It could make sense to enter default values
of, say, 25 years and 6 percent interest, so that the user can simply
type either the principle sum to borrow or the amount that she can
afford to pay each month.
• In this case, the HTML for those two values would be something like
what is shown in next slide
55
Default values [2/4]
Setting default values:
<form method="post" action="calc.php"><pre>
Loan Amount <input type="text" name="principle">
Monthly Repayment <input type="text" name="monthly">
Number of Years <input type="text" name="years" value="25">
Interest Rate <input type="text" name="rate" value="6">
<input type="submit">
</pre></form>
56
Default values [3/4]
• To try this code snippet on previous slide, type it in and save it with
an .html file extention, such as test.html, and then load the file into
your browser.
• By populating the value attribute, a default value will display in the
field, which the users can then change if they wish.
• With sensible default values, the web forms can be made more user-
friendly by minimizing unnecessary typing.
57
Default values [4/4]
• The result of the previous code looks as shown below.
• The code snippet was to illustrate default values and, because the
program calc.php has not been written, the form will not do anything
if submitted.
58
<intentionally left blank>
59
Input types [1/20]
• HTML forms are very versatile and allow you to submit a wide range of
input types, from text boxes and text areas to checkboxes, radio buttons,
and more.
Text boxes
• Text boxes accept a wide range of alphanumeric text and other characters
in a single-line box.
• The general format of a text box input is as follows:
<input type="text" name="name" size="size" maxlength="length" value="value">
• The size attribute specifies the width of the box (in characters of the
current font), and maxlength specifies the maximum number of characters
that a user is allowed to enter into the field.
60
Input types [2/20]
Text areas
• Text areas are used when it is necessary to accept input of more
than a short line of text.
• This is similar to a text box, but, because it allows multiple lines, it has
some different attributes.
• Its general format looks like this:
<textarea name="name" cols="width" rows="height" wrap="type"> </textarea>
• Notice that <textarea> has its own tag and is not a subtype of the
<input> tag. It therefore requires a closing </textarea> to end input.
61
Input types [3/20]
• If there is default text to display in the text area, it must be put before
the closing </textarea>, as shown below:
<textarea name="name" cols="width" rows="height" wrap="type">
This is some default text.
</textarea>
• The default text will then be displayed and be editable by the user.
• The cols and rows attributes are used to control the width and height
of the text area. Both use the character spacing of the current font to
determine the size of the area. If these values are omitted, a default
input box will be created that will vary in dimensions depending on
the browser used.
62
Input types [4/20]
• The wrap attribute of the text area is used to control how the text
entered into the box will wrap, and how any such wrapping will be
sent to the server
• The wrap types available are:
Type Action
off Text does not wrap, and lines appear exactly as the user types them.
soft Text wraps but is sent to the server as one long string without carriage returns and line
feeds.
hard Text wraps and is sent to the server in wrapped format with soft returns and line feeds.
63
Input types [5/20]
Checkboxes
• Checkboxes are used to offer a number of different options to a user,
from which they can select one or more items.
• The format to use a checkbox is as follows:
<input type="checkbox" name="name" value="value" checked="checked">
• If the checked attribute is included, the box is already checked when
the browser is displayed. The string you assign to the attribute should
be either a double quote or the value "checked", or there should be
no value assigned.
• If the checked attribute is not included, the box is shown unchecked.
64
Input types [6/20]
• Here is an example of creating an unchecked box:
I Agree <input type="checkbox" name="agree">
• To allow groups of items to be selected at one time, they all have to
be assigned the same name as illustrated below, however, note that
only the last item checked will be submitted, unless you pass an array
as the name:
Vanilla <input type="checkbox" name="ice" value="Vanilla">
Chocolate <input type="checkbox" name="ice" value="Chocolate">
Strawberry <input type="checkbox" name="ice" value="Strawberry">
65
Input types [7/20]
• The output of the previous code snippet is as shown below.
• If only one of the checkboxes is selected, such as the second one, only
that item will be submitted (the field named ice would be assigned
the value "Chocolate"). But if two or more are selected, only the last
value will be submitted, with prior values being ignored.
66
Input types [8/20]
• To allow multiple submissions, you have to slightly alter the HTML
and pass the array as the name, as shown below:
Vanilla <input type="checkbox" name="ice[]" value="Vanilla">
Chocolate <input type="checkbox" name="ice[]" value="Chocolate">
Strawberry <input type="checkbox" name="ice[]" value="Strawberry">
• Now, when the form is submitted, if any of these items have been
checked, an array called ice will be submitted that contains any and all
values.
• In each case, the single submitted value, or the array of values can be
extracted to a variable like this:
$ice = $_POST['ice'];
67
Input types [9/20]
• If the field ice has been posted as a single value, $ice will be a single
string, such as "Strawberry". But if ice was defined in the form as an
array, $ice will be an array, and its number of elements will be the
number of values submitted.
• If $ice is an array, its contents can be displayed using the foreach PHP
construct as shown below:
foreach($ice as $item) echo "$item<br>";
• The <br> is just an HTML formatting device to force a new line after
each iteration.
68
Input types [10/20]
Radio buttons
• Radio buttons are used when you want only a single value to be
returned from a selection of two or more options.
• All the buttons in a group must use the same name and, because only
a single value is returned, there is no need to pass an array.
• For example, imagine a website that offers a choice of delivery times
for items purchased from the store, HTML might be used as illustrated
in next.
69
Input types [11/20]
• Using radio buttons:
8am-Noon<input type="radio" name="time" value="1">
Noon-4pm<input type="radio" name="time" value="2" checked="checked">
4pm-8pm<input type="radio" name="time" value="3">
• Notice in the above example, the second option of Noon–4pm has
been selected by default. This default choice ensures that at least one
delivery time will be chosen by the user, which they can change to
one of the other two options if they prefer.
70
Input types [12/20]
Hidden fields
• Hidden form fields are a convenient way of keeping track of the state
of the form entry. For example, to know whether a form has already
been submitted.
• This is achieved by adding some HTML in the PHP code, such as the
following:
echo '<input type="hidden" name="submitted" value="yes">'
• This PHP echo statement that adds an input field to the HTML form.
71
Input types [13/20]
• Assuming the form was created outside the program and displayed to the
user. The first time the PHP program receives the input, this line of code
has not run, so there will be no field named submitted.
• The PHP program re-creates the form, adding the input field. So when the
visitor resubmits the form, the PHP program receives it with the submitted
field set to "yes".
• The code can simply check whether the field ispresent:
if (isset($_POST['submitted']))
{...
• Hidden fields can also be useful for storing other details, such as a session
ID string that might be created to identify a user, and so on.
72
Input types [14/20]
<select>
• The <select> tag is used to create a drop-down list of options, offering
either single or multiple selections.
• It conforms to the following syntax:
<select name="name" size="size" multiple="multiple">
• The attribute size is the number of lines to display.
• Clicking on the display causes a list to drop down, showing all the
options. If the multiple attribute is used, a user can select multiple
options from the list by pressing the Ctrl key when clicking.
73
Input types [15/20]
• So to ask a user for their favorite vegetable from a choice of five, the
HTML to use might be as shown below:
Vegetables
<select name="veg" size="1">
<option value="Peas">Peas</option>
<option value="Beans">Beans</option>
<option value="Carrots">Carrots</option>
<option value="Cabbage">Cabbage</option>
<option value="Broccoli">Broccoli</option>
</select>
74
Input types [16/20]
• This HTML (previous slide) offers five choices, with the first one, Peas,
preselected (due to it being the first item).
• The output below shows the list clicked to drop it down, and the
option Carrots highlighted.
75
Input types [17/20]
• To allow users to select more than one item, the multiple attribute can be
used as shown below:
Vegetables
<select name="veg" size="5" multiple="multiple">
<option value="Peas">Peas</option>
<option value="Beans">Beans</option>
<option value="Carrots">Carrots</option>
<option value="Cabbage">Cabbage</option>
<option value="Broccoli">Broccoli</option>
</select>
• Notice that the HTML is not very different; only the size has been changed
to "5" and the attribute multiple has been added.
76
Input types [18/20]
As shown below, it is now possible for the user to select more than one
option by using the Ctrl key.
77
Input types [19/20]
Labels
• The <label> tags can be utilised to improve the user experience.
• With it a form can be surrounded, making it selectable by clicking any
visible part contained between the opening and closing <label> tags.
• For example, going back to the example of choosing a delivery time,
you could allow the user to click the radio button itself and the
associated text, like this:
<label>8am-Noon<input type="radio" name="time" value="1"></label>
78
Input types [20/20]
• Using the <label> tags will not underline the text like a hyperlink, but
when the mouse passes over, it will change to an arrow instead of a text
cursor, indicating that the whole item is clickable.
79
Sanitizing input [1/5]
• Sanitizing input refers to the constraints put in an HTML form to limit
the type and size of input a user can enter.
• A user can intentionally or accidentally populate the form with
something that could interfere with the site.
• Thus any variable fetched either with $_GET or $_POST arrays must
be processed to ensure the input is "clean".
• Therefore, instead of just using code such as the following when
reading in user input:
$variable = $_POST['user_input'];
80
Sanitizing input [2/5]
One or more of the following lines of code should be used
• For example, to prevent escape characters from being injected into a string
that will be presented to MySQL, use the following:
$variable = $connection->real_escape_string($variable);
• To get rid of unwanted slashes, use this:
$variable = stripslashes($variable);
• And to remove any HTML from a string, use the following:
$variable = htmlentities($variable);
This would change a string of interpretable HTML code like <b>hi</b> into
<b>hi</b>, which displays as text, and won’t be interpreted as
HTML tags.
81
Sanitizing input [3/5]
• To strip HTML entirely from an input, use the following (but ensure
you use it before calling htmlentities, which replaces any angle
brackets used as part of HTML tags):
$variable = strip_tags($variable);
• The next slide shows a pair of functions that bring all the checks
together to provide a good level of security.
82
Sanitizing input [4/5]
<?php
function sanitizeString($var)
{
$var = stripslashes($var);
$var = strip_tags($var);
$var = htmlentities($var);
return $var;
}
function sanitizeMySQL($connection, $var)
{
$var = $connection->real_escape_string($var);
$var = sanitizeString($var);
return $var;
}
?>
83
Sanitizing input [5/5]
• The code in previous slide should be added to the end of the PHP
program, and can then then be called for each user input to sanitize
as follows:
$var = sanitizeString($_POST['user_input']);
• Or, when there is an open MySQL connection, and a mysqli
connection object (in this case, called $connection):
$var = sanitizeMySQL($connection, $_POST['user_input']);
84
An example program
For a basic example of sanitizing input, see convert.php under sample
code.
85
What is new in HTML5?
• HTML5 provides a number of useful enhancements to form handling,
including new attributes; color, date, and time pickers; and new input
types,
• But note that some HTML5 features are yet to be supported across all
major browsers.
• The following are some of the new features that will work on all
browsers.
86
The autocomplete attribute
• The autocomplete attribute can be applied to either the <form> element,
or to any of the color, date, email, password, range, search, tel, text, or url
types of the <input> element.
• With autocomplete enabled, previous user inputs are recalled and
automatically entered into fields as suggestions.
• This feature can also be disabled by turning autocomplete off.
• Here’s how to turn autocomplete on for an entire form but disable it for
specific fields (highlighted in bold):
<form action='myform.php' method='post' autocomplete='on'>
<input type='text' name='username'>
<input type='password' name='password' autocomplete='off'>
</form>
87
The autofocus attribute
• The autofocus attribute gives immediate focus to an element when a
page loads. It can be applied to any <input>, <textarea>, or <button>
element, like this:
<input type='text' name='query' autofocus='autofocus'>
• Note: browsers that use touch interfaces (such as Android, iOS, or
Windows Phone) usually ignore the autofocus attribute,
88
The placeholder attribute
• The placeholder attribute lets you place into any blank input field a
helpful hint to explain to users what they should enter. You use it like
this:
<input type='text' name='name' size='50' placeholder='First & Last name'>
• The input field will display the placeholder text as a prompt until the
user starts typing, at which point the placeholder will disappear.
89
The required attribute
• The required attribute is used to ensure that a field has been
completed before a form is submitted. You use it like this:
<input type='text' name='creditcard' required='required'>
• When the browser detects attempted form submission where there’s
an uncompleted required input, a message is displayed, prompting
the user to complete the field.
90
Override attributes
• With override attributes, you can override form settings on an
element-by-element basis.
• So, for example, using the formaction attribute, you can specify that a
submit button should submit a form to a different URL than is
specified in the form itself, like the following (in which the default and
overridden action URLs are bold):
<form action='url1.php' method='post'>
<input type='text' name='field'>
<input type='submit' formaction='url2.php'>
</form>
91
The width and height attributes
• Using these new attributes, you can alter the dimensions of an input
image, like this:
<input type='image' src='picture.png' width='120' height='80'>
92
The form attribute
• HTML5 no longer requires <input> elements to be placed within <form>
elements, because the form to which an input applies can be specified by
supplying a form attribute. The following code shows a form being created,
but with its input outside of the <form> and </form> tags:
• To do this, the form must be given an ID using the id attribute, and this is
the ID to which the form attribute of an input element must refer.
• Note: at the time of writing, this attribute is unsupported by Internet Explorer.
93
End
94