Chapter : Two
HTML Forms and Server-Side Scripting
• What is form in HTML/PHP?
• How can you write the syntax of form ?
• Did you remembered some attributes of forms ?
• Differentiate the attributes of form?
• What are the value of attributes in form ?
• What is validation ? Can you mention some common validation types?
What is Form in PHP
• One of the most powerful features of PHP is the way it handles HTML forms.
• Form used to gather input from users or used to pass data to a server.
• The <form> element defines a form that is used to collect user input:
• A form is the way information is gotten from a browser to a server.
The syntax:
<form action=“url to submit the form filled” method=“get” or “post”>
<!–- form contents -->
</form>
<Form> Attributes and values
• Name – the name of the form
• Method – Indicates how the information in the form will be sent to the web server
when the form is submitted. The value of method attribute can be GET or POST.
 Action – the URL of the script that the data will be sent to – this is the page that will display
once the submit button is clicked.
 action=“url” {url of the server-side script to post data to}
 When a user click on the submit button, the form data is sent to a PHP file, called
"welcome.php":
• enctype=“enctype” -specifies how the form-data should be encoded when submitting it to
the server {application/x-www-form-urlencoded, multipart/form-data, text/plain, … }
multipart/form-data – used when uploading files, does not encode any character. text/plain-
convert spaces into + symbols but special characters are not converted.
• The enctype attribute Can be used only method=“POST”.
• <form name student action="welcome.php" method="post">
 Eg.<form name=“student” method=“post” action=“welcome.php” enctype=“text/plain” >
