CHAPTER 7
HTML Forms and Server Side Scripting
Outline
Introduction
Use Conditionals and Operators
Validate Form Data
Send Values to a Script Manually
Work with Forms and arrays of data
Use For and While Loops
Create a Simple Form using PHP
Use Get or Post
Receive Data from a Form in PHP
Introduction to regular expression
Introduction
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 tag looks like the following:
<form method=“ “ action=“ “ > … </form>
Introduction …
The attributes of the form tag:
Method –dictates how the data is sent to the handling page.
Can be ‘Post’ or ‘Get’
Action -dictates to which page the form data will be sent.
To handle HTML form – We will start with the HTML
form we have created, and its elements
Value stored in the ‘name’ attribute of any form element is
captured by the PHP code
The type of method used is very important otherwise use
$_REQUEST[ ]
HTML form code
Output of the HTML form
HTML Form Handling
Data entered to the form elements will be sent to
the server side script written as value of action
attribute.
1. The server side script (PHP) first gets all the input
info from the form
2. Secondly, processes the received input info inside the
PHP code
3. Finally, generates an output depending on the user
queries, may be from backend server
…cont’d…
To get all the input info from the form above
<input type="text" name="name" size="20">
$_REQUEST[‘name’]; or $_GET[‘name’];
<input type="text" name="email" size="30">
$_REQUEST[‘email’]; or $_GET[‘email’];
<input type="radio" name="gender" value="male">
<input type="radio" name="gender" value="female">
$_REQUEST[‘gender’]; or $_GET[‘gender’];
…cont’d…
For Select element
<select name="age">
<option value="0-29">Under 30</option>
<option value="30-60">Between 30 and60</option>
<option value="60+">Above 60</option>
</select>
$_REQUEST[‘age’] or $_GET[‘age’];
…cont’d…
For Textarea
<textarea name="comment" cols="30“ rows="5">
</textarea>
$_REQUEST[‘comment’]; or $_GET[‘comment’];
Note: PHP is strictly case-sensitive when it
comes to value of ‘name’ attribute.
$_REQUEST[‘Comment’]; …doesn’t work
$_REQUEST[‘comment’]; …Correctly works
$_Request[‘comment’]; …doesn’t work
…cont’d…
As an option you can create the following kind of
table
HTML Form elements name PHP Syntax to get the input info
value
name $_REQUEST[‘name’]
email $_REQUEST[‘email’]
gender $_REQUEST[‘gender’]
age $_REQUEST[‘age’]
comment $_REQUEST[‘comment’]
btnS $_REQUEST[‘btnS’]
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:
An if can also have an else clause:
…cont’d…
An elseif clause allows you to add more
conditions:
A condition can be true in PHP for any number of
reasons.
…cont’d…
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.
isset( ) – is function which checks if a variable is set
or if it contains a value other than NULL
NULL – represents not set value
…cont’d…
PHP has another type of conditional, called the
switch, best used in place of a long if-elseif-else
conditional
…cont’d …[Operators]
…cont’d…
Example of using conditionals:
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.
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 (including 0, FALSE, or an
empty string, but not NULL).
…cont’d…
One issue with the isset( ) function is that an empty
string tests as true,
isset( ) is not an effective way to validate text inputs and
text boxes
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.
The first aim of form validation is seeing if something
was entered or selected in form elements.
…cont’d…
The second goal is to ensure that submitted data is
of the right type (numeric, string, etc.),
of the right format (like an email address),
or a specific acceptable value (like $gender being
equal to either M or F ).
Validation example for the previous form
…cont’d…
…cont’d…
…cont’d…
Send Values to a Script Manually
We can send values to a PHP page without the use of
the form manually.
Normally you’d do so by creating links:
<a href="page.php?id=22">Some Link</a>
That link, which could be dynamically generated by
PHP, will pass the value 22 to page.php, accessible in
$_GET['id'].
This is a very important mechanism to perform data
update or deletion for a list of database table entries.
…cont’d…
Example
…cont’d…
Access the manually sent values in php as follows:
Work with Forms and arrays of data
Arrays are structured as a series of key value pairs.
PHP supports two kinds of arrays:
indexed, which use numbers as the keys, and
associative, which use strings as keys
An array follows the same naming rules as any other variable.
Creating array
1. Add Element at a time e.g: $band[ ]=‘Jano’;
2. Entire array at a time e.g: $artists=
array(‘Netsanet’,’Solomon’,’Samson’);
3. Sequential numbers e.g: $ten=range(1,10);
…cont’d…
Accessing arrays
$langs=array(‘html’,’css’,’js’,’php’);
$langs[0]=‘html’ and $langs[3]=‘php’; //indexing
Use loops to access all elements
Foreach loop or other looping statements
foreach($langs as $lang) { //if keys are not needed
echo $lang.”<br>”;
}
foreach($langs as $key=>$lang){ //if keys are needed
echo “Element at Index $key is $lang <br>”;
}
…cont’d…
Can be used to create the following kinds of form
elements
…cont’d…
Create the months array
$months = array (1 => 'January', 'February', 'March', 'April', 'May',
'June', 'July', 'August', 'September', 'October','November',
'December');
Create the arrays for the days of the month and the years
$days = range (1, 31);
$years = range (2000, 2011);
Generate the month pull-down menu:
echo '<select name="month">';
foreach ($months as $key => $value) {
echo "<option value=\"$key\”>$value</option>\n";
}
echo '</select>‘;
…cont’d…
Generate the day and year pull-down menus:
echo '<select name="day">';
foreach ($days as $value) {
echo "<option value=\"$value\">$value</option>\n";
}
echo '</select>';
echo '<select name="year">';
foreach ($years as $value) {
echo "<option value=\"$value\"> $value</option>\n";
}
echo '</select>';
…cont’d…
Array tips:
count( ) – is used to count array elements
e.g: $n=count($array);
range( ) – can also create a sequence of letters e.g:
$letters=range(‘a’,’z’);
is_array( ) – tests if a variable is an array
e.g: $r=is_array($letters);
$_GET, $_POST, $_REQUEST, $_SERVER, $_ENV, $_SESSION,
and $_COOKIE are super global arrays.
Read about multidimensional arrays
Use For and While Loops
The while loop looks like this:
while (condition) {
// Do something.
}
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.
}
for loop is a better choice for doing something a known number of
times, whereas while is used when a condition will be true an
unknown number of times.
Create a Simple Form using PHP
The following shows a simple php form
Reading assignment: Sticky form
Use Get or Post
When deciding which method to use, keep
in mind these four factors:
1. With the GET method, a limited amount of information
can be passed
2. The GET method sends the data to the handling script
publicly
3. A page generated by a form that used the GET method can
be bookmarked, but one based on POST can’t be
4. Users will be prompted if they attempt to reload a page
accessed via POST ,but will not be prompted for pages
accessed via GET
Receive Data from a Form in PHP
To receive a form data in PHP, use the following
information
The type of method used in the form tag: get or post?
e.g: <form action=“ “ method=“get” >
Use the value stored in the name attribute of the form
elements.
e.g: <input type=“text” name=“fname” >
Make a php variable and store the data in php file
e.g: $firstName=$_GET[‘fname’];
Introduction to regular expression
Regular expressions are nothing more than a sequence or
pattern of characters itself.
They provide the foundation for pattern-matching
functionality.
Using regular expression you can
search a particular string inside another string,
replace one string by another string and
split a string into many chunks.
PHP offers functions specific to two sets of regular
expression functions, each corresponding to a certain type of
regular expression
…cont’d…
The two types are
POSIX Regular Expressions
Easier to learn
PERL Style Regular Expressions
You can use any of the above based on your comfort
Regular expression syntax includes the use of special
characters (do not confuse with the HTML special
characters).
The characters that are given special meaning within a
regular expression, are: . * ? +[ ] ( ) { } ^ $ | \.
POSIX Regular expressions
The basics
Character sets and classes
More powerful than exact matching expressions
Character sets can match any character of particular type
Dot (.) matches any single character except (\n)
.at -- matches “cat” , “sat” , and “mat” etc
Mostly used for filename matching in operating systems
If you want to limit to the characters between a-z; write as
follows:
[a-z]at -- matches any single character before at.
Result may be aat, bat, cat, etc
…cont’d…
[aeiou] – matches any single vowel
[a-zA-Z] – matches any single character a to z in
lower or uppercase
[^a-z] – matches any single character not in a-z range
Caret (^) symbol stands for not
Should be placed inside square brackets ; if outside , it
will give another meaning
Refer to the following table for POSIX character
classes
…cont’d…
…cont’d…
Repetition
You may want to specify multiple occurrence of a
string or class of characters; specify by using the two
operators below
* -- means zero or more
+ -- means one or more
Example
[[:alnum:]]+ -- means at least one alphanumeric character
[[:alnum:]]* -- means zero or more alphanumeric character
…cont’d…
Sub-expressions
Using sub expressions are a good idea to represent like
for example at-least one of a string followed by
another string
Example : (very)*large
Matches : “large”, “very large”, “very very large” etc
(very)+large
Matches: “very large”,”very very large” , etc
…cont’d…
Counted sub-expressions
You can specify how many times something is repeated
by using numerical representations inside { } (curly
braces )
{x} – exactly x repeatition
{x,y} – x to y repeatition
{x,} – Open-ended repeatition
Example: (very){2}
Matches : very very
(very){1,2}
Matches: very, very very
…cont’d…
Anchoring
To the beginning of a string
The caret (^) symbol is used at the beginning of a regular
expression to show that the pattern should appear at the
beginning of a searched string
^bob matches bob at the start of a string
To the end of string
The dollar ($) symbol is used at the end of a regular
expression to show that the pattern should appear at the end
of the searched string
com$ matches com at the end of a string
…cont’d…
Branching
You can represent a choice in a regular expression with a
vertical pipe.
Example: if you want to match com , edu , or net, you
can use the following expression:
com|edu|net
Note:
Enclose regular expressions inside single quotes only
Use double slash to match the literal \
Use four slashes to match regular expression \
…cont’d…
Special characters used outside [ ]
…cont’d…
Special characters used inside [ ]
…cont’d…
Finding a match with regular expression
Two functions are available for POSIX style regular
expressions
ereg() and eregi()
Prototype of ereg() is as follows:
int ereg(string pattern, string search,array[matches]);
Searches a pattern in search string and stores it in array
matches per element
eregi() is the case-insensitive version of ereg() function
Has similar prototype with ereg() function
…cont’d…
Example
To match an email, we can use:
^[a-zA-Z0-9_\-\.]+@[a-zA-Z0-9\-]+\.[a-zA-Z0-9\-\.]+$
In PHP you may write as follows:
$email=$_GET[‘email’];
$pattern=‘^[a-zA-Z0-9_\-\.]+@[a-zA-Z0-9\-]+\.[a-zA-Z0-9\-\.]+$‘;
if(!eregi($pattern , $email)) {
echo”<p>That is not a valid email address.</p>”;
else
exit;
}
…cont’d…
Example
…cont’d…
Example
…cont’d…
Exercise
Write a regular expression to match a postal code
Write a regular expression to match Ethiopian phone
number
Write a regular expression to match an age
Write a regular expression to match a person name
Write a regular expression to match a URL
Write a regular expression to match visa card number
Write a regular expression to match a php variable
The End
Thanks!