0% found this document useful (0 votes)
75 views68 pages

Chapter Two: HTML Forms and Server Side Scripting

The document discusses HTML forms and server-side scripting. It describes various form elements like <form>, <input>, <select>, <textarea>, and <button> that allow users to enter text, select options, and submit information. It provides examples of how to create text fields, radio buttons, checkboxes, and dropdown lists. The document also explains how to build a simple HTML form and use PHP to process the submitted data on the server-side.

Uploaded by

Lamesgn Yigrem
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
75 views68 pages

Chapter Two: HTML Forms and Server Side Scripting

The document discusses HTML forms and server-side scripting. It describes various form elements like <form>, <input>, <select>, <textarea>, and <button> that allow users to enter text, select options, and submit information. It provides examples of how to create text fields, radio buttons, checkboxes, and dropdown lists. The document also explains how to build a simple HTML form and use PHP to process the submitted data on the server-side.

Uploaded by

Lamesgn Yigrem
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 68

Chapter

Two
HTML Forms and Server Side Scripting
2

Create a simple form using PHP

Thursday, April 11,


Advanced IP Compiled By: Yonas H. (MSc.)
19
3

HTML Forms
!  The <form> Element:
!  HTML forms are used to collect user input.
!  The <form> element defines an HTML form:

!  Example <form> form elements </form>

!  HTML forms contain form elements. Form


elements are different types of input
elements, checkboxes, radio buttons, submit
buttons, and more.

!  The <input> Element: <input> element is the


most important form element.The <input> element has
many variations, depending on the type attribute.
Thursday, April 11,
Advanced IP Compiled By: Yonas H. (MSc.)
19

4

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.

!  Password: used for encrypting !  E-mail: used for to accept standard


the password characters e-mail which include @ sign.
Thursday, April 11,
Advanced IP Compiled By: Yonas H. (MSc.)
19
5

Text Input
!  <input type="text">

!  defines a one-line input field for text input:

!  Example
<html>
<body>
<form>
First name:<input type="text"
name="firstname"><br>
Last name:<input type="text" name="lastname">
</form>
</body>
</html>

Thursday, April 11,


Advanced IP Compiled By: Yonas H. (MSc.)
19
6

Radio Button Input



!  <input type="radio"> defines a radio button.
!  Radio buttons let a user select ONE of a
limited number of choices:
<html>
<body>
<form>
<input type="radio" name="sex" value="male">Male<br>
<input type="radio" name="sex" value="female">Female
</form>
</body>
</html>

Thursday, April 11,


Advanced IP Compiled By: Yonas H. (MSc.)
19
7

The Submit Button



!  <input type="submit"> defines a button
for submitting a form to a form-handler.
!  The form-handler is typically a server page
with a script for processing input data.
!  The form-handler is specified in the
form's action attribute.
<html>
<body>
<form action="">
First name:<input type="text"><br><br>
Last name:<input type="text”><br><br>
<input type="submit" value="Submit">
</form>
</body>
</html>

Thursday, April 11,
Advanced IP Compiled By: Yonas H. (MSc.)
19
8

Fieldset
!  The <fieldset> element groups related data
in a form.

!  The <legend> element defines a caption for


the <fieldset> element.

Thursday, April 11,


Advanced IP Compiled By: Yonas H. (MSc.)
19
9

HTML Form Elements


The <input> Element

!  The most important form element is


the <input> element.

!  The <input> element can vary in many ways,


depending on the type attribute.

!  The <select> Element (Drop-Down List)

!  The <select> element defines a drop-


down list:


Thursday, April 11,
Advanced IP Compiled By: Yonas H. (MSc.)
19
10

The <textarea> Element



!  The <text area> element defines a multi-line
input field (a text area)

<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

The <button> Element


! The <button> element defines a
clickable button:
<!DOCTYPE html>
<html>
<body>
<button type="button
onclick="alert('Hello
World!')">Click Me!
</button>
</body>
</html>
Thursday, April 11,
Advanced IP Compiled By: Yonas H. (MSc.)
19
12

Input Type: checkbox



