Professional Documents
Culture Documents
November, 2018
Assosa, Ethiopia
Contents
–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
Introduction
• Handling an HTML form with PHP is perhaps the most important process in any dynamic
Web site.
• There are two steps here:
– create the HTML form
– 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.
<form action=“process.php" method="post">
</form>
– the most important attribute of your form tag here is action, which dictates to which
page the form data will be sent.
– The second attribute method has its own issues, you will learn in other topics in this
chapter.
• The different inputs like text boxes, radio buttons, select menus, check boxes, etc. are
placed within the opening and closing form tags.
• So you place different types of form elements inside it.
Conditional Statements
• Php control statements are the same as any other programming language
• There are several statements in PHP that you can use to make decisions:
• PHP also allows you to write code that perform different actions based on the
results of a logical or comparative test conditions at run time.
• This means, you can create test conditions in the form of expressions that
evaluates to either true or false and
• based on these results you can perform certain actions.
– The if statement
– The if...else statement
– The if...elseif....else statement
– The switch...case statement
The if statement
• The if statement is used to execute a block of code only if the specified condition evaluates to
true.
• This is the simplest PHP's conditional statements and can be written like:
if(condition){
// Code to be executed
}
• The following example will output "Have a nice weekend!" if the current day is Friday:
<?php
$d = “Fri";
if($d == "Fri"){
echo "Have a nice weekend!";
}
?>
T h e if ...e lse S t a t ement
• The if...else statement allows you to execute one block of code if the specified condition is evaluates to
true and another block of code if it is evaluates to false. It can be written, like this:
if(condition){
// Code to be executed if condition is true
} else{
// Code to be executed if condition is false
}
• The following example will output "Have a nice weekend!" if the current day is Friday, otherwise it will
output "Have a nice day!“
<?php
$d = “Fri";
if($d == “Fri"){
echo "Have a nice weekend!";
}
else{
echo "Have a nice day!";
}
?>
The if...elseif...else Statement
• The if...elseif...else a special statement that is used to combine multiple if...else statements.
if(condition){
// Code to be executed if condition is true
} elseif(condition){
// Code to be executed if condition is true
} else{
// Code to be executed if condition is false
}
• The following example will output "Have a nice weekend!" if the current day is Friday, and "Have a nice Sunday!"
if the current day is Sunday, otherwise it will output "Have a nice day!“
<?php
$d = “Fri";
if($d == "Fri"){
echo "Have a nice weekend!";
} elseif($d == "Sun"){
echo "Have a nice Sunday!";
}else{
echo "Have a nice day!";
}
?>
PHP Switch…Case Statements
• The switch-case statement tests a variable against a series of values until it finds a
match, and then executes the block of code corresponding to that match.
switch(n){
case label1:
// Code to be executed if n=label1
break;
case label2:
// Code to be executed if n=label2
break;
...
default:
// Code to be executed if n is different from all labels
}
• Php switch statements
– Case: it takes a single variable as input and then checks it against all the different cases you set up
for that switch statement (e.g. case November: Output: Current Month!)
– Break (to stop executing all the cases that follow the correct case)
– Default case (when the variable doesn’t match all conditions, no case before default default:)
PHP Switch…Case Statements. . . Example
<?php case "Fri":
$today = “Mon"; echo "Today is Friday.The weekend! .";
switch($today){ break;
case "Mon": case "Sat":
echo "Today is Monday. Clean your dorm."; echo "Today is Saturday. Its movie time.";
break; break;
case "Tue": case "Sun":
echo "Today is Tuesday. Buy some food."; echo "Today is Sunday. Do some rest.";
break; break;
case "Wed": default:
echo "Today is Wednesday. AIP Class ."; echo "No information available.";
break; break;
case "Thu": }
echo "Today is Thursday. Clean your Lab."; ?>
break;
PHP Switch…Case Statements. . . Cont’
• The switch-case statement is an alternative to the if-elseif-else
statement, which does almost the same thing.
• The switch-case statement differs from the if-elseif-else
statement in one important way.
– The switch statement executes line by line (i.e. statement by statement)
and once PHP finds a case statement that evaluates to true, it's not only
executes the code corresponding to that case statement,
– but also executes all the subsequent case statements till the end of the
switch block automatically.
– To prevent this add a break statement to the end of each case block.
• The break statement tells PHP to break out of the switch-case
statement block once it executes the code associated with the first
true case.
Validate Form
• As noticed in the introduction the first step to validate the form is to create the form itself
• We will not discuss in detail about creating HTML form (refer fundamental of IP)
• but I will show you one quick example (Example1)from the fundamental of IP course so that
it may be used throughout the chapter.
Validate Form . . . Cont’
• The next step after creating the form is, handling or receiving the data
entered by user for further processing.
• PHP scripts store the received information in special variables $_REQUEST
• $_REQUEST is a special variable type, known as a super global.
– It stores all of the data sent to a PHP page through either the GET or POST method,
as well as data accessible in cookies.
– Super global will be discussed later in the chapter, cookies in another chapter.
• Example:
<input type="text" name="city" />
Whatever the user types into, that input will be accessible via a PHP variable
named $_REQUEST['city'].
• Note: spelling and capitalization must match exactly!
Validate Form . . . Cont’
• Hence, PHP is case-sensitive when it comes to variable names:
– $_REQUEST['city'] will work
– $_ Request['city'] and $_REQUEST['City'] will have no value.
• In this next example, you will simply receive and print the entered data back to
the Web browser from the already-created HTML form in Example1
(process.php)
• Next slide . . .
process.php
User fills their information as shown below
User submits the information by clicking on “Submit
My Information” button and the result is shown
below
Validate Form . . . Cont’
Form elements to PHP variables
Element Name Variable Name
fname $_REQUEST['fname']
mname $_REQUEST[‘mname']
lname $_REQUEST[‘lname']
age $_REQUEST['age']
email $_REQUEST[‘mail']
gender $_REQUEST[‘gender']
detail $_REQUEST[‘detail']
• In the previous chapter, chapter1, you saw one simple example during “numbering
and operator session” which is pen buying application.
• you have practiced by specifying the number of pens manually inside the code
• Now, you are asked to create a simple form that accepts
– The name of the buyer or user (name field)
– The number of pens to buy and calculate the total cost by adding tax.
• Taxation is based on the number of pens:
– 5-20 pens: 5%
– 21-50 pens: 10%
– 51-100 pens: 15%
– 101-300 pens: 20%
– >300 pens: 25%
Validate Form . . . Cont’
• In the previous slides, you saw HTML form creation and form data handling with example
• 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.
• 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 (including 0,
FALSE, or an empty string, but not NULL).
– Another is pass all variables through PHP's htmlspecialchars() function. This function will
replace HTML chars like < and > to their HTML version < and >.
Validate Form . . . Cont’
– 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.
– you can use the empty() function. It checks if a variable has an empty value: an empty string,
0, NULL, or FALSE.
Reading Assignment
• Read the details of the above discussed super global
arrays and others (if any)by referring to the internet
and practice it by your own
Arrays and strings
• Because arrays and strings are so commonly used together, PHP has two functions for converting
between them:
$array = explode (separator, $string);//string to array
$string = implode (glue, $array);//array to string
• The key to using and understanding these two functions is the separator and glue relationships.
• When turning an array into a string, you establish the glue the characters or code that will be
inserted between the array values in the generated string.
• Conversely, when turning a string into an array, you specify the separator, which is the token that
marks what should become separate array elements.
• For example, start with a string:
$s1 = 'Mon-Tue-Wed-Thu-Fri';
$days_array = explode ('-', $s1);
The $days_array variable is now a five element array, with Mon indexed at 0, Tue indexed at 1,
etc.
$s2 = implode (', ', $days_array);
• The $s2 variable is now a comma separated list of days: Mon, Tue, Wed,Thu, Fri.
Arrays and strings . . .cont.
Sorting Arrays
• One of the many advantages arrays have over the other variable types is the
ability to sort them.
• PHP includes several functions you can use for sorting arrays, all simple in syntax:
$names = array (‘ymr', ‘you', ‘we');
sort($names);
• 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
• During sorting using print_r() or loops through array is recommended
Sorting Arrays in indexed arrays
Sorting Arrays in associative arrays
Function in PHP
• In PHP, there two types of functions:
– built-in
– user defined
Built-in
• PHP has a lot of built-in functions (more than thousand), addressing almost every need you might
have, making it a very rich language Some of these are:
– Echo, print, include(), require(), sort(), etc.
• You have seen examples in this chapter in which single file contains all of the required HTML and
PHP code.
• But as you develop more complex Web applications, you’ll see that this approach is not often
practical.
• A better way to create dynamic Web applications is to divide your scripts and Web sites into
distinct parts, each part being stored in its own file.
• Frequently, you will use multiple files to extract the HTML from the PHP or to separate out
commonly used processes.
Function in PHP. . .cont.
• PHP has two functions for incorporating external files:
– include()
– require()
• In terms of functionality, it also doesn’t matter what extension the included file uses, be it .php or
.html
• To use them, your PHP script would have a line like
– include('filename.php');
– require('/path/to/filename.html');
• Both functions also have a *_once() version, which guarantees that the file in question is included
only once regardless of how many times a script may (presumably inadvertently) attempt to
include it.
– require_once('filename.php');
– include_once('filename.php');
• Because require_once() and include_once() require extra work from the PHP module (i.e.,
PHP must first check that the file has not already been included),
• it’s best not to use these two functions unless a redundant include is likely to occur (which can
happen on complex sites).
Function in PHP. . .cont.
Absolute vs. Relative paths
• When referencing any external item, be it an included file in PHP, a CSS document in HTML, or an
image, you have the choice of using either an absolute or a relative path.
An absolute path references a file starting from the root directory of the computer:
include ('C:/php/includes/file.php');
– Assuming file.php exists in the named location, the inclusion will work, no matter the location of the
referencing (parent) file (barring any permissions issues)
• A relative path uses the referencing (parent) file as the starting point. To move up one folder, use
two periods together. To move into a folder, use its name followed by a slash.
• So assuming the current script is in the htdocs/Myapps folder and you want to include something
in htdocs/Myapps2, the code would be:
include('../Myapps2/file.php');
• A relative path will remain accurate, even if the site is moved to another server, as long as the files
maintain their current relationship to each other.
Function in PHP. . .cont.
Why include() and require()?
• you can type up a common logo, header or menu, footer, database connectivity file
that you want all your web pages to include.
• When you add a new page to your site, instead of having to update the links on
several web pages, you can simply change the Menu file.
Difference
• If PHP cannot find the file you will see an error message (warning)
– in include () function the echo statement will be executed after the
error
– but in required () function the echo statement will not be executed
– because the script execution will died after the require function returned a
fatal error!
Function in PHP. . .cont.
Examples: create navigation and footer in separate file, save it with different folder
(include) and include in the parent (index) page (include(include/nav.php);)
nav.php
footer.php
Function in PHP. . .cont.
• In each page you can include the navigation and footer as follow
• At the top of each page
115