SlideShare a Scribd company logo
1 of 22
Chapter Two:
HTML Forms and
Server Side
Scripting
11/27/2019
BantamlakDejene,Information
Technology
1
Create a Simple Form using Php
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 tags look like <form action="script.php"
method="post"></form>
11/27/2019
BantamlakDejene,Information
Technology
2
Cont.….
In terms of PHP, the most important attribute of your form tag is
action, which dictates to which page the form data will be sent. The
second attribute method has its own, but post is the value you’ll use
most frequently. The different inputs be the text boxes, radio buttons,
select menus, check boxes, etc. are placed within the opening and
closing form tags. As you’ll see in the next section, what kinds of
inputs your form has makes little difference to the PHP script handling
it. You should, however, pay attention to the names you give your form
inputs, as they’ll be of critical importance when it comes to your PHP
code.
11/27/2019
BantamlakDejene,Information
Technology
3
Receive Data from a Form in Php
Now that the HTML form has been created, it’s time to write a bare-
bones PHP script to handle it. To say that this script will be handling
the form means that the PHP page will do something with the data it
receives (which is the data the user entered into the form). In this
chapter, the scripts will simply print the data back to the Web browser.
In later examples, form data will be stored in a MySQL database,
compared against previously stored values, sent in emails, and more.
11/27/2019
BantamlakDejene,Information
Technology
4
Cont.….
The beauty of PHP and what makes it so easy to learn and use is how
well it interacts with HTML forms. PHP scripts store the received
information in special variables. For example, say you have a form
with an input defined like so: <input type="text" name="city" />
Whatever the user types into that input will be accessible via a PHP
variable named $_REQUEST['city']. It is very important that the
spelling and capitalization match exactly! PHP is case-sensitive when
it comes to variable names, so $_REQUEST['city'] will work, but
$_Request['city'] and $_REQUEST['City'] will have no value.
11/27/2019
BantamlakDejene,Information
Technology
5
Cont.….
Element Name Variable Name
Name $_REQUEST['name']
Email $_REQUEST['email']
comments $_REQUEST['comments']
Age $_REQUEST['age']
Gender $_REQUEST['gender']
Submit $_REQUEST['submit']
11/27/2019
BantamlakDejene,Information
Technology
6
Cont.….
All of those examples use two separate files: one that displays the
form and another that receives its submitted data. While there’s
certainly nothing wrong with this approach, there are advantages
to putting the entire process into one script. To have one page both
display and handle a form, a conditional must check which action
(display or handle) should be taken:
if (/* form has been submitted */) {
// Handle the form.
} else {
// Display the form.
}
11/27/2019
BantamlakDejene,Information
Technology
7
Cont.….
The question, then, is how to determine if the form has been submitted. The answer is
simple, after a bit of explanation. When you have a form that uses the POST method and
gets submitted back to the same page, two different types of requests will be made of
that script. The first request, which loads the form, will be a GET request. This is the
standard request made of most Web pages. When the form is submitted, a second
request of the script will be made, this time a POST request (as long as the form uses the
POST method). With this in mind, you can test for a form’s submission by checking the
request method, found in the $_SERVER array:
if ($_SERVER['REQUEST_METHOD'] = = 'POST') {
// Handle the form.
} else {
// Display the form.
}
11/27/2019
BantamlakDejene,Information
Technology
8
Cont.….
If you want a page to handle a form and then display it again (e.g.,
to add a record to a database and then give an option to add
another), drop the else clause:
if ($_SERVER['REQUEST_METHOD'] = = 'POST') {
// Handle the form.
}
// Display the form.
11/27/2019
BantamlakDejene,Information
Technology
9
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. Whether erroneous data
is purposefully malicious or just unintentionally inappropriate, it’s up to you the
Web architect to test it against expectations.
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. You saw an example of this in the preceding
script. One issue with the isset() function is that an empty string tests as true,
meaning that isset() is not an effective way to validate text inputs and text boxes
from an HTML form. 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.
11/27/2019
BantamlakDejene,Information
Technology
10
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:
if (condition) {
// Do something!
}
An if can also have an else clause:
if (condition) {
// Do something!
} else {
// Do something else!
}
11/27/2019
BantamlakDejene,Information
Technology
11
Cont.….
Symbol Meaning Type Example
= = is equal to Comparison $x = = $y
!= is not equal to Comparison $x != $y
< less than Comparison $x < $y
> Greater than Comparison $x > $y
<= less than or equal to Comparison $x <= $y
>= Greater than or equal to Comparison $x >= $y
! not Logical !$x
&& and Logical $x && $y
AND and Logical $x and $y
|| or Logical $x || $y
OR or Logical $x or $y
XOR and not logical $x XOR $y
11/27/2019
BantamlakDejene,Information
Technology
12
Cont.….
A condition can be true in PHP for any number of reasons. 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. In the second example, a
new function, isset(), is introduced. This function checks if a
variable is “set,” meaning that it has a value other than NULL (as
a reminder, NULL is a special type in PHP, representing no set
value). You can also use the comparative and logical operators in
conjunction with parentheses to make more complicated
expressions.
11/27/2019
BantamlakDejene,Information
Technology
13
Use For and While Loops
The other two types of loops you’ll use are for and while. The while loop looks
like this:
while (condition) {
// Do something.
}
As long as the condition part of the loop is true, the loop will be executed. Once
it becomes false, the loop is stopped. If the condition is never true, the loop will
never be executed. 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.
}
11/27/2019
BantamlakDejene,Information
Technology
14
Work with Forms and Arrays of Data
Now it’s time to learn about another type, the array. Unlike strings and
numbers, an array can hold multiple, separate pieces of information. An
array is therefore like a list of values, each value being a string or a number
or even another array. Arrays are structured as a series of key value pairs,
where one pair is an item or element of that array. For each item in the list,
there is a key (or index) associated with it. PHP supports two kinds of
arrays: indexed, which use numbers as the keys, and associative, which use
strings as keys. As in most programming languages, with indexed arrays,
arrays will begin with the first index at 0, unless you specify the keys
explicitly.
11/27/2019
BantamlakDejene,Information
Technology
15
Cont.….
An array follows the same naming rules as any other variable. This means that
you might not be able to tell that $var is an array as opposed to a string or
number. The important syntactical difference arises when accessing individual
array elements. To refer to a specific value in an array, start with the array
variable name, followed by the key within square brackets:
$band = $artists[0]; // The Mynabirds
echo $states['MD']; // Maryland
You can see that the array keys are used like other values in PHP: numbers (e.g.,
0) are never quoted, whereas strings (MD) must be. Because arrays use a
different syntax than other variables, and can contain multiple values, printing
them can be trickier. This will not work: echo "My list of states: $states";
11/27/2019
BantamlakDejene,Information
Technology
16
Introduction to Regular Expressions
Sometimes you want to check for a specific structure as
opposed to a specific value. Regular expressions allow this
type of matching. Besides the few examples below and the
inclusion of some regular expression syntax, no tutorial on
regular expressions is given here.
11/27/2019
BantamlakDejene,Information
Technology
17
Cont.….
^ Start of string
$ End of string
. Any single character
( ) Group of expressions
[] Item range (e.g. [afg] means a, f, or g)
[^] Items not in range ( e.g. [^cde] means not c, d, or e )
- (dash) character range within an item range (e.g. [a-z] means a through z)
| (pipe) Logical or ( e.g. (a|b) means a or b )
? Zero or one of preceding character/item range
* Zero or more of preceding character/item range
+ One or more of preceding character/item range
{integer} Exactly integer of preceding character/item range ( e.g. a{2} )
11/27/2019
BantamlakDejene,Information
Technology
18
Cont.….
{integer,} Integer or more of preceding character/item range ( e.g. a{2,} )
{integer, integer} From integer to integer (e.g. a{2,4} means 2 to four of a )
 Escape character