<input type="checkbox"> defines a checkbox.
Checkboxes let a user select ZERO or MORE options
of a limited number of choices.
<!DOCTYPE html>
<html>
<body>
<form action="">
<input type="checkbox" name="vehicle"
value="Bike">I have a bike<br>
<input type="checkbox" name="vehicle"
value="Car">I have a car <br><br>
<input type="submit">
</form>
</body>
</html>
Thursday, April 11,
Advanced IP Compiled By: Yonas H. (MSc.)
19
13

a Simple Form using PHP


!  The example below displays a simple HTML
form with two input fields and a submit
button:
<html>
<body>
<form action="welcome.php" method="post">
Name: <input type="text" name="name"><br>
E-mail: <input type="text" name="email"><br>
<input type="submit">
</form>
</body>
</html>
Thursday, April 11,
Advanced IP Compiled By: Yonas H. (MSc.)
19
14

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.

!  To display the submitted data you could simply


echo all the variables. The "welcome.php" looks
like this
<html>
<body>
Welcome <?php echo $_POST["name"]; ?><br>
Your email address is: <?php echo
$_POST["email"]; ?>
</body>
</html> Thursday, April 11,
Advanced IP Compiled By: Yonas H. (MSc.)
19
15

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>

Thursday, April 11,


Advanced IP Compiled By: Yonas H. (MSc.)
19
16

"welcome_get.php”
<html>
<body>
Welcome <?php echo $_GET["name"]; ?><br>
Your email address is:
<?php echo $_GET["email"]; ?>
</body>
</html>

Thursday, April 11,


Advanced IP Compiled By: Yonas H. (MSc.)
19
17

GET and POST


!  The PHP superglobals $_GET and $_POST are
used to collect form-data.

!  Both GET and POST create an array (e.g.


array( key => value, key2 => value2, key3
=> value3, ...)).

!  This array holds key/value pairs, where


keys are the names of the form controls and
values are the input data from the user.

!  Both GET and POST are treated as $_GET and


$_POST.

Thursday, April 11,


Advanced IP Compiled By: Yonas H. (MSc.)
19
18

GET and POST


!  These are superglobals, which means that
they are always accessible, regardless of
scope - and you can access them from any
function, class or file without having to
do anything special.

!  $_GET is an array of variables passed to


the current script via the URL parameters.

!  $_POST is an array of variables passed to


the current script via the HTTP POST
method.

Thursday, April 11,


Advanced IP Compiled By: Yonas H. (MSc.)
19
19

When to use GET?


!  Information sent from a form with the GET method
is visible to everyone (all variable names and
values are displayed in the URL).

!  GET also has limits on the amount of information


to send. The limitation is about 2000
characters. However, because the variables are
displayed in the URL, it is possible to bookmark
the page. This can be useful in some cases.

!  GET may be used for sending non-sensitive data.

!  Note: GET should NEVER be used for sending


passwords or other sensitive information!

Thursday, April 11,


Advanced IP Compiled By: Yonas H. (MSc.)
19
20

When to use POST?


!  Information sent from a form with the POST
method is invisible to others (all names/
values are embedded within the body of the
HTTP request) and has no limits on the amount
of information to send.

!  Moreover POST supports advanced functionality


such as support for multi-part binary input
while uploading files to server.

!  However, because the variables are not


displayed in the URL, it is not possible to
bookmark the page.

!  Developers prefer POST for sending form data.

Thursday, April 11,


Advanced IP Compiled By: Yonas H. (MSc.)
19
21

Submit form values


<form action="login.php" method="post">
<table>
<tr><td>Name:</td><td>
<input type="text" name="name"/></td></tr>
<tr><td>Password:</td><td>
<input type="password" name="password"/></td></tr>
<tr><td colspan="2">
<input type="submit" value="login"/>
</td></tr>
</table>
</form>

Thursday, April 11,


Advanced IP Compiled By: Yonas H. (MSc.)
19
22

Login.php
<?php
$name=$_POST["name"];

//receiving name field value in $name variable


$password=$_POST["password"];

//receiving password field value in $password variable


echo "Welcome: $name, your password is: $password";

?>

Thursday, April 11,


