Chapter 2 HTML Forms and Server Side Scripting PDF
Chapter 2 HTML Forms and Server Side Scripting PDF
Conditional statements are used to perform different actions based on different conditions.
They are used to perform different actions for different conditions.
Example
<?php
$dt = date("H");
if ($dt < "1") {
echo "The first day of the Month!";
}
?>
Example
<?php
$item = 10; // Set this to a number greater than 5!
if ($items > 5)
{
echo "Discount is 10%!";
}
else ($items <= 5)
1
Advanced Internet Programming Course handout – Chapter II
{
echo "Discount is 5%!"
}
?>
Example
<?php
$dt = date("D");
if($dt == "Sat")
{
echo "The first Weekend!";
}
elseif($dt == "Sun")
{
echo "The last day of the week!";
}
else{
echo "It is weekday!";
}
?>
Syntax
switch (n) {
case label1:
// code to be executed if n=label1;
break;
case label2:
// code to be executed if n=label2;
break;
case label3:
// code to be executed if n=label3;
break;
...
default:
// code to be executed if n is different from all labels;
}
2
Wolkite University, College of CCI, Department of IT
Example
<?php
$myDay = date("D");
switch($myDay){
case "Mon":
echo "Today is the first day!";
break;
case "Tue":
echo "Today is second day!";
break;
case "Wed":
echo "Today is third day!";
break;
case "Thu":
echo "Today is Fourth day!";
break;
case "Fri":
echo "Today is Fifth day!";
break;
case "Sat":
echo "Today is Sixth day!";
break;
case "Sun":
echo "Today is Seventh day!";
break;
default:
echo "None!";
break;
}
?>
When we use the htmlspecialchars() function; then if a user tries to submit a script code it
will be translated as HTML code.
Example 1:
<script>location.href('http://www.google.com')</script>
would be saved as HTML escaped code, like this:
<script>location.href('http://www.hacked.com')</script>
Example 2:
3
Advanced Internet Programming Course handout – Chapter II
<form method="post" action="<?php echo
htmlspecialchars($_SERVER["PHP_SELF"]);?>">
Will be saved as
<form method="post"
action="test_form.php/"><script>alert('hacked')</script>">
We can also also do two more things when the user submits the form:
1. Strip unnecessary characters (extra space, tab, newline) from the user input data (with the
PHP trim() function)
2. Remove backslashes (\) from the user input data (with the PHP stripslashes() function)
4
Wolkite University, College of CCI, Department of IT
PHP Code to validate user Inputs to the form
Syntax:
Example:
<?php
function validate(){
$name = $_POST["name"];
$name = stripslashes($name);
$name = htmlspecialchars($name);
if (!preg_match("/^[a-zA-Z ]*$/",$name)) {
$nameErr = "Only letters and white space allowed";
echo $nameErr;
}
}
validate();
?>
Syntax:
(!filter_var($email, FILTER_VALIDATE_EMAIL))
Example:
<?php
function validate(){
$email = $_POST["email"];
$email = stripslashes($email);
$email = htmlspecialchars($email);
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$emailErr = "Invalid email format";
echo $emailErr;
}
}
5
Advanced Internet Programming Course handout – Chapter II
validate();
?>
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'].
Example: (File name - links.html)
Creating the Form
<html>
<body>
<div><p>Click the following link:</p>
<ul>
<li><a href="hello.php? name=Abebe"> Abebe </a></li>
<li><a href="hello.php? name=Bekele"> Bekele </a></li>
<li><a href="hello.php? name=Tolesa"> Tolesa </a></li>
<li><a href="hello.php? name=Ayantu"> Ayantu </a></li>
</ul>
</div>
</body>
</html>
6
Wolkite University, College of CCI, Department of IT
2.4. Work with Forms and 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] . ".";
?>
a. Indexed arrays
The index can be assigned automatically (index always starts at 0), like this:
$cars[0] = "Volvo";
$cars[1] = "BMW";
$cars[2] = "Toyota";
Index can also be assigned as:
$list = array (1 => 'apples', 2 => 'bananas', 3 => 'oranges');
The count() function is used to return the length (the number of elements) of an array:
Example
<?php
7
Advanced Internet Programming Course handout – Chapter II
$mamal = array(“Dog", “Cat", “Rat");
echo count($mamal);
?>
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. PHP Associative Arrays
Associative arrays are arrays that use named keys that you assign to them.
Example 1:
<?php
$age = array("Abebe"=>"35", "Tolesa"=>"37", "Ajyet"=>"43");
echo "Ajyet is " . $age['Ajyet'] . " years old.";
?>
Example 2:
<html>
<head> <title>Food Menu!</title> </head>
<body>
<h1>Our Weekly Menu </h1>
<?php
8
Wolkite University, College of CCI, Department of IT
$fdmenu = array ('Monday' => 'Clam Chowder', 'Tuesday' => 'White Chicken Chili',
'Wednesday' => 'Vegetarian');
print "<p>$fdmenu </p>";
print_r ($fdmenu);
?>
</body>
</html>
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>";
}
?>
Multidimensional Arrays
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
Two-dimensional Arrays
9
Advanced Internet Programming Course handout – Chapter II
The data in the above table can be stored in a two dimensional array as:
$cars = array
(
array("Volvo",22,18),
array("BMW",15,13),
array("Ford",5,2),
array("Land Rover",17,15)
);
Now the two-dimensional $cars array contains four arrays, and it has two indices: row and
column. To get access to the elements of the $cars array we must point to the row and column:
Example 1:
<?php
echo $cars[0][0].": In stock: ".$cars[0][1].", sold: ".$cars[0][2].".<br>";
echo $cars[1][0].": In stock: ".$cars[1][1].", sold: ".$cars[1][2].".<br>";
echo $cars[2][0].": In stock: ".$cars[2][1].", sold: ".$cars[2][2].".<br>";
echo $cars[3][0].": In stock: ".$cars[3][1].", sold: ".$cars[3][2].".<br>";
?>
We can also put for loop inside another for loop to get the elements of the $cars array (we still
have to point to the two indices):
Example
10
Wolkite University, College of CCI, Department of IT
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
Example 1:
<?php
$cars = array("Volvo", "BMW", "Toyota");
sort($cars); // Sorting in ascending order
rsort($cars); // Sorting in descending order
?>
Example 2:
<?php
$age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");
asort($age); //Sorting an associative array in ascending order, according to the value:
ksort($age); //Sorting an associative array in ascending order, according to the key
arsort($age); //Sorting an associative array in descending order, according to the value:
krsort($age); //Sorting an associative array in descending order, according to the key
?>
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;
}
11
Advanced Internet Programming Course handout – Chapter II
?>
Example:
<?php
$colors = array("red", "green", "blue", "yellow");
foreach ($colors as $value)
{
echo "$value <br>";
}
?>
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++;
}
?>
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
12
Wolkite University, College of CCI, Department of IT
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);
?>
Example:
<html>
<body>
<form action="postTest.php" method="post">
Name: <input type="text" name="name"><br>
E-mail: <input type="text" name="email"><br>
<input type="submit">
</form>
</body>
</html>
When the user fills out the form above and clicks the submit button, the form data is sent for
processing with the HTTP POST method to a PHP file named "postTest.php".
The same thing can be done by using the Using the GET method:
13
Advanced Internet Programming Course handout – Chapter II
Example:
<html>
<body>
<form action="getTest.php" method="get">
Name: <input type="text" name="name"><br>
E-mail: <input type="text" name="email"><br>
<input type="submit">
</form>
</body>
</html>
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.
Both GET and POST are treated as $_GET and $_POST. These are superglobals (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 HTTP POST method.
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. (About 2000 characters.)
However, because the variables are displayed in the URL, it is possible to bookmark the
page which can be useful in some cases.
GET may be used for sending non-sensitive data.
GET should NEVER be used for sending passwords or other sensitive information!
14
Wolkite University, College of CCI, Department of IT
When to use POST?
Information sent with the POST method is invisible to others (all names/values are
embedded within the body of the HTTP request)
POST has no limits on the amount of information to send.
POST supports advanced functionality such as support for multi-part binary input while
uploading files to server.
It is not possible to bookmark the page. (Because the variables are not displayed in the
URL)
Developers prefer POST for sending form data.
When submitting a form through the GET method, PHP provides a superglobal variable,
called $_GET. PHP uses this $_GET variable to create an associative array with keys to
access all the sent information. The key is created using the element's name attribute values.
Example:
Form with the GET Method
<form action="get-method.php" method="get">
<input type="text" name="firstname" placeholder="First Name" />
<input type="text" name="lastname" placeholder="Last Name" />
<input type="submit" name="send" />
</form>
//Retrieve the form data by using the element's name attributes value as key
$firstname = $_GET['firstname'];
$lastname = $_GET['lastname'];
15
Advanced Internet Programming Course handout – Chapter II
}
Firstly, the isset() function checks if the form has been submitted by using the element's
name attribute value "send" as key and pass it to the $_GET[] superglobal variable.
Then the form data, (first name and last name) are retrieved by using the same
method, passing their respective name attribute values into the $_GET['name as key'] array
parameter, and each is assigned to a variable name that was used to display the results.
The form POST method sends information via HTTP header. All name/value pairs sent through
this method is invisible to anyone else since all the information are embedded within the body of
the HTTP request.
When you submit a form to a server through the POST method, PHP provides a superglobal
variable called $_POST. The $_POST variable is used by PHP to create an associative array with
an access key ($_POST['name as key']). The key is created automatically by PHP when the
form is submitted. PHP uses the form field element name attribute (name="unique-name-
here") to create the key.
16