[:punct:] Any punctuation
[:space:] Any space character
[:blank:] Any space or tab
[:digit:] Any digit: 0 through 9
[:alpha:] All letters: a-z and A-Z
[:alnum:] All digits and letters: 0-9, a-z, and A-Z
[:xdigit:] Hexadecimal digit
[:print:] Any printable character
[:upper:] All uppercase letters: A-Z
[:lower:] All lowercase letters: a-z
11/27/2019
BantamlakDejene,Information
Technology
19
Cont.….
c Control character
s Whitespace
S Not whitespace
d Digit (0-9)
D Not a digit
w Letter (a-z, A-Z)
W Not a letter
x Hexadecimal digit
O Octal digit
11/27/2019
BantamlakDejene,Information
Technology
20
Character classes:–
Cont.….
11/27/2019
BantamlakDejene,Information
Technology
21
I Case-insensitive
S Period matches newline
M ^ and $ match lines
U Ungreedy matching
E Evaluate replacement
X Pattern over several lines
Modifiers:–
THANK YOU
11/27/2019
BantamlakDejene,Information
Technology
22

More Related Content

What's hot

Assignment 8 Group 2 - Final Group Project Report
Assignment 8 Group 2 - Final Group Project ReportAssignment 8 Group 2 - Final Group Project Report
Assignment 8 Group 2 - Final Group Project ReportBrian Jonathan
 