Advanced IP Compiled By: Yonas H. (MSc.)
19
23

Validate Forms

Thursday, April 11,


Advanced IP Compiled By: Yonas H. (MSc.)
19
24

What is form validation?


!  validation: ensuring that form's values are
correct

!  some types of validation:


!  preventing blank values (email address)
!  ensuring the type of values
!  integer, real number, currency, phone number,
Social Security number, postal
!  address, email address, date, credit card
number, ...
!  ensuring the format and range of values (ZIP code
must be a 5-digit integer)
!  ensuring that values fit together (user types
email twice, and the two must match)

Thursday, April 11,


Advanced IP Compiled By: Yonas H. (MSc.)
19
25

A real Form that uses


validation

Thursday, April 11,


Advanced IP Compiled By: Yonas H. (MSc.)
19
26

Client vs. server-side


validation
! Validation can be performed:
!  client-side (before the form is
submitted)
!  can lead to a better user experience, but
not secure (why not?)
!  server-side (in PHP code, after the
form is submitted)
!  needed for truly secure validation, but
slower
!  both
!  best mix of convenience and security,
but requires most effort to program

Thursday, April 11,


Advanced IP Compiled By: Yonas H. (MSc.)
19
27

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?

Thursday, April 11,


Advanced IP Compiled By: Yonas H. (MSc.)
19
28

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

!  Regular expression: a pattern in a piece of text


Thursday, April 11,
Advanced IP Compiled By: Yonas H. (MSc.)
19
29

Basic Regular Expression


/abc/
!  in PHP, regexes are strings that begin and
end with /

!  the simplest regexes simply match a


particular substring

!  the above regular expression matches any


string containing "abc":
!  YES: "abc", "abcdef", "defabc",
".=.abc.=.", ...
!  NO: "fedcba", "ab c", "PHP", ...
Thursday, April 11,
Advanced IP Compiled By: Yonas H. (MSc.)
19
30

Regular Expression Syntax



!  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: .
* ? + [ ] ( ) { } ^ $ | \.

!  You will need to backslash these characters


whenever you want to use them literally.

!  For example, if you want to match ".",


you'd have to write \.. All other
characters automatically assume their
literal meanings.
Advanced IP Compiled By: Yonas H. (MSc.) 11 April 2019
31

Wildcards
!  A dot . matches any character except a \n
line break
!  "/.oo.y/" matches "Doocy", "goofy",
"LooNy", ...

!  A trailing i at the end of a regex (after


the closing /) signifies a case-insensitive
match
!  "/xen/i" matches “Xenia", “xenophobic", “Xena
the warrior princess", “XEN technologies” ...

Thursday, April 11,


Advanced IP Compiled By: Yonas H. (MSc.)
19
32

Special characters:
|, (), ^, \
! | means OR
!  "/abc|def|g/" matches "abc", "def", or "g"
!  There's no AND symbol. Why not?

! () are for grouping


!  "/(Homer|Marge) Simpson/" matches "Homer
Simpson" or "Marge Simpson"

! ^ matches the beginning of a line; $


the end
!  "/^<!--$/" matches a line that consists
entirely of "<!--"
Thursday, April 11,
Advanced IP Compiled By: Yonas H. (MSc.)
19
33

Con’t
! \ starts an escape sequence
! many characters must be escaped to
match them literally: / \ $ . [ ]
( ) ^ * + ?
! "/<br \/>/" matches lines
containing <br /> tags

Thursday, April 11,


Advanced IP Compiled By: Yonas H. (MSc.)
19
34

Repetition Quantifiers

!  In the previous section we've learnt how to match a
single character in a variety of fashions.

!  But what if you want to match on more than one


character?

!  For example, let's say you want to find out words


containing one or more instances of the letter p,
or words containing at least two p's, and so on.

!  This is where quantifiers come into play.

!  With quantifiers you can specify how many times a


character in a regular expression should match.

!  The following table lists the various ways to


quantify a particular pattern:

Advanced IP Compiled By: Yonas H. (MSc.) 11 April 2019


35

RegExp What it Does

p+ Matches one or more occurrences of the letter p.


