Chapter Two: HTML Forms and Server Side Scripting
Chapter Two: HTML Forms and Server Side Scripting
Two
HTML Forms and Server Side Scripting
2
HTML Forms
! The <form> Element:
! HTML forms are used to collect user input.
! The <form> element defines an HTML form:
Cont.
Description ! Number: used to accept number
only.
! Text: defines normal text input
! File: used to upload file from
! Radio: defines radio button computer.
input (for selecting one of
! Reset: used to clear form elements.
many choices)
! Button: used for alerting
! Submit: defines a submit
button (for submitting the ! Select: used to select elements from
form value) drop-down list.
Text Input
! <input type="text">
! Example
<html>
<body>
<form>
First name:<input type="text"
name="firstname"><br>
Last name:<input type="text" name="lastname">
</form>
</body>
</html>
Fieldset
! The <fieldset> element groups related data
in a form.
Thursday, April 11,
Advanced IP Compiled By: Yonas H. (MSc.)
19
10
<DOCTYPE html>
<html>
<body>
<form action="">
<textarea name="message" rows="10" cols="30">
The cat was playing in the garden.
</textarea><br><br> <input type="submit">
</form> </body>
</html>
Thursday, April 11,
Advanced IP Compiled By: Yonas H. (MSc.)
19
11
cont
! When the user fills out the form above and
clicks the submit button, the form data is sent
for processing to a PHP file named
"welcome.php". The form data is sent with the
HTTP POST method.
cont
! The same result could also be achieved using the
HTTP GET method:
<html>
<body>
<form action="welcome_get.php" method="get">
Name: <input type="text" name="name"><br>
E-mail: <input type="text" name="email"><br>
<input type="submit">
</form>
</body>
</html>
"welcome_get.php”
<html>
<body>
Welcome <?php echo $_GET["name"]; ?><br>
Your email address is:
<?php echo $_GET["email"]; ?>
</body>
</html>
Login.php
<?php
$name=$_POST["name"];
?>
Validate Forms
Basic server-side
validation code
! validation code can take a lot of time /
lines to write
! How do you test for integers vs. real numbers
vs. strings?
! How do you test for a valid credit card
number?
! How do you test that a person's name has a
middle initial?
! How do you test whether a given string matches
a particular complex format?
Regular expressions
Reg exp Meaning
[a-z]at #cat, rat, bat…
[aeiou]
[a-zA-Z]
[^a-z] #not a-z
[[:alnum:]]+ #at least one alphanumeric char
(very)*large #large, very very very large…
(very){1, 3} #counting “very” up to 3
^bob #bob at the beginning
com$ #com at the end
Wildcards
! A dot . matches any character except a \n
line break
! "/.oo.y/" matches "Doocy", "goofy",
"LooNy", ...
Special characters:
|, (), ^, \
! | means OR
! "/abc|def|g/" matches "abc", "def", or "g"
! There's no AND symbol. Why not?
Con’t
! \ starts an escape sequence
! many characters must be escaped to
match them literally: / \ $ . [ ]
( ) ^ * + ?
! "/<br \/>/" matches lines
containing <br /> tags
Repetition Quantifiers
! In the previous section we've learnt how to match a
single character in a variety of fashions.
Quantifiers: *, +, ?
! * means 0 or more occurrences
! "/abc*/" matches "ab", "abc", "abcc",
"abccc", ...
! "/a(bc)*/" matches "a", "abc", "abcbc",
"abcbcbc", ...
! "/a.*a/" matches "aa", "aba", "a8qa", "a!?
_a", ...
! ? means 0 or 1 occurrences
! "/a(bc)?/" matches "a" or "abc"
More quantifiers:
{min,max}
! {min,max} means between min and max
occurrences (inclusive)
! "/a(bc){2,4}/" matches "abcbc", "abcbcbc", or
"abcbcbcbc"
Character Classes
! Square brackets surrounding a pattern of characters are
called a character class e.g. [abc].
Character sets: []
! [] group characters into a character
set; will match any single character
from the set
! "/[bcd]art/" matches strings containing
"bart", "cart", and "dart"
! equivalent to "/(b|c|d)art/" but shorter
Character ranges:
[start-end]
! inside a character set, specify a range of
characters with -
! "/[a-z]/" matches any lowercase letter
! "/[a-zA-Z0-9]/" matches any lower- or
uppercase letter or digit
Character ranges:
[start-end]
! inside a character set, - must be escaped
to be matched
! "/[+\-]?[0-9]+/" matches an optional + or -,
followed by at least one digit
Pattern Modifiers
Modifi What it Does
er
i Makes the match case-insensitive manner.
m Changes the behavior of ^ and $ to match against a
newline boundary (i.e. start or end of each line
within a multiline string), instead of a string
boundary.
g Perform a global match i.e. finds all occurrences.
o Evaluates the expression only once.
s Changes the behavior of . (dot) to match all
characters, including newlines.
x Allows you to use whitespace and comments within a
regular expression for clarity.
Escape sequences
! special escape sequence character sets:
! \d matches any digit (same as [0-9]); \D any
non-digit ([^0-9])
! \w matches any “word character” (same as [a-
zA-Z_0-9]); \W any non-word
! char
! \s matches any whitespace character ( , \t,
\n, etc.); \S any non-whitespace
function description
preg_match(regex, string) returns TRUE if string matches regex
returns a new string with all
preg_replace(regex,
substrings that match regex replaced
replacement, string)
by replacement
returns an array of strings from
given string broken apart using the
preg_split(regex, string) given regex as the delimiter
(similar to explode but more
powerful)
Word Boundaries
! A word boundary character ( \b) helps you search
for the words that begins and/or ends with a
pattern.
Advanced IP Compiled By: Yonas H. (MSc.) 11 April 2019
49
Regular expressions
example
$matchesarray[0] = "http://www.tipsntutorials.com/"
$matchesarray[1] = "http://"
$matchesarray[2] = "www.tipsntutorials.com/"
preg_match ('/(http://)(.*)/', "http://
www.tipsntutorials.com/", $matchesarray)
$state = $_REQUEST["state"];
if (!preg_match("/[A-Z]{2}/", $state))
{ ?>
<h2>Error, invalid state submitted.</h2>
<?php
}
Example
[A-Z]{8,12}
<input type="text" name="name"
pattern="[A-Z]{8,12}" autofocus="on"
title="Enter uppercase letter in
between 8 and 12 ">
htmlspecialchars()
function
! converts special characters to HTML entities.
This means that it will replace HTML
characters like < and > with < and >.
?>
Thursday, April 11,
Advanced IP Compiled By: Yonas H. (MSc.)
19
56
! If($_SERVER[“REQUEST_METHOD”]==“POST”)
Concept of Validation
! Our concept in the validation process is
very simple. We have created a variable
$valid and set up its value as 1 initially.
! If no validation error occurs, this value
will never be changed, and we will print
the success message.
! But if this value is changed to 0 (you can
use any value, 0 is used just as an
instance) anyhow in the validation
process, we will finally stop the script
so that it can’t proceed further and put
the specific error message.
Thursday, April 11,
Advanced IP Compiled By: Yonas H. (MSc.)
19
58
validating Name, Gender,
Country
! In our process, validating the Name, Gender,
Country, Bio and Term is very easy. Just we
need to check if user has given data to those
fields or not. The codes for validating these
fields are shown here:
If(empty($_POST[‘uname’])){
$valid=0;
$error_message=“name cano not be empty<br>”;
}
If(empty($_POST[‘gender’])){
$valid=0;
$error_message=“name cano not be empty<br>”;
} ….....
Thursday, April 11,
Advanced IP Compiled By: Yonas H. (MSc.)
19
59
{ $valid=0;
$error_message=“email can not be empty<br/>”;
else {
if(filter_var($_post[‘email’],FILTER_VALIDATE_EMAIL)===false)
{
$valid=0;
Validating Username
! Validating username is easy also. As a test case, we have setup
a rule here. Username must be at least 5 characters in long and
must contain at least 1 number and 1 alphabetic character. This
rule will vary project to project.
! First of all, the compiler will check if there is any empty data
or not.
! If the input field is not empty (it means user has given
something in the text box), then username will be checked for
validation.
}else {
$len=strlen($POST[‘username’]);
If($len<5){ $valid=0;
}else {
$count_number=preg_match_all(“/[0-9]/”,$_POST[‘username’]);
$count_alphabet=preg_match_all(“/[A-Za-z]/”,
$_POST[‘username’]);
Validating Password
! Password can be validated in multiple ways.
Here we do not use a complex rule for
password. Our rule is very simple.
if(empty($_POST[‘password’])){ $valid=0;
$error_message=“password cannot be empty<br/>”; }
If(empty($_POST[‘repassword’])){ $valid=0;
$error_message=“re type password <br/>”; }
if(!empty($_POST[‘password’])&& !
empty($_POST[‘repassword’]))
{ If($_POST[‘repassword’]!=$_POST[‘repassword’])
{ $valid=0;
$error_message=“password do not match<br>”;
}