Sakai09 Osp Preconference Afternoon Forms
Sakai09 Osp Preconference Afternoon FormsSakai09 Osp Preconference Afternoon Forms
Sakai09 Osp Preconference Afternoon FormsSean Keesler
 
SessionTen_CaseStudies
SessionTen_CaseStudiesSessionTen_CaseStudies
SessionTen_CaseStudiesHellen Gakuruh
 
PHP Form Validation Technique
PHP Form Validation TechniquePHP Form Validation Technique
PHP Form Validation TechniqueMorshedul Arefin
 
Open Source Package Php Mysql 1228203701094763 9
Open Source Package Php Mysql 1228203701094763 9Open Source Package Php Mysql 1228203701094763 9
Open Source Package Php Mysql 1228203701094763 9isadorta
 
Php forms and validations by naveen kumar veligeti
Php forms and validations by naveen kumar veligetiPhp forms and validations by naveen kumar veligeti
Php forms and validations by naveen kumar veligetiNaveen Kumar Veligeti
 
Basic Data Types in C++
Basic Data Types in C++ Basic Data Types in C++
Basic Data Types in C++ Hridoy Bepari
 
Abap slides user defined data types and data
Abap slides user defined data types and dataAbap slides user defined data types and data
Abap slides user defined data types and dataMilind Patil
 
Web Design L2 - Playing with Tags
Web Design L2 - Playing with TagsWeb Design L2 - Playing with Tags
Web Design L2 - Playing with Tagsmykella
 

What's hot (19)

Assignment 8 Group 2 - Final Group Project Report
Assignment 8 Group 2 - Final Group Project ReportAssignment 8 Group 2 - Final Group Project Report
Assignment 8 Group 2 - Final Group Project Report
 
Sakai09 Osp Preconference Afternoon Forms
Sakai09 Osp Preconference Afternoon FormsSakai09 Osp Preconference Afternoon Forms
Sakai09 Osp Preconference Afternoon Forms
 
SessionTen_CaseStudies
SessionTen_CaseStudiesSessionTen_CaseStudies
SessionTen_CaseStudies
 
PHP Form Validation Technique
PHP Form Validation TechniquePHP Form Validation Technique
PHP Form Validation Technique
 
C5 Javascript
C5 JavascriptC5 Javascript
C5 Javascript
 
Unit 2.2
Unit 2.2Unit 2.2
Unit 2.2
 
Open Source Package Php Mysql 1228203701094763 9
Open Source Package Php Mysql 1228203701094763 9Open Source Package Php Mysql 1228203701094763 9
Open Source Package Php Mysql 1228203701094763 9
 
XML
XMLXML
XML
 
Introduction to XML
Introduction to XMLIntroduction to XML
Introduction to XML
 
Unit 2.2
Unit 2.2Unit 2.2
Unit 2.2
 
Php forms and validations by naveen kumar veligeti
Php forms and validations by naveen kumar veligetiPhp forms and validations by naveen kumar veligeti
Php forms and validations by naveen kumar veligeti
 
uptu web technology unit 2 Xml2
uptu web technology unit 2 Xml2uptu web technology unit 2 Xml2
uptu web technology unit 2 Xml2
 
Xml ppt
Xml pptXml ppt
Xml ppt
 
Sgml and xml
Sgml and xmlSgml and xml
Sgml and xml
 
Basic Data Types in C++
Basic Data Types in C++ Basic Data Types in C++
Basic Data Types in C++
 
Abap slides user defined data types and data
Abap slides user defined data types and dataAbap slides user defined data types and data
Abap slides user defined data types and data
 
uptu web technology unit 2 Xml2
uptu web technology unit 2 Xml2uptu web technology unit 2 Xml2
uptu web technology unit 2 Xml2
 
uptu web technology unit 2 Xml2
uptu web technology unit 2 Xml2uptu web technology unit 2 Xml2
uptu web technology unit 2 Xml2
 