p* Matches zero or more occurrences of the letter p.
p? Matches zero or one occurrences of the letter p.
p{2} Matches exactly two occurrences of the letter p.
p{2,3} Matches at least two occurrences of the letter p, but
not more than three occurrences of the letter p.
p{2,} Matches two or more occurrences of the letter p.
p{,3} Matches at most three occurrences of the letter p

Advanced IP Compiled By: Yonas H. (MSc.) 11 April 2019


36

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 1 or more occurrences


!  "/a(bc)+/" matches "abc", "abcbc", "abcbcbc", ...
!  "/Goo+gle/" matches "Google", "Gooogle",
"Goooogle", ...

!  ? means 0 or 1 occurrences
!  "/a(bc)?/" matches "a" or "abc"

Thursday, April 11,


Advanced IP Compiled By: Yonas H. (MSc.)
19
37

More quantifiers:
{min,max}
!  {min,max} means between min and max
occurrences (inclusive)
!  "/a(bc){2,4}/" matches "abcbc", "abcbcbc", or
"abcbcbcbc"

!  min or max may be omitted to specify any


number
!  {2,} means 2 or more
!  {,6} means up to 6
!  {3} means exactly 3

Thursday, April 11,


Advanced IP Compiled By: Yonas H. (MSc.)
19
38

Character Classes

!  Square brackets surrounding a pattern of characters are
called a character class e.g. [abc].

!  A character class always matches a single character out


of a list of specified characters that means the
expression [abc] matches only a, b or c character.

!  Negated character classes can also be defined that match


any character except those contained within the
brackets.

!  A negated character class is defined by placing a caret


(^) symbol immediately after the opening bracket, like
this [^abc].

!  You can also define a range of characters by using the


hyphen (-) character inside a character class, like
[0-9]. Let's look at some examples of character classes:
Advanced IP Compiled By: Yonas H. (MSc.) 11 April 2019
39

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

! inside [], many of the modifier keys


act as normal characters
!  "/what[!*?]*/" matches "what", "what!",
"what?**!", "what??!”,
Thursday, April 11,
Advanced IP Compiled By: Yonas H. (MSc.)
19
40

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

!  an initial ^ inside a character set negates


it
!  "/[^abcd]/" matches any character other than
a, b, c, or d

Thursday, April 11,


Advanced IP Compiled By: Yonas H. (MSc.)
19
41

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

!  What regular expression matches letter


grades such as A, B+, or D- ?

Thursday, April 11,


Advanced IP Compiled By: Yonas H. (MSc.)
19
42

RegExp What it Does


[abc] Matches any one of the characters a, b, or c.
[^abc] Matches any one character other than a, b, or c.
[a-z] Matches any one character from lowercase a to
lowercase z.
[A-Z] Matches any one character from uppercase a to
uppercase z.
[a-Z] Matches any one character from lowercase a to
uppercase Z.
[0-9] Matches a single digit between 0 and 9.
[a-z0-9] Matches a single character between a and z or
between 0 and 9.

Advanced IP Compiled By: Yonas H. (MSc.) 11 April 2019


43

Predefined Character Classes



Shortcut What it Does
. Matches any single character except newline \n.
\d matches any digit character. Same as [0-9]
\D Matches any non-digit character. Same as [^0-9]
\s Matches any whitespace character (space, tab, newline
or carriage return character). Same as [ \t\n\r]
\S Matches any non-whitespace character. Same as [^ \t\n
\r]
\w Matches any word character (definned as a to z, A to
Z,0 to 9, and the underscore). Same as [a-zA-Z_0-9]
\W Matches any non-word character. Same as [^a-zA-Z_0-9]

Advanced IP Compiled By: Yonas H. (MSc.) 11 April 2019


44

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.

Advanced IP Compiled By: Yonas H. (MSc.) 11 April 2019


45

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

!  What regular expression matches dollar


amounts of at least $100.00 ?

Thursday, April 11,


Advanced IP Compiled By: Yonas H. (MSc.)
19
46

Regular expressions in PHP

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)

Thursday, April 11,


