You are on page 1of 115

COLLEGE OF COMPUTING AND INFORMATICS

Department of Information Technolog y

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.

– Whether erroneous data is purposefully malicious or just unintentionally inappropriate, it’s up to


you the Web architect to test it against expectations

• 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 &lt; and &gt;.
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.

• The first aim of form validation is


– seeing if something was entered or selected in form elements.

• The second goal is to ensure that submitted data is:


– of the right type (numeric, string, etc.)

– of the right format (like an email address), or

– a specific acceptable value (like $gender being equal to either M or F )


Validate Form . . . Cont’
• Validating HTML form data before you use it is critical to Web security and achieving
professional results.
• Here, conditionals check that every referenced form element has a value, in Example1
• You can add some CSS code, two CSS class inside head tag as shown below
Continue from the previous slide which is the actual validation code using if. . . else
Validate Form . . . Cont’-Sample Snapshot: all the 7 fields Empty
Va lid a te F o r m . . . C o n t ’ - Sa mpl e Sn a p s h ot: w h e n th e 3 fi e l d s Em p ty
Va lid a te F o r m . . . C o n t ’ - Sa mpl e Sn a p s h ot: w h e n o n l y 1 fi e l d Em p ty
Va lid a te F o r m . . . C o n t ’ - Sa mpl e Sn a p s h ot: w h e n a l l i n fo r m ati o n fi l l e d
Little modification on Age (to be number) and Gender (Append
welcome message based on their gender )
Va lid a te F o r m . . . C o n t ’ - Sa mpl e Sn a p s h ot: w h e n a g e b e c o me s n o t N u mb e r
Va lid a te F o r m . . . C o n t ’ - Sa mpl e Sn a p s h ot: w i th c o r r e ct a g e a n d M a le
Send Values to a Script Manually

• Inside the code ………….


Work With Forms And Arrays Of Data
• An array can hold multiple, separate pieces of information.
• It is therefore like a list of values, each value being a string or a number
or even another array.
• Arrays are structured as a series of key value pairs, where one pair is
an item or element of that array.
• For each item in the list, there is a key (or index) associated with it
• An array follows the same naming rules as any other variable.
Creating Array
• There are different ways to create an array in php
– By assigning a value e.g.
$cities[0]=“Assosa”;
$cities[1]=“Bahirdar”;
– By using the array() function, which is mostly used technique.
$cities=array(“Assosa”, “Bahirdar”, “Mekelle”, “Dire Dewa”, “Adama”);
– Comma separated list of elements
• The array will remember the order in which the elements were stored.
• In php there are three types of arrays:
– Indexed: Arrays with a numeric index
– Associative: Arrays with named (string) keys
– Multidimensional: Arrays containing one or more arrays
• The details will be in next slides
Array . . .cont.
Indexed array
• It can store numbers, strings and any object but their index will be represented by numbers.
• By default array index starts from zero.
• Values are stored and accessed in linear fashion.
• The index can be assigned automatically (index always starts at 0) or assigned manually
• Example: creating and accessing indexed arrays
$laptops=array(“Dell”, “HP”, “Toshiba”, “Lenovo”, “Asus”, “Apple”, “Acer”);
Echo $laptops [0]; // outputs Dell
Echo $laptops [3]; // outputs Lenovo
• Determine or find the number of elements in an array using count() or sizeof()
• Example: $size= count($laptops);//returns 7
Array . . .cont.
Array . . .cont.
Associative array
• An array with string as index
• The associative arrays are very similar to numeric arrays in term of
functionality but they are different in terms of their index.
• Associative array will have their index as string so that you can establish a
strong association between key and values.
• Don't keep associative array inside double quote while printing
otherwise it would not return any value.
• Example:
– To store the salaries of employees in an array, a numerically indexed array would not be
the best choice.
– Instead, we could use the employees names as the keys in our associative array, and the
value would be their respective salary.
– See this example in next slide
Array Example ( wr it e p h p c o d e t o c re a t e a n d a c c e s s a r r a y $ u n ive r sities )
Array example 1: $cities Array example 2: $universities
which use numbers as the keys which use strings as keys