….
</form>
<Form> Attributes and values…
The GET Method:-
• Has restriction to send to server/ database parts upto 1024 characters only.
• Can't be used to send binary data, like images or word documents, to the server because the
GET method sends the encoded user information.
• The data sent by GET can be accessed using QUERY_STRING environment variable.
• Never use GET method for systems which have password or other sensitive information.
• The information sent from a form with the GET method is visible to everyone (it will be
displayed in the browser's address bar). it is possible to bookmark the page.
• For example http://localhost/xy.php?name=bekele$age=39
Method Attributes values…
Method Attributes values…
• The POST Method
• The POST method does not have any restriction on data size to be sent.
• Relatively secured and could large data in requesting and responding data
• The POST method can be used to send ASCII as well as binary data.
• The data sent by POST method goes through HTTP header is secured enough on HTTP protocol.
• Variables sent with HTTP POST are not visible in the URL. , it is not possible to bookmark the
page
• The Information sent from a form with the POST method is invisible to others
• For example http://localhost/xy.php
 Several tags are used in connection with forms:
 <form>
 <input>
 <select> …… </select>
 <option> ……</option>
 <textarea> …… </textarea>
 <fieldset>……. </fieldset>
 <legend>…… </legend>
 </form>
 All objects must be inside of a form tag.
FORM Tag Elements
Elements of <Form>
• Form elements are different types of input elements, like text fields, checkboxes,
radio buttons, submit buttons, and more. Those objects are called widgets(e.g.,
radio buttons and checkboxes).
• All of the widgets, or components of a form are defined in the content of a <form>
tag.
• <input type="text“, “password“, “radio”, “image”, "checkbox“, “File”, ”Button”,
"submit“, "reset" > and <select>, <textarea>, <fieldset>
Elements of <Form>
Save as Form.html
<html> Save as welcome.php
<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>
Cont.…
• The $_REQUEST variable
• The PHP $_REQUEST variable contains the contents of $_GET, $_POST, and
$_COOKIE variables.
• This variable can be used to get the result from form data sent with both the GET
and POST methods.
•$username=$_REQUEST['username'];
•$password=$_REQUEST['password'];
Cont.…
• The PHP header () function supplies raw HTTP headers to the browser and
can be used to redirect it to another location.
• The redirection script should be at the very top of the page to prevent any
other part of the page from loading.
• The target is specified by the Location: header as the argument to the header
() function. header("location:homepage.php").
• After calling this function the exit () function can be used to halt parsing of
rest of the code.
The $_REQUEST variable
Form Validation
• User input should be validated whenever possible.
• You can validate the form input on two places,
• Client side (done with javascript) ,required = “ required“,maxlength=“5”
• Server side (done with PHP) , if(!preg_match("/^[A-Z,a-z]+$/", $name))
• Client side validation is faster, and will reduce server load.
• For security reason, use server side validation if the form accesses a database.
• Server side form validation with PHP can act as a backup just in case the user
switch off java script support on the browser.
Cont..
• Form validation must be carried out on every form element to guarantee that
the input is correct and processing incorrect input values can make your
application give unpredictable result.
• A good way to validate a form on the server is to post the form to itself <?
php $_PHP_SELF ?>, instead of jumping (welcome.php) to a different
page. The user will then get the error messages on the same page as the
form.
• This makes it easier to discover the error.
Common Validations
 We can categorize validation in to the following groups:
Presence Validation
String Length Validation
Type Validation
Inclusion in set Validation
Uniqueness Validation
Format Validation
The preg_match() function will tell you whether a string contains matches of a
pattern.
Cont..
• Presence Validation: check if there is something in a field or if a variable is not empty.
Cont..
• String Length Validation: is used to check if a value is within a certain range.
• $password=”itec1234”;
• $min=6;
• $max=10;
• if(strlen($password)<$min&&strlen($password)>$max)
• die("Password doesnot fulfill the requirement");
Cont..
Cont..
• Type Validation: is checking whether the given value is number, string or of another type.
Cont..
• Type Validation: is checking whether the given value is number, string or of another
type.
• Write a php program that can accept students age only 2 digits ?
Cont..
• Write a php program that can accept phone number which is started by +251 ?
Cont..
• Inclusion in set Validation: Is used to validate whether the value is in the set
• Write a php program that can accept students’sex with letters m or f ?
Cont..
• Uniqueness Validation: Is used to validate whether the value which is going to be submitted to a
Cont..
• Format Validation: Is used to validate whether the value has the right format e.g.
email with @ symbol, currency with $ symbol, DateTime with AM or PM
• It uses regular expression on the string Syntax: preg_match($regexp,$subject)
• if(!preg_match("/^[@]+$/", $Email)){
• echo "You enterd invaid input";
• }else
• {echo "Your Email is".$Email;
• }
Cont..
• Validate e-mail address: Used to check an email is valid, i.e to have valid forms. if
(!filter_var($value, FILTER_VALIDATE_EMAIL))
• die("Invalid email format");
• Or
• if(!preg_match("/([w-]+@[w-]+.[w-]+)/",$value))
• die("Invalid email format");
• URLAddress: If there is an input field named "website" we can check for a valid
URL address like this
• if (!preg_match("/b(?:(?:https?|ftp)://|www.)[-a-z0-9+&@#/%?=~_|!:,.;]*[-a-z0-
9+&@#/%=~_|]/i",$value)) {
• die("Invalid URL");
Decision Statements
Read Read Read more!!!
26
PHP Control Structures
if, while, do, for, switch are virtually identical to those in C++ and Java
PHP Decision Making
The if, elseif ...else and switch statements are used to take
decision based on the different condition.
1. if...else statement - use this statement if you want to execute
a set of code when a condition is true and another if the
condition is not true
2. elseif statement - is used with the if...else statement to
execute a set of code if one of several condition are true
3. switch statement - is used if you want to select one of many
blocks of code to be executed, use the Switch statement. The
switch statement is used to avoid long blocks of if..elseif..else
code.
27
If …else statement
Normal if..then..else statement
• Ex.
if ($a<5) {
$b=$a+10;
}
else {
$b=$a*2;
}
28
If...elseif... else statement
The example below introduces these constructs:
<?php
// Conditionals
if ($a) {
print "a is true<BR>n";
}
elseif ($b) {
print "b is true<BR>n";
}
else
{
print "neither a or b is true<BR>n";
}
29
The Switch Statement
• If you want to select one of many blocks of code to be executed, use the
Switch statement.
• The switch statement is used to avoid long blocks of if..elseif..else code.
• Syntax
switch (expression)
{
case label1:
code to be executed if expression = label1;
break;
case label2:
code to be executed if expression = label2;
break;
default:
code to be executed if expression is different from both label1 and label2;
}
30
Example
 The switch statement works in an unusual way.
 First it evaluates given expression then seeks a label to
match the resulting value.
 If a matching value is found then the code associated with
the matching label will be executed or if none of the labels
match then statement will execute any specified default
code.
31
<html><body>
<?php
$d=date("D");
switch ($d)
{
case "Mon":
echo "Today is Monday";
break;
case "Tue":
echo "Today is Tuesday";
break;
case "Wed":
echo "Today is Wednesday";
break;
case "Thu":
echo "Today is Thursday";
break;
case "Fri":
echo "Today is Friday";
break;
case "Sat":
echo "Today is Saturday"; break;
case "Sun":
echo "Today is Sunday";
break;
default:
echo "Wonder which day is this ?“;
}
?>
</body></html>
32
PHP Control Structures….
// Loops
do {
$c = test_something();
} while ($c);
while ($d) {
print "ok<BR>n";
$d = test_something();
}
for ($i = 0; $i < 10; $i++) {
print "i=$i<BR>n";
}
?>
33
PHP Control Structures…..
For loop
for (starting value;ending value;increment)
{
Statements
}
• Ex.
for ($i=0; $i<10; $i++)
{
echo $i;
}
34
PHP Control Structures….
While Loop
while (something is true)
{
some statements
}
Ex.
$i=0;
while ($i<10){
echo $i;
$i++;
}
35
PHP Expressions and Operators
4 Similar to those in C++ / Java / Perl
4 Be careful with a few operators
• / in PHP is always floating point division
• To get integer division, we must cast to int
$x = 15;
$y = 6;
echo ($x/$y), (int) ($x/$y), "<BR />";
• Output is 2.5 2
36
PHP operators
Operator Meaning
== Is Equal to
!= Not Equal to
< Is less than
<= Is less than or equal to
> Is Greater than
>= Is Greater than or equal to
&& and And
|| or Or
37
Refer the following PHP Built-in Functions
• Trim()
• Empty()
• Preg_match()
• Preg_replace()
• html_entities()
• Htmlspecialcharacters()
• Add_slashes()
• Strip_slashes()
• Mail()
PHP Operators
• Operators are used to perform operations on variables and values.
• PHP divides the operators in the following groups:
• Arithmetic operators
• Assignment operators
• Comparison operators
• Increment/Decrement operators
• Logical operators
• String operators
• Array operators
• Conditional assignment operators 39
Cont…
Read Read Read more!!!
40
Reading Assignment
 PHP Operators
 PHP Conditional Statements
Thank You!!!

2-Chapter Edit.pptx debret tabour university

  • 1.
    Chapter : Two HTMLForms and Server-Side Scripting • What is form in HTML/PHP? • How can you write the syntax of form ? • Did you remembered some attributes of forms ? • Differentiate the attributes of form? • What are the value of attributes in form ? • What is validation ? Can you mention some common validation types?
  • 2.
    What is Formin PHP • One of the most powerful features of PHP is the way it handles HTML forms. • Form used to gather input from users or used to pass data to a server. • The <form> element defines a form that is used to collect user input: • A form is the way information is gotten from a browser to a server. The syntax: <form action=“url to submit the form filled” method=“get” or “post”> <!–- form contents --> </form>
  • 3.
    <Form> Attributes andvalues • Name – the name of the form • Method – Indicates how the information in the form will be sent to the web server when the form is submitted. The value of method attribute can be GET or POST.  Action – the URL of the script that the data will be sent to – this is the page that will display once the submit button is clicked.  action=“url” {url of the server-side script to post data to}  When a user click on the submit button, the form data is sent to a PHP file, called "welcome.php":
  • 4.
    • enctype=“enctype” -specifieshow the form-data should be encoded when submitting it to the server {application/x-www-form-urlencoded, multipart/form-data, text/plain, … } multipart/form-data – used when uploading files, does not encode any character. text/plain- convert spaces into + symbols but special characters are not converted. • The enctype attribute Can be used only method=“POST”. • <form name student action="welcome.php" method="post">  Eg.<form name=“student” method=“post” action=“welcome.php” enctype=“text/plain” > …. </form> <Form> Attributes and values…
  • 5.
    The GET Method:- •Has restriction to send to server/ database parts upto 1024 characters only. • Can't be used to send binary data, like images or word documents, to the server because the GET method sends the encoded user information. • The data sent by GET can be accessed using QUERY_STRING environment variable. • Never use GET method for systems which have password or other sensitive information. • The information sent from a form with the GET method is visible to everyone (it will be displayed in the browser's address bar). it is possible to bookmark the page. • For example http://localhost/xy.php?name=bekele$age=39 Method Attributes values…
  • 6.
    Method Attributes values… •The POST Method • The POST method does not have any restriction on data size to be sent. • Relatively secured and could large data in requesting and responding data • The POST method can be used to send ASCII as well as binary data. • The data sent by POST method goes through HTTP header is secured enough on HTTP protocol. • Variables sent with HTTP POST are not visible in the URL. , it is not possible to bookmark the page • The Information sent from a form with the POST method is invisible to others • For example http://localhost/xy.php
  • 7.
     Several tagsare used in connection with forms:  <form>  <input>  <select> …… </select>  <option> ……</option>  <textarea> …… </textarea>  <fieldset>……. </fieldset>  <legend>…… </legend>  </form>  All objects must be inside of a form tag. FORM Tag Elements
  • 8.
    Elements of <Form> •Form elements are different types of input elements, like text fields, checkboxes, radio buttons, submit buttons, and more. Those objects are called widgets(e.g., radio buttons and checkboxes). • All of the widgets, or components of a form are defined in the content of a <form> tag. • <input type="text“, “password“, “radio”, “image”, "checkbox“, “File”, ”Button”, "submit“, "reset" > and <select>, <textarea>, <fieldset>
  • 9.
    Elements of <Form> Saveas Form.html <html> Save as welcome.php <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>
  • 10.
    Cont.… • The $_REQUESTvariable • The PHP $_REQUEST variable contains the contents of $_GET, $_POST, and $_COOKIE variables. • This variable can be used to get the result from form data sent with both the GET and POST methods. •$username=$_REQUEST['username']; •$password=$_REQUEST['password'];
  • 11.
    Cont.… • The PHPheader () function supplies raw HTTP headers to the browser and can be used to redirect it to another location. • The redirection script should be at the very top of the page to prevent any other part of the page from loading. • The target is specified by the Location: header as the argument to the header () function. header("location:homepage.php"). • After calling this function the exit () function can be used to halt parsing of rest of the code.
  • 12.
  • 13.
    Form Validation • Userinput should be validated whenever possible. • You can validate the form input on two places, • Client side (done with javascript) ,required = “ required“,maxlength=“5” • Server side (done with PHP) , if(!preg_match("/^[A-Z,a-z]+$/", $name)) • Client side validation is faster, and will reduce server load. • For security reason, use server side validation if the form accesses a database. • Server side form validation with PHP can act as a backup just in case the user switch off java script support on the browser.
  • 14.
    Cont.. • Form validationmust be carried out on every form element to guarantee that the input is correct and processing incorrect input values can make your application give unpredictable result. • A good way to validate a form on the server is to post the form to itself <? php $_PHP_SELF ?>, instead of jumping (welcome.php) to a different page. The user will then get the error messages on the same page as the form. • This makes it easier to discover the error.
  • 15.
    Common Validations  Wecan categorize validation in to the following groups: Presence Validation String Length Validation Type Validation Inclusion in set Validation Uniqueness Validation Format Validation The preg_match() function will tell you whether a string contains matches of a pattern.
  • 16.
    Cont.. • Presence Validation:check if there is something in a field or if a variable is not empty.
  • 17.
    Cont.. • String LengthValidation: is used to check if a value is within a certain range. • $password=”itec1234”; • $min=6; • $max=10; • if(strlen($password)<$min&&strlen($password)>$max) • die("Password doesnot fulfill the requirement");
  • 18.
  • 19.
    Cont.. • Type Validation:is checking whether the given value is number, string or of another type.
  • 20.
    Cont.. • Type Validation:is checking whether the given value is number, string or of another type. • Write a php program that can accept students age only 2 digits ?
  • 21.
    Cont.. • Write aphp program that can accept phone number which is started by +251 ?
  • 22.
    Cont.. • Inclusion inset Validation: Is used to validate whether the value is in the set • Write a php program that can accept students’sex with letters m or f ?
  • 23.
    Cont.. • Uniqueness Validation:Is used to validate whether the value which is going to be submitted to a
  • 24.
    Cont.. • Format Validation:Is used to validate whether the value has the right format e.g. email with @ symbol, currency with $ symbol, DateTime with AM or PM • It uses regular expression on the string Syntax: preg_match($regexp,$subject) • if(!preg_match("/^[@]+$/", $Email)){ • echo "You enterd invaid input"; • }else • {echo "Your Email is".$Email; • }
  • 25.
    Cont.. • Validate e-mailaddress: Used to check an email is valid, i.e to have valid forms. if (!filter_var($value, FILTER_VALIDATE_EMAIL)) • die("Invalid email format"); • Or • if(!preg_match("/([w-]+@[w-]+.[w-]+)/",$value)) • die("Invalid email format"); • URLAddress: If there is an input field named "website" we can check for a valid URL address like this • if (!preg_match("/b(?:(?:https?|ftp)://|www.)[-a-z0-9+&@#/%?=~_|!:,.;]*[-a-z0- 9+&@#/%=~_|]/i",$value)) { • die("Invalid URL");
  • 26.
  • 27.
    PHP Control Structures if,while, do, for, switch are virtually identical to those in C++ and Java PHP Decision Making The if, elseif ...else and switch statements are used to take decision based on the different condition. 1. if...else statement - use this statement if you want to execute a set of code when a condition is true and another if the condition is not true 2. elseif statement - is used with the if...else statement to execute a set of code if one of several condition are true 3. switch statement - is used if you want to select one of many blocks of code to be executed, use the Switch statement. The switch statement is used to avoid long blocks of if..elseif..else code. 27
  • 28.
    If …else statement Normalif..then..else statement • Ex. if ($a<5) { $b=$a+10; } else { $b=$a*2; } 28
  • 29.
    If...elseif... else statement Theexample below introduces these constructs: <?php // Conditionals if ($a) { print "a is true<BR>n"; } elseif ($b) { print "b is true<BR>n"; } else { print "neither a or b is true<BR>n"; } 29
  • 30.
    The Switch Statement •If you want to select one of many blocks of code to be executed, use the Switch statement. • The switch statement is used to avoid long blocks of if..elseif..else code. • Syntax switch (expression) { case label1: code to be executed if expression = label1; break; case label2: code to be executed if expression = label2; break; default: code to be executed if expression is different from both label1 and label2; } 30
  • 31.
    Example  The switchstatement works in an unusual way.  First it evaluates given expression then seeks a label to match the resulting value.  If a matching value is found then the code associated with the matching label will be executed or if none of the labels match then statement will execute any specified default code. 31
  • 32.
    <html><body> <?php $d=date("D"); switch ($d) { case "Mon": echo"Today is Monday"; break; case "Tue": echo "Today is Tuesday"; break; case "Wed": echo "Today is Wednesday"; break; case "Thu": echo "Today is Thursday"; break; case "Fri": echo "Today is Friday"; break; case "Sat": echo "Today is Saturday"; break; case "Sun": echo "Today is Sunday"; break; default: echo "Wonder which day is this ?“; } ?> </body></html> 32
  • 33.
    PHP Control Structures…. //Loops do { $c = test_something(); } while ($c); while ($d) { print "ok<BR>n"; $d = test_something(); } for ($i = 0; $i < 10; $i++) { print "i=$i<BR>n"; } ?> 33
  • 34.
    PHP Control Structures….. Forloop for (starting value;ending value;increment) { Statements } • Ex. for ($i=0; $i<10; $i++) { echo $i; } 34
  • 35.
    PHP Control Structures…. WhileLoop while (something is true) { some statements } Ex. $i=0; while ($i<10){ echo $i; $i++; } 35
  • 36.
    PHP Expressions andOperators 4 Similar to those in C++ / Java / Perl 4 Be careful with a few operators • / in PHP is always floating point division • To get integer division, we must cast to int $x = 15; $y = 6; echo ($x/$y), (int) ($x/$y), "<BR />"; • Output is 2.5 2 36
  • 37.
    PHP operators Operator Meaning ==Is Equal to != Not Equal to < Is less than <= Is less than or equal to > Is Greater than >= Is Greater than or equal to && and And || or Or 37
  • 38.
    Refer the followingPHP Built-in Functions • Trim() • Empty() • Preg_match() • Preg_replace() • html_entities() • Htmlspecialcharacters() • Add_slashes() • Strip_slashes() • Mail()
  • 39.
    PHP Operators • Operatorsare used to perform operations on variables and values. • PHP divides the operators in the following groups: • Arithmetic operators • Assignment operators • Comparison operators • Increment/Decrement operators • Logical operators • String operators • Array operators • Conditional assignment operators 39
  • 40.
    Cont… Read Read Readmore!!! 40 Reading Assignment  PHP Operators  PHP Conditional Statements
  • 41.