Advanced IP Compiled By: Yonas H. (MSc.)
19
47

commonly used PHP's built-in pattern-


matching functions
Function What it Does
preg_match_all() Perform a global regular expression
match.
preg_grep() Returns the elements of the input
array that matched the pattern.
preg_quote() Quote regular expression characters
found within a string.

Advanced IP Compiled By: Yonas H. (MSc.) 11 April 2019


48

Word Boundaries
!  A word boundary character ( \b) helps you search
for the words that begins and/or ends with a
pattern.

!  For example, the regexp /\bcar/ matches the words


beginning with the pattern car, and would match
cart, carrot, or cartoon, but would not match
oscar.

!  Similarly, the regexp /car\b/ matches the words


ending with the pattern car, and would match scar,
oscar, or supercar, but would not match cart.

!  Likewise, the /\bcar\b/ matches the words beginning


and ending with the pattern car, and would match
only the word car.


Advanced IP Compiled By: Yonas H. (MSc.) 11 April 2019
49

Regular expressions
example

echo preg_match ('/test/', "a test of preg_match");


echo preg_match ('/
tutorial/', "a test of preg_match");

$matchesarray[0] = "http://www.tipsntutorials.com/"
$matchesarray[1] = "http://"
$matchesarray[2] = "www.tipsntutorials.com/"
preg_match ('/(http://)(.*)/', "http://
www.tipsntutorials.com/", $matchesarray)

Thursday, April 11,


Advanced IP Compiled By: Yonas H. (MSc.)
19
50
Regular expressions
example
# replace vowels with stars
$str = "the quick brown fox";
$str = preg_replace("/[aeiou]/", "*", $str);
# "th* q**ck br*wn f*x"
# break apart into words
$words = preg_split("/[ ]+/", $str);
# ("th*", "q**ck", "br*wn", "f*x")
# capitalize words that had 2+ consecutive vowels
for ($i = 0; $i < count($words); $i++) {
if (preg_match("/\\*{2,}/", $words[$i])) {
$words[$i] = strtoupper($words[$i]);
}
} # ("th*", "Q**CK", "br*wn", "f*x")
PHP
Thursday, April 11,
Advanced IP Compiled By: Yonas H. (MSc.)
19
51
PHP form validation w/
regexes

$state = $_REQUEST["state"];
if (!preg_match("/[A-Z]{2}/", $state))
{ ?>
<h2>Error, invalid state submitted.</h2>
<?php
}

!  using preg_match and well-chosen regexes allows you to


quickly validate query parameters against complex
patterns

Thursday, April 11,


Advanced IP Compiled By: Yonas H. (MSc.)
19
52

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 ">

Advanced IP Compiled By: Yonas H. (MSc.) 11 April 2019



53

Passing Form Data to the
Same Page
!  After giving input to the form fields, you
can pass the data to the same page or
another separate page. In this case, we
will pass data into the same page. To do
this, just write the <form> tag as below:

!  <form action=“<?php echo


htmlspecialchars($_SERVER[“PHP_SELF”]);?>”
method=“post”>
!  Here the superglobal variable $_SERVER is
used and its parameter PHP_SELF indicates
that the form data is passed in the same
page.

Thursday, April 11,


Advanced IP Compiled By: Yonas H. (MSc.)
19
54

htmlspecialchars()
function
!  converts special characters to HTML entities.
This means that it will replace HTML
characters like < and > with &lt; and &gt;.

!  This prevents attackers from exploiting the


code by injecting HTML or Javascript code
(Cross-site Scripting attacks) in forms.

!  Strip unnecessary characters (extra space,


tab, newline) from the user input data (with
the PHP trim() function)

!  Remove backslashes (\) from the user input


data (with the PHP stripslashes() function)

Thursday, April 11,


Advanced IP Compiled By: Yonas H. (MSc.)
19
55
<?php // define variables and set to empty values
$name = $email = $gender = $comment = $website = "";
if ($_SERVER['REQUEST_METHOD'] == 'POST')
{
$name = test_input($_POST["name"]);
$email = test_input($_POST["email"]);
$website = test_input($_POST["website"]);
$comment = test_input($_POST["comment"]);
$gender = test_input($_POST["gender"]);
}
function test_input($data)
{
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}

?>
Thursday, April 11,
Advanced IP Compiled By: Yonas H. (MSc.)
19
56

Checking the Top of Page


!  In the beginning of the page, we will check
if any form data is submitted or not. If
data is submitted, we will check for
validation.

!  Otherwise, we will just proceed to show the


fields normally. In order to check that, we
will run the follow conditional statement:

!  If($_SERVER[“REQUEST_METHOD”]==“POST”)

Thursday, April 11,


Advanced IP Compiled By: Yonas H. (MSc.)
19
57

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

Validating Email Address


!  Email address validation is a bit tricky.

!  First of all, you will have to check if user has given


any email address into the text field or not.

!  If user gives something in the input field, now we


will have to again check if that format is a valid
email address or not.

!  Therefore, here is 2 parts.


!  The first part is same as before.
!  But in the second part, we will use a filter that is
called FILTER_VALIDATE_EMAIL. You can use some other
alternate methods too like preg_match or manually coding
for validation.

!  Here are the codes we used:

Thursday, April 11,


Advanced IP Compiled By: Yonas H. (MSc.)
19
60
if(empty($_post[‘email’]))

{ $valid=0;
$error_message=“email can not be empty<br/>”;

else {

if(filter_var($_post[‘email’],FILTER_VALIDATE_EMAIL)===false)
{

$valid=0;

$error_message=“invalid email address<br/>”;

Thursday, April 11,


Advanced IP Compiled By: Yonas H. (MSc.)
19
61

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.

!  We have used 2 built-in functions of PHP here: strlen and


preg_match_all.
!  The first function strlen will check the total length of string that user gives as
input and
!  the second function preg_match_all will check how many letters and alphabets the
string contains.

Thursday, April 11,


Advanced IP Compiled By: Yonas H. (MSc.)
19
If(empty($_POST[‘username’])){ $valid=0; 62

$error_message=“user name can not be empty<br/>”;

}else {

$len=strlen($POST[‘username’]);

If($len<5){ $valid=0;

$error_message=“user name can not be empty<br/>”;

}else {

$count_number=preg_match_all(“/[0-9]/”,$_POST[‘username’]);

$count_alphabet=preg_match_all(“/[A-Za-z]/”,
$_POST[‘username’]);

If($count_number==0|| $count_alphabet==0){ $valid=0;

$error_message=“usernmae must contain at least 1 # and 1


chrater”;}}}

Thursday, April 11,


Advanced IP Compiled By: Yonas H. (MSc.)
19
63

Validating Password
!  Password can be validated in multiple ways.
Here we do not use a complex rule for
password. Our rule is very simple.

!  First, compiler will check if data is given


into the password and retype password
fields.

!  If data is given there, compiler will match


both of those. The code will be like this:

Thursday, April 11,


Advanced IP Compiled By: Yonas H. (MSc.)
19
64

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>”;
}

Thursday, April 11,


Advanced IP Compiled By: Yonas H. (MSc.)
19
65

Checking final validation


!  When the value of previously discussed $valid
variable is not changed, you can generate a
success message like this:
If($valid==1)
{
$success_message=“evrything is Ok!”;
}

Thursday, April 11,


Advanced IP Compiled By: Yonas H. (MSc.)
19
66

Error and Success Message


!  We did not print error and success message
in the point of errors. We just kept all
into variables.

!  We will print the messages just before the


form starts.

!  You can change the location of these


messages into anywhere in your PHP page.

!  See how the code looks like:

Thursday, April 11,


Advanced IP Compiled By: Yonas H. (MSc.)
19
67
if($error_message !=‘ ‘)
{
echo’<div class=“red”>.
$error_message.’</div><br>’
}
if($success_message !=‘ ‘)
{
echo’<div class=“green”>.
$success_message.’</div><br>’
}

Advanced IP Compiled By: Yonas H. (MSc.)
Thursday, April 11,
19
68

Thursday, April 11,


Advanced IP Compiled By: Yonas H. (MSc.)
19

You might also like