Key Value Key Value


0 Assosa asu Assosa University
1 Bahirdar aau AA University
2 Mekelle astu Adama Science and Technology University
3 Dire Dewa bdu Bahirdar University
4 Adama hu Hawassa University
$city=$cities[0]; //Assosa
$university= $universities [‘asu’]; //Assosa University
Echo $university. ”, ”. $city;// Assosa University, Assosa
Note: numbers (e.g., 0) are never quoted, whereas strings (asu)must be.
Array . . .cont.
• Because arrays use a different syntax than other variables, and can contain multiple
values, printing them is different.
– E.g. $universities=array(“asu”=>”Assoa University”,”AAU”=>”AA University”);
Echo “List of universities: $universities”; //will not work
Echo “List of universities: $universities[0]”; //undefined offset 0
Echo “List of universities: $universities[‘asu’]”; //parse error
To fix this, wrap the array name and key in curly braces when an array uses strings for its keys
like:
Echo “List of universities: {$universities[‘asu’]}”; //works properly
or write the array name outside of any quotation mark like:
Echo “List of universities: “. $universities[‘asu’]; //works properly
• An array’s key can be multiple-worded strings, such as first name or phone number
• The range() function can also create an array of sequential letters and
numbers like: range(‘a’, ‘z’); range(1, 30);
Array . . .cont.
Multidimensional array
• array is an array containing one or more arrays.
• In multi-dimensional array each element in the main array can also
be an array. And each element in the sub-array can be an array, and
so on.
• Values in the multi-dimensional array are accessed using multiple
index.
– 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: create a two dimensional array to store marks of three students in
three subjects:
• See this example in next slide
Superglobal Arrays
• PHP includes several predefined arrays called the super global variables. They are always accessible
regardless of scope (in all scopes)
• They are:
– $_GET, $_POST, $_REQUEST, $_FILES, $_SERVER, $_ENV, $_SESSION, and $_COOKIE.
• The $_GET variable is where PHP stores all of the values sent to a PHP script via the GET
method (possibly but not necessarily from an HTML form).
• $_POST stores all of the data sent to a PHP script from an HTML form that uses the POST
method. $_GET and $_POST will be discussed later in this chapter.
• Both of these along with $_COOKIE are subsets of $_REQUEST, which you’ve been using.
• $_SERVER stores information about the server PHP is running on, as does $_ENV.
• $_SESSION and $_COOKIE will both be discussed in Chapter 5, “Cookies and Sessions.”
• Refer for more Super global Arrays in php
• One aspect of good security and programming is to be precise when referring to a variable.
– This means that, although you can use $_REQUEST to access form data submitted through the POST
method, $_POST would be more accurate. See example in next slide, but more details will be discussed
in lesson “use get or post”.
Superglobal Arrays: example: process.php
Superglobal Arrays

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

• At the bottom of each page

• More examples in lab class and project work!


Function in PHP. . .cont.
User defined function
• Function is a self-contained block of code that performs a specific task, which can be used
repeatedly in a program.
• Function will not execute immediately when a page loads (executed by calling it)
– There are more than 1000 built in functions in php, besides these built functions, PHP has also the
capability for you to define and use your own functions for whatever purpose.
– The syntax for making your own function is
function function_name ([parameter[, . . .]]) {
// Function code.
}
– The name of your function can be any combination of letters, numbers, and the underscore, but it must
begin with either a letter or the underscore. It is not case-sensitive
– You also cannot use an existing (built-in) function name for your function (print, echo, isset, and so on).
Function in PHP. . . Cont.
• The most common reasons to create your own functions are:
– To associate repeated code with one function call.
– To separate out sensitive or complicated processes from other code.
– To make common code bits easier to reuse
• As a general rule, functions are best used for chunks of code that may be executed
in several places in a script or Web site. This is because a user-defined function
takes up some memory.
Function arguments
• Information can passed to functions through arguments which is comma delimited list of
expression.
• There are three different ways of passing arguments to functions:
– By value (default way)

