HTML Forms and Server Side Scripting: Chapter Two
HTML Forms and Server Side Scripting: Chapter Two
Prepared by Alem D.
outline
• Use Conditionals and Operators
• Validate Form Data
• Send Values to a Script Manually
• Work with Forms and arrays of data
• Use For and While Loops
• Create a Simple Form using PHP
• Use Get or Post
• Receive Data from a Form in PHP
• Introduction to regular expressions
PHP conditional statements
• Very often when we write code, we want to perform different actions for
different decisions. We can use conditional statements in our code to do
this.
• In PHP we have the following conditional statements:
if statement - executes some code only if a specified condition is true
if...else statement - executes some code if a condition is true and
another code if the condition is false
if...else if....else statement - selects one of several blocks of code to be
executed
switch statement - selects one of many blocks of code to be executed
Syntax for if statement
If(condition){
// code to be executed
For example
If($age<23){
}
Syntax for if..else statement
• If(condition){
//code to be executed
}
Else{
// condition to be executed if the above statement is false.
}
Example
$date=Date(“D”);
If($date==“Wed”){
Echo “today is Wednesday”;
}
else{
Echo “today is not Wednesday ”;
Syntax for if…elseif…else statement
If(condition){
//condition to be executed
}
elseif(condition){
// condition to be executed if the above statement is not true
}
Else{
// condition to be executed if all the above statements are not true.
}
Syntax for Switch statement
• The value of the expression is compared with the value in each case
• After the code is executed , break is used to stop the code from
running into the next case.
<script>location.href('http://www.google.com')</script>
Simple HTML registration form
<form action=“where to send data” method=“POST/GET”>
Name <input type="text" name="name">
<br>
Password <input type="password" name="psw1">
<br>
Confirm-pass <input type="password" name="psw2">
<br>
Email <input type="text" name="email">
<br>
<input type="submit" name="ok" value="Send">
</form>
Using GET or POST
• The super global variables $_GET and $_POST are used to collect user inputs.
• they are always accessible, regardless of scope and can be accessed 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 POST method
• Both GET and POST create an array - array (key => value, key2 => value2 ...).
This array holds key/value pairs where:-
• Keys are the names of the form controls.
• Values are the input data from the user.
…CONT…
• 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 has also a limit on the amount of information to send(About 2000
characters)
• GET may be used for sending Non sensitive data
• GET should never be used to send Password , or other sensitive
information
…CONT…
• When to Use POST?
?>
…CONT…
Receiving form data with POST method
When you submit a form to a server through the POST method, PHP provides a super global variable called $_POST.
Example
<?php
if (isset($_POST["ok"])) {// check if the form is submitted
$name=$_POST["name"];
$pass1=$_POST["psw1"];
$pass2=$_POST["psw2"];
$email=$_POST["email"];
Echo $name;
}
?>
Note Isset() checks if the form is submitted
Form Validation and sanitizing
Validate Name
$name=$_POST[“name”];
$name=trim($name);
$name=stripslashes($name);
$name=htmlspecialchars($name);
if (!preg_match("/^[a-zA-Z ]*$/",$name)) {
$nameErr = "Only letters and white space allowed";
echo $nameErr;
}
…CONT…
Validating password
$pass1=$_POST[“psw1”];
$pass2=$_POST[“psw2”];
If($passw1!=$pass2){
Echo “wrong password please re enter”;
}
elseif{Strlen($pass)<8){
Echo “password length should be greater than 8”;
}
Else{
Echo “correct password”;
}
…CONT…
Checking valid email
$email = $_POST["email"];
$email = stripslashes($email);
$email = htmlspecialchars($email);
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$emailErr = "Invalid email format";
echo $emailErr;
Or you can use input type =email.
Sending Values to script Manually
• One can pass data to a PHP script by creating an HTML form that uses
the GET method. But you can also use the same idea to send data to a
PHP page without the use of the form - by creating links like: <a
href="links.php?id=22">Some Link</a>
• The link, which could be dynamically generated by PHP, will pass the
value 22 to links.php, accessible in $_GET['id'].
For and While Loops
The for loop
• PHP for loops execute a block of code a specified number of times. The for loop is used
when you know in advance how many times the script should run.
Syntax:
for (init counter; test counter; increment counter)
{
code to be executed;
}
Parameters:
• init counter: Initialize the loop counter value
• test counter: Evaluated for each loop iteration. If true, the loop continues otherwise the
loop ends.
• increment counter: Increases the loop counter value
• Example
<?php
for ($i = 0; $i <= 10; $i++)
{
echo $i;
}
The foreach loop
• The foreach loop works only on arrays, and is used to loop through each key
or value pair in an array.
Syntax
foreach ($array as $value)
{
code to be executed;
}
• For every iteration the value of the current array element is assigned to
$value and the array pointer is moved by one, until it reaches the last array
element.
• Example:
<?php
$colors = array("red", "green", "blue", "yellow");
foreach ($colors as $value)
{
echo "$value <br>";
}
?>
While loop
• The “while” loop executes a block of code as long as the specified condition is true.
Syntax
while (condition is true)
{
code to be executed;
}
Example
<?php
$n = 1; while($n <= 5)
{
echo $n <br>"; $n++;
}
The do…..while loop
• In a do while loop the condition is tested after executing the
statements within the loop. This means that the do while loop would
execute its statements at least once, even if the condition is false the
first time. It will then check the condition, and repeat the loop while
the specified condition is true.
Syntax
Do
{
code to be executed;
} while(condition is true)
Example 1:
<?php
$n = 1; do {
echo $n <br>";
$n++;
} while ($n <= 5);
?>
Work with arrays of data
• An array is a special variable that stores multiple values in one single variable:
Creating an Array
• The formal method of creating an array is to use the array() function.
Syntax:
$list = array ('apples', 'bananas', 'oranges'); // Index not specified
Example:
<?php
$cars = array("Volvo", "BMW", "Toyota");
echo "I like " . $cars[0] . ", " . $cars[1] . " and " . $cars[2] . ".";
?>
…CONT…
In PHP, there are three types of arrays:
• Indexed arrays - Arrays with a numeric index
• Associative arrays - Arrays with named keys
• Multidimensional arrays - Arrays containing one or more arrays
a. Indexed arrays
• Numerically indexed arrays are supported in most programming languages.
In PHP, the indices start at zero by default, although you can alter this value.
• The index can be assigned automatically (index always starts at 0), like this:
$cars = array("Volvo", "BMW", "Toyota");
or the index and value can be assigned manually:
$cars[0] = "Volvo"; $cars[1] = "BMW"; $cars[2] = "Toyota";
• Index can also be assigned as:
$list = array (1 => 'apples', 2 => 'bananas', 3 => 'oranges');
.CONT…
The count() Function
• The count() function is used to return the length (the number of elements)
of an array:
Example
<?php
$mamal = array(“Dog", “Cat", “Rat");
echo count($mamal);
?>
…CONT…
Looping through an Indexed Array
• A for loop can be used to loop through and print all the values of an indexed
array.
Example
<?php
$departments = array(“IT", “SC", “IS", “SE");
$deptcnt = count($ departments);
for($i = 0; $i < $ deptcnt; $i++) { echo $ departments[$i]; echo "<br>"; }
?>
b. Associative array
Associative arrays are arrays that use named keys that you assign to them.
There are two ways to create an associative array:
$age = array("Abebe"=>"35", "Tolesa"=>"37", "Ajyet"=>"43");
or:
$age['Abebe'] = "35"; $age['Tolesa'] = "37"; $age['Ajyet'] = "43";
Example 1:
<?php
$age = array("Abebe"=>"35", "Tolesa"=>"37", "Ajyet"=>"43"); echo "Ajyet is " .
$age['Ajyet'] . " years old.";
?>
…CONT…
Looping through associative array
• foreach loop can be used to loop through and print all the values of an associative array.
Example
<?php
$age = array("Abebe"=>"35", "Tolesa"=>"37", "Ayantu"=>"43");
foreach($age as $i => $i_value)
{
echo "Key=" . $i . ", Value=" . $i_value; echo "<br>";
}
?>
Multi Dimensional Array
• A multidimensional array is an array containing one or more arrays. The dimension of an
array indicates the number of indices you need to select an element.
• For a two-dimensional array you need two indices to select an element
• For a three-dimensional array you need three indices to select an element
Example
$cars = array
(
array("Volvo",22,18), array("BMW",15,13), array("Ford",5,2), array("Land Rover",17,15)
);
Assignment(write a program that displays each elements of the above multi
dimensional array)
Some functions for arrays
• The elements in an array can be sorted in alphabetical or numerical order,
descending or ascending.
• Sort()- sort arrays in ascending order
• rsort() - sort arrays in descending order
• asort() - sort associative arrays in ascending order, according to the value
• ksort() - sort associative arrays in ascending order, according to the key
• arsort() - sort associative arrays in descending order, according to the
value
• krsort() - sort associative arrays in descending order, according to the key
END OF CHAPTER 2