Web Design L2 - Playing with Tags
Web Design L2 - Playing with TagsWeb Design L2 - Playing with Tags
Web Design L2 - Playing with Tags
 

Similar to Php ch-2_html_forms_and_server_side_scripting

html forms and server side scripting
html forms and server side scriptinghtml forms and server side scripting
html forms and server side scriptingbantamlak dejene
 
php-mysql-tutorial-part-3
php-mysql-tutorial-part-3php-mysql-tutorial-part-3
php-mysql-tutorial-part-3tutorialsruby
 
&lt;b>PHP&lt;/b>/MySQL &lt;b>Tutorial&lt;/b> webmonkey/programming/
&lt;b>PHP&lt;/b>/MySQL &lt;b>Tutorial&lt;/b> webmonkey/programming/&lt;b>PHP&lt;/b>/MySQL &lt;b>Tutorial&lt;/b> webmonkey/programming/
&lt;b>PHP&lt;/b>/MySQL &lt;b>Tutorial&lt;/b> webmonkey/programming/tutorialsruby
 
php-mysql-tutorial-part-3
php-mysql-tutorial-part-3php-mysql-tutorial-part-3
php-mysql-tutorial-part-3tutorialsruby
 
&lt;img src="../i/r_14.png" />
&lt;img src="../i/r_14.png" />&lt;img src="../i/r_14.png" />
&lt;img src="../i/r_14.png" />tutorialsruby
 
CS1520 Session 2 - Simple Router
CS1520 Session 2 - Simple RouterCS1520 Session 2 - Simple Router
CS1520 Session 2 - Simple RouterSalim Malakouti
 
10_introduction_php.ppt
10_introduction_php.ppt10_introduction_php.ppt
10_introduction_php.pptGiyaShefin
 
Php interview questions
Php interview questionsPhp interview questions
Php interview questionssekar c
 
10_introduction_php.ppt
10_introduction_php.ppt10_introduction_php.ppt
10_introduction_php.pptMercyL2
 
chapter Two Server-side Script lang.pptx
chapter  Two Server-side Script lang.pptxchapter  Two Server-side Script lang.pptx
chapter Two Server-side Script lang.pptxalehegn9
 
Sperimentazioni di Tecnologie e Comunicazioni Multimediali: Lezione 5
Sperimentazioni di Tecnologie e Comunicazioni Multimediali: Lezione 5Sperimentazioni di Tecnologie e Comunicazioni Multimediali: Lezione 5
Sperimentazioni di Tecnologie e Comunicazioni Multimediali: Lezione 5Salvatore Iaconesi
 
server side scripting basics by Bantamlak Dejene
server side scripting basics by Bantamlak Dejeneserver side scripting basics by Bantamlak Dejene
server side scripting basics by Bantamlak Dejenebantamlak dejene
 
server side scripting basics
server side scripting basicsserver side scripting basics
server side scripting basicsbantamlak dejene
 
Working with data.pptx
Working with data.pptxWorking with data.pptx
Working with data.pptxSherinRappai
 
PHP Basics Ebook
PHP Basics EbookPHP Basics Ebook
PHP Basics EbookSwanand Pol
 

Similar to Php ch-2_html_forms_and_server_side_scripting (20)

html forms and server side scripting
html forms and server side scriptinghtml forms and server side scripting
html forms and server side scripting
 
php-mysql-tutorial-part-3
php-mysql-tutorial-part-3php-mysql-tutorial-part-3
php-mysql-tutorial-part-3
 
&lt;b>PHP&lt;/b>/MySQL &lt;b>Tutorial&lt;/b> webmonkey/programming/
&lt;b>PHP&lt;/b>/MySQL &lt;b>Tutorial&lt;/b> webmonkey/programming/&lt;b>PHP&lt;/b>/MySQL &lt;b>Tutorial&lt;/b> webmonkey/programming/
&lt;b>PHP&lt;/b>/MySQL &lt;b>Tutorial&lt;/b> webmonkey/programming/
 
php-mysql-tutorial-part-3
php-mysql-tutorial-part-3php-mysql-tutorial-part-3
php-mysql-tutorial-part-3
 
&lt;img src="../i/r_14.png" />
&lt;img src="../i/r_14.png" />&lt;img src="../i/r_14.png" />
&lt;img src="../i/r_14.png" />
 
CS1520 Session 2 - Simple Router
CS1520 Session 2 - Simple RouterCS1520 Session 2 - Simple Router
CS1520 Session 2 - Simple Router
 