– By reference (simply add & before the variable name)


– Default argument
• Arguments by value
Function: Default argument value
• Default argument is a value assigned inside function parameter
• When we have called the function with out arguments, it takes the default value as an argument
else default argument will override with the new value.
Function: Retuning values
• In php, values are returned by a return statement .
• The return values must be specified in the variable.
• The return statement can return any type of data.
• Example: a function accepts quantity and price of products, calculates total price by adding tax
and returns this total price. (Pen Buying Application )
Variable Scope
• Every variable in PHP has a scope to it, which is to say a realm in which the variable (and therefore its
value) can be accessed.
• For starters, variables have the scope of the page in which they reside.
• If you define $var, the rest of the page can access $var, but other pages generally cannot (unless you use
special variables).
• Since included files act as if they were part of the original (including) script, variables defined before an
include() line are available to the included file.
• Further, variables defined within the included file are available to the parent (including) script after the
include() line.
• User-defined functions have their own scope: variables defined within a function are not available
outside of it, and variables defined outside of a function are not available within it.
• For this reason, a variable inside of a function can have the same name as one outside of it but still be an
entirely different variable with a different value.
• This is a confusing concept for many beginning programmers. To alter the variable scope within a function,
you can use the global statement.
Variable Scope. . . Cont.
function function_name() {
global $var;
}
$var = 20;
function_name(); // Function call.
• In this example, $var inside of the function is now the same as $var outside of it.
• This means that the function $var already has a value of 20, and if that value changes inside of the
function, the external $var’s value will also change.
• Another option for circumventing variable scope is to make use of the super globals: $_GET,
$_POST, $_REQUEST, etc.
• These variables are automatically accessible within your functions (hence, they are superglobal).
• You can also add elements to the $GLOBALS array to make them available within a function.
• All of that being said, it’s almost always best not to use global variables within a function.
• Functions should be designed so that they receive every value they need as arguments and return
whatever value (or values) need to be returned.
• Relying upon global variables within a function makes them more context-dependent, and
consequently less useful. See example in next slide
Loops in PHP
• Scripts can decide how many times to execute a block of code.
• Loop statements are designed to enable you to achieve repetitive tasks.
• A loop will continue to operate until a condition is achieved, or you explicitly
choose to exit the loop.
• Loops are used frequently in scripts to set up a block of statements that repeat.
• PHP supports following four loop types.
– for - loops through a block of code a specified number of times.
– while - loops through a block of code if and as long as a specified condition is true.
– do...while - loops through a block of code once, and then repeats the loop as long
as a special condition is true.
– foreach - loops through a block of code for each element in an array.
Loops in PHP . . . Cont.
for loop
• The for statement is used when you know how many times you want to execute a statement
or a block of statements. Syntax:
for (initialization; condition; increment)
{
code to be executed;
}
• The initializer is used to set the start value for the counter of the number of loop iterations.
Loops in PHP . . . Cont.
while loop
• The while statement will execute a block of code if and as long as a test expression is true.
• If the test expression is true then the code block will be executed. After the code has
executed the test expression will again be evaluated and the loop will continue until the test
expression is found to be false. Syntax:
while (condition is true) {
code to be executed;
}
Loops in PHP . . . Cont.
do...while Loop
• The do...while loop will always execute the block of code once, 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);
Loops in PHP . . . Cont.
Foreach loop
• The foreach statement is used to loop through arrays.
• For each pass the value of the current array element is assigned to $value and
the array pointer is moved by one and in the next pass next element will be
processed. Syntax
foreach (array as value)
{
code to be executed;
}
Loops in PHP . . . Cont.
Breaking out of a loop
• Sometimes you want your script to break out of a loop.
• PHP provides two statements for this purpose:
–break: breaks completely out of a loop and continues with
the script statements after the loop.
–continue: stops current iteration and goes back to condition
check. If condition check is true, it will go to the next
iteration.
• The break and continue statements are usually used in
conditional statements. In particular, break is used most often in
switch statements.
Loops in PHP (breaking out of a loop)
Loops in PHP (breaking out of a loop)
Loops through an array in PHP
• You’ve already seen how to access individual array elements using its keys (e.g.,
$_REQUEST['email']).
• This works when you know exactly what the keys are or if you want to refer to only a single
element.
• To access every array element, use the foreach loop:
foreach ($array as $value) {
// Do something with $value.
}
• The foreach loop will iterate through every element in $array, assigning each element’s value to
the $value variable.
• To access both the keys and values, use
foreach ($array as $key => $value) {
echo "The value at $key is : $value.";
}
• You can use any valid variable name in place of $key and $value, like just $k and $v, if you’d prefer.
Note:
• The use of loops in arrays
–Using the four types of loops and
–the three types of arrays
• The use of loops and arrays in forms
–Using the two methods (you will learn in next slides):
• POST and
• GET
• Will be elaborated in details with practical examples in Lab
and lecture classes
Create a Simple Form using PHP arrays and loops
• The following form uses arrays to dynamically create three pull-down menus together with the
foreach loop.
Use Get or Post
• A web browser communicates with the server typically using one of
the two HTTP methods GET and POST.
• Both methods pass the information differently and have different
advantages and disadvantages which deals with forms
• Before the browser sends the information, it encodes it using a scheme
called URL encoding.
• In this scheme, name/value pairs are joined with equal signs and
different pairs are separated by the ampersand.
name1=value1&name2=value2&name3=value3
• Spaces are removed and replaced with the + character and any other
nonalphanumeric characters are replaced with a hexadecimal values.
• After the information is encoded it is sent to the server.
Use Get or Post . . . Cont.
• Forms are generally used to collect data, whether the data needs to
be stored on the server (registration) or checked against the
server(login)
• Two components to a form:
– The HTML generating the form itself
– The server-side script that the form data is sent to (via GET or POST),
taking care of the processing involved
• Server should respond appropriately, redirecting the user to the appropriate
destination or generating the appropriate page
Use Get or Post . . . Cont.
• The syntax is:
$_POST[“form element name”]
$_GET[“form element name”]
• You get information from the array by using the form field name as the array key.
• For example, suppose that you echo the following field in your form that uses the
POST method:
<input type=’text’ name=’firstName’>;
• The value entered in this textbox can be accessed by
$_POST[‘firstName’]
• This contains the text the user typed into the field.
• If the form uses GET method, the above textbox can be accessed as
$_GET[“firstName”]
When to use $_GET vs. $_POST
• There difference is on encoding and form processing
• GET requests are sent via the URL, and can thus be cached,
bookmarked, shared, etc. it should be used if and only if the form
processing is idempotent (pure query form)
• GET requests are limited by the length of the URL, which can make it
necessary to use POST even for idempotent processing
• POST requests are not exposed in the URL and should be used for
sensitive data
• There is no limit to the amount of information passed via POST
The GET Method
• In GET method the data is sent as URL parameters that are usually strings of name
and value pairs separated by ampersands (&).
• GET is the default method if not specified
• In general, a URL with GET data will look like this:
http://www.assosacity.com/action.php?name=yimer&age=27
• The bold parts in the URL are the GET parameters and the italic parts are the
value of those parameters.
• More than one parameter=value can be embedded in the URL by concatenating
with ampersands (&).
• One can only send simple text data via GET method. So, GET can't be used to
send binary data, like images or word documents, to the server.
• PHP provides the super global variable $_GET to access all the information sent
either through the URL or submitted through an HTML form using the
method="get".
The GET Method . . .cont.
Advantages and Disadvantages of Using the GET Method
• Since the data sent by the GET method are displayed in the URL, it is possible to
bookmark the page with specific query string values.
• The GET method is not suitable for passing sensitive information such as the
username and password, because these are fully visible in the URL query string as
well as potentially stored in the client browser's memory as a visited page.
• The data sent by GET method can be accessed using QUERY_STRING
environment variable.
• Because the GET method assigns data to a server environment variable, the length
of the URL is limited.
• So, there is a limitation for the total data to be sent (2000 characters).
The POST Method
• In POST method the data is sent to the server as a package in a separate
communication with the processing script.
• Data sent through POST method will not visible in the URL.
• Like $_GET, PHP provide another super global variable $_POST to access all the
information sent via post method or submitted through an HTML form using the
method="post". Used to send ASCII as well as binary data
• It is more secure than GET because user-entered information is never visible in
the URL query string or in the server logs (all names/values are embedded within
the body of the HTTP request).
• There is a much larger limit on the amount of data that can be passed and one
can send text data as well as binary data (uploading a file) using POST.
• Since the data sent by the POST method is not visible in the URL, so it is not
possible to bookmark the page with specific query
Receive Data from a Form in PHP
• Forms: client-side
<html>
<head>
<title> A Form Example </title>
</head><body>
<form action="welcome.php" method="post">
Name: <br /> <input type="text" name="name" /><br />
E-mail:<br /> <input type="text" name="email" /><br />
Phone Number: <br /> <input type="text" name="phone" /><br />
<input type="submit" value="Send Data">
</form>
</body>
</html>
• form action: where to send the form data
• method: how to send the data (GET or POST)
• Name attributes become the keys used to access the corresponding fields in the
$_GET or $_POST arrays
The above created Form with data filled by users
Receive Data from a Form in PHP. . . Cont.
• Forms: server-side (with method POST)
<html>
<head><title>This is welcome.php</title></head>
<body>
The name that was submitted was:
<?php echo $_POST['name']; ?><br />
The E-Mail that was submitted was:
<?php echo $_POST[‘email']; ?><br />
The phone number that was submitted was:
<?php echo $_POST['phone']; ?><br />
</body>
</html>
• A simple PHP file that displays what was entered into the form
– Can do many other things server-side depending on the situation
– Note the use of $_POST
Receive Data from a Form in PHP. . . Cont.
• Forms: server-side (with method GET)
<html>
<head><title>This is welcome.php</title></head>
<body>
The name that was submitted was:
<?php echo $_GET['name']; ?><br />
The E-Mail that was submitted was:
<?php echo $_GET[‘email']; ?><br />
The phone number that was submitted was:
<?php echo $_GET['phone']; ?><br />
</body>
</html>
• A simple PHP file that displays what was entered into the form
– Can do many other things server-side depending on the situation
– Note the use of $_GET
User Data after it submitted to welcome.php using post
and get method respectively
Introduction to Regular Expressions
• Regular expressions are a sequence or pattern of characters itself.
• The main purpose of regular expressions, also called regex or regexp,
is to efficiently search for patterns in a given text.
• These search patterns are written using a special format which a
regular expression parser understands.
• They provide the foundation for pattern-matching functionality.
• Using regular expression you can search a particular string inside a
another string, you can replace one string by another string and you
can split a string into many chunks.
Regular Expressions . . . Cont.
• PHP offers functions specific to two sets of regular expression functions, each
corresponding to a certain type of regular expression.You can use any of them
based on your comfort.
– POSIX Regular Expressions
– PERL Style Regular Expressions
• In a regular expression, most characters match only themselves.
• For instance, if you search for the regular expression “for" in the string
“Information Technology" you get a match because "for" occurs in that string.
• Some characters have special meanings in regular expressions.
– E.g. a dollar sign ($) is used to match strings that end with the given pattern.
– Similarly, a caret (^) character at the beginning of a regular expression indicates that it
must match the beginning of the string.
Regular Expressions . . . Cont.
• The characters that match themselves are called literals.
• The characters that have special meanings are called metacharacters.
• The dot (.) metacharacter matches any single character except newline (\).
• So, the pattern i.t matches hot, iatiet, iut, i3t, etc. but not ioet
• The vertical pipe (|) metacharacter is used for alternatives in a regular
expression. It behaves much like a logical OR operator and you should use it if
you want to construct a pattern that matches more than one set of characters.
• E.g. the pattern Asosa|Assosa|Asso matches strings that contain “Asosa” or
“Assosa” or”Asso”.
• Parentheses give us a way to group sequences. For example, (Af|Bet)ter
matches “After" or “Better".
• Using parentheses to group together characters for alternation is called
grouping.
Regular Expressions . . . Cont.
• If you want to match a literal metacharacter in a pattern, you have to escape
it with a backslash.
• To specify a set of acceptable characters in your pattern, you can either build a
character class yourself or use a predefined one.
• A character class lets you represent a bunch of characters as a single item in a
regular expression.
• You can build your own character class by enclosing the acceptable characters
in square brackets. A character class matches any one of the characters in the
class. E.g. a character class [abc] matches a, b or c.
• To define a range of characters, just put the first and last characters in, separated
by hyphen. E.g , to match all alphanumeric characters: [a-zA-Z0-9].
• You can also create a negated character class, which matches any character
that is not in the class, begin the character class with ^: [^0-9].
Regular Expressions . . . Cont.
• The metacharacters +, *, ?, and {} affect the number of times a pattern
should be matched.
• + means "Match one or more of the preceding expression",
• * means "Match zero or more of the preceding expression", and
• ? means "Match zero or one of the preceding expression".
• Curly braces {} can be used differently.
– With a single integer, {n} means "match exactly n occurrences of the
preceding expression",
– with one integer and a comma, {n,} means "match n or more occurrences of
the preceding expression", and
– with two comma-separated integers {n,m} means "match the previous
character if it occurs at least n times, but no more than m times".
Meta Characters in PERL Style Regular Expressions
Operators that are the Basic Building Blocks of Regular Expressions
Operator Description
^ This symbol marks the beginning of a pattern, although in some cases it can be omitted
$ Same as with the circumflex symbol, the dollar sign marks the end of a search pattern
. The period matches any single character
? It will match the preceding pattern zero or one times
+ It will match the preceding pattern one or more times
* It will match the preceding pattern zero or more times
| Boolean OR
– Matches a range of elements
() Groups a different pattern elements together
[] Matches any single character between the square brackets
{min, max} It is used to match exact character counts
\d Matches any single digit (0-9)
\D Matches any single non digit character
\w Matches any alpha numeric character including underscore (a-z, A-Z, 0-9, _)
\W Matches any non alpha numeric character excluding the underscore character
\s Matches whitespace character (space, tab, newline)
\S Matches non whitespace character
Modifiers, w h ic h c a n g lo ba lly a lte r th e b e h a viour o f s e a r c h p a tte rns.
Regular Expression Will match...
for The string "for"
^for "for" at the start of a string
for$ "for" at the end of a string
^for$ "for" when it is alone on a string
[abc] a, b, or c
[a-z] Any lowercase letter
[^A-Z] Any character that is not a uppercase letter
(gif|jpg) Matches either "gif" or "jpeg"
[a-z]+ One or more lowercase letters
[0-9\.\-] Аny number, dot, or minus sign
^[a-zA-Z0-9_]{1,}$ Any word of at least one letter, number or _
([wx])([yz]) wy, wz, xy, or xz
[^A-Za-z0-9] Any symbol (not a number or a letter)
([A-Z]{3}|[0-9]{4}) Matches three letters or four numbers
Using Regex in PHP
• The real power of regular expressions relies in combining these
operators and modifiers, therefore creating rather complex search
patterns.
• Perl-Compatible Regular Expressions (PCRE) emulate the Perl syntax
for patterns, which means that each pattern must be enclosed in a
pair of delimiters.
– Usually, the slash (/) character is used. For instance, /pattern/.
• The PCRE functions can be divided in several classes: matching,
replacing, splitting and filtering.
Using Regex in PHP . . . Cont.
In PHP we have a total of nine PCRE functions which we can use
• preg_filter – performs a regular expression search and replace
• preg_grep – returns array entries that match a pattern
• preg_last_error – returns the error code of the last PCRE regex execution
• preg_match – perform a regular expression match
• preg_match_all – perform a global regular expression match
• preg_quote – quote regular expression characters
• preg_replace – perform a regular expression search and replace
• preg_replace_callback – perform a regexp search and replace using a callback
• preg_split – split string by a regular expression
The two most commonly used functions are preg_match and preg_replace.
• preg_replace and preg_filter are identical (In preg_filter if no match,
nothing is returned, but In preg_replace the original content is returned )
Using Regex in PHP . . . Cont.
• The preg_match() function performs Perl-style pattern matching on a string.
• preg_match() takes two basic and three optional parameters.
– These parameters are, in order, a regular expression string, a source string, an array variable which
stores matches, a flag argument and an offset parameter that can be used to specify the alternate place
from which to start the search:
• preg_match ( pattern, subject [, matches [, flags [, offset]]])
– The preg_match() function returns 1 if a match is found and 0 otherwise

Example: $test_string = 'hello world';


• If we simply want to search for the word hello or world then the search pattern
would look something like this:
– preg_match('/hello/', $test_string);
– preg_match('/world/', $test_string);
Using Regex in PHP . . . Cont.
• If we wish to see if the string begins with the word hello, we would simply put the
^ character in the beginning of the search pattern like this:
– preg_match('/^hello/', $test_string);
• Please note that regular expressions are case sensitive, the above pattern won’t
match the word hElLo. If we want our pattern to be case insensitive we should
apply the following modifier:
– preg_match('/^hello/i', $test_string);
• Notice the character i at the end of the pattern after the forward slash.
Example2: More complex search pattern.
• What if we want to check that the first five characters in the string are alpha numeric characters.
– preg_match('/^[A-Za-z0-9]{5}/', $test_string);
• Also, this regular expression could be optimized to the following form:
– preg_match('/^\w{5}/', $test_string);
• \w specifies any alpha numeric characters plus the underscore character (_).
Using Regex in PHP . . . Cont.
• The preg_replace() function looks for substrings that match a pattern and then
replaces them with new text.
• It takes three basic parameters and an additional one.
– These parameters are, in order, a regular expression, the text with which to replace a
found pattern, the string to modify, and the last optional argument which specifies how
many matches will be replaced.
• preg_replace( pattern, replacement, subject [, limit ])
• The function returns the changed string if a match was found or an unchanged
copy of the original string otherwise.
• In the following example we search for the course title IP and replace with the
course code.
• See the next slide
Using Regex in PHP . . . Cont.
• In the above example we use back references in the replacement
string.
– Back references make it possible for you to use part of a
matched pattern in the replacement string.
– To use this feature, you should use parentheses to wrap any
elements of your regular expression that you might want to use.
– You can refer to the text matched by sub pattern with a dollar sign
($) and the number of the sub pattern.
– For instance, if you are using sub patterns, $0 is set to the whole
match, then $1, $2, and so on are set to the individual matches
for each sub pattern
The most popular use of regular expressions is validation
• Validating
– E-mail (username@domainname (.et/com/info))
– Phone number(country code(+251 or 0), length (10))
– Name (must be letters space)
Read and Validate by
– URL (Website Address)
Your Own
• Creating strong password:
– contains letters (small and CAP)
– numbers (digit)
– Symbols (@, !, ,$, -)
– At least 10 characters long
More examples and details on this chapter:
Decision statements
Form data handling
Loops in php
Arrays in php
Loop through an array
Functions in php
Regular expressions
?

115

You might also like