Sei sulla pagina 1di 16

Wolkite University, College of CCI, Department of IT

Unit 2: HTML Forms and Server Side Scripting

2.1. Use Conditionals and Operators

Conditional statements are used to perform different actions based on different conditions.
They are used to perform different actions for different conditions.

PHP conditional statements:

 if statement - executes some code if one condition is true


 if...else statement - executes some code if a condition is true and another code if that
condition is false
 if...elseif....else statement - executes different codes for more than two conditions
 switch statement - selects one of many blocks of code to be executed

The if Statement - Syntax


if (condition) {
code to be executed if condition is true;
}

Example

<?php
$dt = date("H");
if ($dt < "1") {
echo "The first day of the Month!";
}
?>

The if...else Statement - Syntax


if (condition) {
code to be executed if condition is true;
} else {
code to be executed if condition is false;
}

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%!"
}
?>

The if...elseif....else Statement - Syntax


if (condition) {
code to be executed if this condition is true;
} elseif (condition) {
code to be executed if this condition is true;
} else {
code to be executed if all conditions are false;
}

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!";
}
?>

The PHP switch Statement


The switch statement is used to select one of many blocks of code to be executed.

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

2.2. Validate Form Data


Validation of form data helps to implement some basic security feature to the user's input so that
users cannot insert potentially harmful data that compromise the website security or might break
the application.

This can be done by:


 Passing all variables through PHP's htmlspecialchars() function.

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:
&lt;script&gt;location.href('http://www.hacked.com')&lt;/script&gt;
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/&quot;&gt;&lt;script&gt;alert('hacked')&lt;/script&gt;">

 Asking the users to enter comments about the website.


 Displaying the contact form and process the submitted form data.
 Sanitizing and validating user inputs. Redisplays the form with an error message if any
required field is missing or due to incorrect inputs.
 Remembering which fields the user has already filled in, and prefills those fields when the
form redisplayed due to validation error.
 Send an email to the website administrator and display a success message to the user if the
data is successfully submitted and accepted.

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)

Simple HTML Form


<html>
<head>
</head>
<body>
<table border ="1">
<tr><td>
<center><p><b>Simple Registration Form </b></p></center>
<form method="post" action="mdata.php">
<p><b>Name: <input type="text" name="name"> <sup>*</sup></p>
<p>E-mail: <input type="text" name="email" required> <sup>*</sup></p>
<center><p> <Input type="submit" name="submit"
value="Send"></p></center>
</form>
</td></tr>
</table>
</body>
</html>

4
Wolkite University, College of CCI, Department of IT
PHP Code to validate user Inputs to the form

Syntax:

if(!preg_match("/^[a-zA-Z ]*$/",$name)) //Returns true if pattern exists

 ^ and $ - require the whole string match


 [] - is a character class - any character inside is allowed.
 a-zA-Z - Range that the character class understands
 \d - is a number.

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();
?>

Checking Valid Emails

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();
?>

2.3. Send Values to a 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'].
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>

Creating the PHP script as links.php:


<html>
<head>
<title>Greetings!</title>
</head>
<body>
<?php
$name = $_GET['name'];
print "<p>Hello, <span style=\"font-weight: bold;\">$name</span>!</p>";
?>
</body>
</html>
Run the links.html page to see the result.

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] . ".";
?>

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

There are two ways to create indexed arrays:

The index can be assigned automatically (index always starts at 0), like this:

$cars = array("Volvo", "BMW", "Toyota");

or the index 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');

The count() Function

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);
?>

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. PHP Associative Arrays

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.";
?>
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>

Looping through an 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>";
}
?>

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

A two-dimensional array is an array of arrays as shown below:

Car Name Stock Sold


Volvo 22 18
BMW 15 13
Ford 5 2
Land Rover 17 15

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

for ($i = 0; $i < 4; $i++) //Rows


{
echo "<p><b>Car number $i</b></p>";
echo "<ul>";
for ($j = 0; $j < 3; $j++) //Columns
{
echo "<li>".$cars[$i][$j]."</li>";
}
echo "</ul>";
}

The elements in an array can be sorted in alphabetical or numerical order, descending or


ascending.

Sort Functions for Arrays

 sort() - sort arrays in ascending order


 rsort() - sort arrays in descending order

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

2.5. For and While Loops

2.5.1. 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;
}

11
Advanced Internet Programming Course handout – Chapter II
?>

2.5.2. 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>";
}
?>

The 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++;
}
?>

2.5.3. 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
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);
?>

2.6. Use Get or Post


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

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 postTest.php script file:


<html>
<body>
Hello <?php echo $_POST["name"]; ?><br>
Your email address is: <?php echo $_POST["email"]; ?>
</body>
</html>

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>

The “getTest.php" Script file:


<html>
<body>
Hello <?php echo $_GET["name"]; ?><br>
Your email address is: <?php echo $_GET["email"]; ?>
</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.

2.7. Receive Data from a Form in PHP


2.7.1. Retrieving form data sent via GET

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>

The $_GET Method Script


if (isset($_GET['send'])) //Check if the form is submitted.
{

//Retrieve the form data by using the element's name attributes value as key
$firstname = $_GET['firstname'];
$lastname = $_GET['lastname'];

//Display the results


echo 'Your name is ' . $lastname . ' ' . $firstname;
exit;

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.

2.7.2. Using the POST

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

Potrebbero piacerti anche