10_introduction_php.ppt
10_introduction_php.ppt10_introduction_php.ppt
10_introduction_php.ppt
 
Php interview questions
Php interview questionsPhp interview questions
Php interview questions
 
introduction_php.ppt
introduction_php.pptintroduction_php.ppt
introduction_php.ppt
 
10_introduction_php.ppt
10_introduction_php.ppt10_introduction_php.ppt
10_introduction_php.ppt
 
chapter Two Server-side Script lang.pptx
chapter  Two Server-side Script lang.pptxchapter  Two Server-side Script lang.pptx
chapter Two Server-side Script lang.pptx
 
Sperimentazioni di Tecnologie e Comunicazioni Multimediali: Lezione 5
Sperimentazioni di Tecnologie e Comunicazioni Multimediali: Lezione 5Sperimentazioni di Tecnologie e Comunicazioni Multimediali: Lezione 5
Sperimentazioni di Tecnologie e Comunicazioni Multimediali: Lezione 5
 
server side scripting basics by Bantamlak Dejene
server side scripting basics by Bantamlak Dejeneserver side scripting basics by Bantamlak Dejene
server side scripting basics by Bantamlak Dejene
 
server side scripting basics
server side scripting basicsserver side scripting basics
server side scripting basics
 
forms.pptx
forms.pptxforms.pptx
forms.pptx
 
Working with data.pptx
Working with data.pptxWorking with data.pptx
Working with data.pptx
 
lab4_php
lab4_phplab4_php
lab4_php
 
lab4_php
lab4_phplab4_php
lab4_php
 
PHP Basics Ebook
PHP Basics EbookPHP Basics Ebook
PHP Basics Ebook
 
phptutorial
phptutorialphptutorial
phptutorial
 

More from bantamlak dejene

object oriented fundamentals in vb.net
object oriented fundamentals in vb.netobject oriented fundamentals in vb.net
object oriented fundamentals in vb.netbantamlak dejene
 
Vb ch 3-object-oriented_fundamentals_in_vb.net
Vb ch 3-object-oriented_fundamentals_in_vb.netVb ch 3-object-oriented_fundamentals_in_vb.net
Vb ch 3-object-oriented_fundamentals_in_vb.netbantamlak dejene
 
Vb ch 2-introduction_to_.net
Vb ch 2-introduction_to_.netVb ch 2-introduction_to_.net
Vb ch 2-introduction_to_.netbantamlak dejene
 

More from bantamlak dejene (6)

object oriented fundamentals in vb.net
object oriented fundamentals in vb.netobject oriented fundamentals in vb.net
object oriented fundamentals in vb.net
 
introduction to .net
introduction to .netintroduction to .net
introduction to .net
 
introduction to vb.net
introduction to vb.netintroduction to vb.net
introduction to vb.net
 
Vb ch 3-object-oriented_fundamentals_in_vb.net
Vb ch 3-object-oriented_fundamentals_in_vb.netVb ch 3-object-oriented_fundamentals_in_vb.net
Vb ch 3-object-oriented_fundamentals_in_vb.net
 
Vb ch 2-introduction_to_.net
Vb ch 2-introduction_to_.netVb ch 2-introduction_to_.net
Vb ch 2-introduction_to_.net
 
Vb ch 1-introduction
Vb ch 1-introductionVb ch 1-introduction
Vb ch 1-introduction
 

Recently uploaded

Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Mark Simos
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...Fwdays
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machinePadma Pradeep
 
APIForce Zurich 5 April Automation LPDG
APIForce Zurich 5 April  Automation LPDGAPIForce Zurich 5 April  Automation LPDG
APIForce Zurich 5 April Automation LPDGMarianaLemus7
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Patryk Bandurski
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr BaganFwdays
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitecturePixlogix Infotech
 
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Wonjun Hwang
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Mattias Andersson
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek SchlawackFwdays
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...shyamraj55
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brandgvaughan
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsMark Billinghurst
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024Lorenzo Miniero
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 3652toLead Limited
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfAddepto
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Commit University
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationSafe Software
 

Recently uploaded (20)

Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
 
DMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special EditionDMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special Edition
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machine
 
APIForce Zurich 5 April Automation LPDG
APIForce Zurich 5 April  Automation LPDGAPIForce Zurich 5 April  Automation LPDG
APIForce Zurich 5 April Automation LPDG
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC Architecture
 
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brand
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR Systems
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdf
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
 

Php ch-2_html_forms_and_server_side_scripting

  • 1. Chapter Two: HTML Forms and Server Side Scripting 11/27/2019 BantamlakDejene,Information Technology 1
  • 2. Create a Simple Form using Php 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 tags look like <form action="script.php" method="post"></form> 11/27/2019 BantamlakDejene,Information Technology 2
  • 3. Cont.…. In terms of PHP, the most important attribute of your form tag is action, which dictates to which page the form data will be sent. The second attribute method has its own, but post is the value you’ll use most frequently. The different inputs be the text boxes, radio buttons, select menus, check boxes, etc. are placed within the opening and closing form tags. As you’ll see in the next section, what kinds of inputs your form has makes little difference to the PHP script handling it. You should, however, pay attention to the names you give your form inputs, as they’ll be of critical importance when it comes to your PHP code. 11/27/2019 BantamlakDejene,Information Technology 3
  • 4. Receive Data from a Form in Php Now that the HTML form has been created, it’s time to write a bare- bones PHP script to handle it. To say that this script will be handling the form means that the PHP page will do something with the data it receives (which is the data the user entered into the form). In this chapter, the scripts will simply print the data back to the Web browser. In later examples, form data will be stored in a MySQL database, compared against previously stored values, sent in emails, and more. 11/27/2019 BantamlakDejene,Information Technology 4
  • 5. Cont.…. The beauty of PHP and what makes it so easy to learn and use is how well it interacts with HTML forms. PHP scripts store the received information in special variables. For example, say you have a form with an input defined like so: <input type="text" name="city" /> Whatever the user types into that input will be accessible via a PHP variable named $_REQUEST['city']. It is very important that the spelling and capitalization match exactly! PHP is case-sensitive when it comes to variable names, so $_REQUEST['city'] will work, but $_Request['city'] and $_REQUEST['City'] will have no value. 11/27/2019 BantamlakDejene,Information Technology 5
  • 6. Cont.…. Element Name Variable Name Name $_REQUEST['name'] Email $_REQUEST['email'] comments $_REQUEST['comments'] Age $_REQUEST['age'] Gender $_REQUEST['gender'] Submit $_REQUEST['submit'] 11/27/2019 BantamlakDejene,Information Technology 6
  • 7. Cont.…. All of those examples use two separate files: one that displays the form and another that receives its submitted data. While there’s certainly nothing wrong with this approach, there are advantages to putting the entire process into one script. To have one page both display and handle a form, a conditional must check which action (display or handle) should be taken: if (/* form has been submitted */) { // Handle the form. } else { // Display the form. } 11/27/2019 BantamlakDejene,Information Technology 7
  • 8. Cont.…. The question, then, is how to determine if the form has been submitted. The answer is simple, after a bit of explanation. When you have a form that uses the POST method and gets submitted back to the same page, two different types of requests will be made of that script. The first request, which loads the form, will be a GET request. This is the standard request made of most Web pages. When the form is submitted, a second request of the script will be made, this time a POST request (as long as the form uses the POST method). With this in mind, you can test for a form’s submission by checking the request method, found in the $_SERVER array: if ($_SERVER['REQUEST_METHOD'] = = 'POST') { // Handle the form. } else { // Display the form. } 11/27/2019 BantamlakDejene,Information Technology 8
  • 9. Cont.…. If you want a page to handle a form and then display it again (e.g., to add a record to a database and then give an option to add another), drop the else clause: if ($_SERVER['REQUEST_METHOD'] = = 'POST') { // Handle the form. } // Display the form. 11/27/2019 BantamlakDejene,Information Technology 9
  • 10. 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. Whether erroneous data is purposefully malicious or just unintentionally inappropriate, it’s up to you the Web architect to test it against expectations. 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. You saw an example of this in the preceding script. One issue with the isset() function is that an empty string tests as true, meaning that isset() is not an effective way to validate text inputs and text boxes from an HTML form. 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. 11/27/2019 BantamlakDejene,Information Technology 10
  • 11. 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: if (condition) { // Do something! } An if can also have an else clause: if (condition) { // Do something! } else { // Do something else! } 11/27/2019 BantamlakDejene,Information Technology 11
  • 12. Cont.…. Symbol Meaning Type Example = = is equal to Comparison $x = = $y != is not equal to Comparison $x != $y < less than Comparison $x < $y > Greater than Comparison $x > $y <= less than or equal to Comparison $x <= $y >= Greater than or equal to Comparison $x >= $y ! not Logical !$x && and Logical $x && $y AND and Logical $x and $y || or Logical $x || $y OR or Logical $x or $y XOR and not logical $x XOR $y 11/27/2019 BantamlakDejene,Information Technology 12
  • 13. Cont.…. A condition can be true in PHP for any number of reasons. 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. In the second example, a new function, isset(), is introduced. This function checks if a variable is “set,” meaning that it has a value other than NULL (as a reminder, NULL is a special type in PHP, representing no set value). You can also use the comparative and logical operators in conjunction with parentheses to make more complicated expressions. 11/27/2019 BantamlakDejene,Information Technology 13
  • 14. Use For and While Loops The other two types of loops you’ll use are for and while. The while loop looks like this: while (condition) { // Do something. } As long as the condition part of the loop is true, the loop will be executed. Once it becomes false, the loop is stopped. If the condition is never true, the loop will never be executed. 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. } 11/27/2019 BantamlakDejene,Information Technology 14
  • 15. Work with Forms and Arrays of Data Now it’s time to learn about another type, the array. Unlike strings and numbers, an array can hold multiple, separate pieces of information. An array is therefore like a list of values, each value being a string or a number or even another array. Arrays are structured as a series of key value pairs, where one pair is an item or element of that array. For each item in the list, there is a key (or index) associated with it. PHP supports two kinds of arrays: indexed, which use numbers as the keys, and associative, which use strings as keys. As in most programming languages, with indexed arrays, arrays will begin with the first index at 0, unless you specify the keys explicitly. 11/27/2019 BantamlakDejene,Information Technology 15
  • 16. Cont.…. An array follows the same naming rules as any other variable. This means that you might not be able to tell that $var is an array as opposed to a string or number. The important syntactical difference arises when accessing individual array elements. To refer to a specific value in an array, start with the array variable name, followed by the key within square brackets: $band = $artists[0]; // The Mynabirds echo $states['MD']; // Maryland You can see that the array keys are used like other values in PHP: numbers (e.g., 0) are never quoted, whereas strings (MD) must be. Because arrays use a different syntax than other variables, and can contain multiple values, printing them can be trickier. This will not work: echo "My list of states: $states"; 11/27/2019 BantamlakDejene,Information Technology 16
  • 17. Introduction to Regular Expressions Sometimes you want to check for a specific structure as opposed to a specific value. Regular expressions allow this type of matching. Besides the few examples below and the inclusion of some regular expression syntax, no tutorial on regular expressions is given here. 11/27/2019 BantamlakDejene,Information Technology 17
  • 18. Cont.…. ^ Start of string $ End of string . Any single character ( ) Group of expressions [] Item range (e.g. [afg] means a, f, or g) [^] Items not in range ( e.g. [^cde] means not c, d, or e ) - (dash) character range within an item range (e.g. [a-z] means a through z) | (pipe) Logical or ( e.g. (a|b) means a or b ) ? Zero or one of preceding character/item range * Zero or more of preceding character/item range + One or more of preceding character/item range {integer} Exactly integer of preceding character/item range ( e.g. a{2} ) 11/27/2019 BantamlakDejene,Information Technology 18
  • 19. Cont.…. {integer,} Integer or more of preceding character/item range ( e.g. a{2,} ) {integer, integer} From integer to integer (e.g. a{2,4} means 2 to four of a ) Escape character [:punct:] Any punctuation [:space:] Any space character [:blank:] Any space or tab [:digit:] Any digit: 0 through 9 [:alpha:] All letters: a-z and A-Z [:alnum:] All digits and letters: 0-9, a-z, and A-Z [:xdigit:] Hexadecimal digit [:print:] Any printable character [:upper:] All uppercase letters: A-Z [:lower:] All lowercase letters: a-z 11/27/2019 BantamlakDejene,Information Technology 19
  • 20. Cont.…. c Control character s Whitespace S Not whitespace d Digit (0-9) D Not a digit w Letter (a-z, A-Z) W Not a letter x Hexadecimal digit O Octal digit 11/27/2019 BantamlakDejene,Information Technology 20 Character classes:–
  • 21. Cont.…. 11/27/2019 BantamlakDejene,Information Technology 21 I Case-insensitive S Period matches newline M ^ and $ match lines U Ungreedy matching E Evaluate replacement X Pattern over several lines Modifiers:–