You are on page 1of 113

Chapter 5

PHP
Introduction
HTML- focuses on marking up information(define the
content of web pages)
CSS- focuses on formatting and presenting
information(specify the layout of web pages)
 JavaScript to program the behavior of web pages( to add
dynamic features on the client side)
PHP is a server scripting language, and a powerful tool for
making dynamic and interactive Web pages. ( used to add
dynamic features on the server side…including database
interaction)
Client-side Technologies

CLIENT
Server
SIDE

Browser

HTML
JavaScript
CSS

Script
Database Engine

3
Server-Side

Browser Server

Apache

SERVER SIDE

Database Script PHP


MySQL Engine

4
Client side vs Server side scripting

Client-side Server-side
Scripts are stored on the client (engine Scripts are stored on the server
is in browser) (engine is on server)

Scripts can be modified by the end Scripts cannot be modified by the end
user user

Browser-dependent Browser-independent
Source code can be viewed Source code can’t be viewed
Can’t communicate with a database Can communicate with a database

No network overhead Dependent on network bandwidth

Processing is done by the browser - Processing is done by the server -


fast slower
How web server works?
 Client specifies document at a specific web address.
E.g. http://www.MAU.edu.et/
 If the requested document is HTML or text, the server
simply forwards it back to the client.
 However, the requested document may be an executable
script, or it may be HTML with an embedded script, In
this cases, the server executes the script
 If the entire document was a script, the server simply
sends the output back to the client
 If the document had an embedded script, the script
sections are replaced with the output and the modified
document is then sent to the client
Note that the client never sees the server-side script code
What is PHP?

• PHP is a scripting language, created in 1994 by Rasmus


Lerdorf from the Apache Group, that is designed for
producing dynamic Web content.
• PHP stands for PHP: Hypertext Preprocessor
• PHP is a widely-used, open source scripting language
executed on the server designed specifically for
development of dynamic web page.
• Its similarity to C’s syntax and open-source nature make
PHP relatively easy to learn.
What is a PHP File?

• PHP files can contain text, HTML, JavaScript


code, and PHP code
• PHP code are executed on the server, and the
result is returned to the browser as plain HTML
• PHP files have a default file extension of “.php"
What Can PHP Do?
• PHP can generate dynamic page content
• PHP can create, open, read, write, and close files
on the server
• PHP can collect form data
• PHP can send and receive cookies
• PHP can add, delete, modify data in your database
• PHP can restrict users to access some pages on
your website
• PHP can encrypt data
Why use PHP?
• Powerful and flexible,
• PHP is easy to learn and runs efficiently on the server side
• PHP runs on different platforms (Windows, Linux, Unix, Mac
OS X, etc.)
• PHP is compatible with almost all servers used today (Apache,
IIS, etc.)
• PHP has support for a wide range of databases(MySQL,
Informix, Oracle, Sybase, Solid, PostgreSQL, Generic ODBC,
etc)
• PHP is an open source software and free to download and use.
• Cheap
• Easy to set up
Basic PHP Syntax
<html>
<body>
<?php
<?php
echo "Hello World";

?>
</body></html> ?>
• A PHP scripting block always starts with <?php and ends with ?
>.
• A PHP scripting block can be placed (almost) anywhere in an
HTML document.
• Anything written within these tags will be treated by the Web
server as PHP.
• The PHP interpreter will process the code.
Cont..
• All PHP code is contained in one of several script tags:
1. <?php
// Some code here
?>

2. <?
// Some code
?>

3. <script language=“PHP">
// Some code here
</script>
• When a PHP file is requested, the PHP interpreter parses the entire
file
• Any content within PHP delimiter tags is interpreted, and
the output substituted
• Any other content (i.e. not within PHP delimiter tags) is
simply passed on unchanged
• This allows us to easily mix PHP and other content (ex:
HTML)
• All PHP statements end with a semi-colon (;)
• The semicolon is a separator which is used to distinguish one set of
instructions from another.
• With PHP, there are two basic statements to output text in the
browser: echo and print.
Example 1

HTML 5 Document
<!DOCTYPE html>
<html> Root HTML Tag
<head>
<title>Simple PHP Example</title>
Document Head
</head>
<body>
<?php echo "<p><h1>Output</h1>";
D print"<h2>Output</h2>";
O Print"<h3>Output</h3></p>";
C PHP Code
?>
<script language="PHP">
B echo "\n<b>More PHP Output</b>\n";
O echo "New line in source but not rendered";
D
echo "<br/>";
Y
echo "New line rendered but not in source";
</script>
</body>
</html>
Example2
<!DOCTYPE html>
<html>
<head>
<title> Hello world </title>
</head>
<body>
<?php
print 'Hello, World!';
echo "<br/>";
echo "Hello, World!";
?>
</body></html>
The use of include() fuction

• Used to include external PHP file into another PHP code


Example
setdate.php:
<?php $today=getdate(time());?>
footer.php:
<SMALL>Today is <?php print$today['weekday'];?></SMALL>
Index.php:

<?php
include ("setdate.php");
?>
<H2>Today's Headline:</H2>
<P ALIGN="center">
<?php
print "World Peace Declared";
?>
</P><HR>
<?php include ("footer.php");
?>
Script execution
• There are two methods for executing PHP scripts:
 via the Web server, and
 the command-line interface (CLI).
• The first method will be used almost exclusively in this
course, so you may ignore the CLI for now.
1. Upload your .php file to your Web account (i.e., within the
www-home directory on wapserver or httdocs directory on
xampserver).
2. Make sure the permissions are set correctly;
3. Navigate to the file with a Web browser.

17
Cont...
• The PHP processor has two modes: copy (HTML) and
interpret (PHP).
• PHP processor takes a PHP document as input and
produces an HTML document file
• When it finds HTML code in the input file, simply
copies it to the output file
• When it finds PHP script, it interprets it and send any
output of the script to the output file
• This new output file is sent to the requesting browser.
• The client never sees the PHP script.

18
Basic PHP Facts
• Like JS, PHP is usually purely interpreted
• Syntax and semantics are closely related to JS
• Like JS, PHP uses dynamic typing
• PHP variables are case sensitive, but reserved
words and function names are not.
E.g
• while, WHILE, While, and wHiLe are same

19
20
Comments in PHP

• In PHP, three different kinds (Java and Perl)


(a) // ... ; for single line
(b) # ... ; for single line
(c) /* ... */ ; for multiple-line
<html>
<body>
<?php
//This is a comment
# this is also a comment
/*
This is a comment
block
*/
?></body>
</html>
PHP Variables
• Variables are containers used to temporarily store values.
• These values can be numbers, text, or much more complex
data.
• All variables in PHP start with a $ sign symbol.
<?php
$txt="Hello World!";
$x=16;
?>
• In PHP, a variable does not need to be declared before adding a
value to it.
Rules for PHP variable
• A variable starts with the $ sign, followed by the name of the
variable
• A variable name must begin with a letter or the underscore
character
• A variable name can only contain alpha-numeric characters
and underscores (A-z, 0-9, and _ )
• A variable name should not contain spaces
• Variable names are case sensitive ($y and $Y are two different
variables)
Example
<!DOCTYPE html>
<html>
<body>
<?php
$txt = “Php variable example!";
$x = 30;
$y = 20.5;
echo $txt;
echo "<br>";
echo $x;
echo "<br>";
echo $y;
?>
</body>
</html>
Environment/predefined Variables
• Beyond the variables you declare in your code, PHP has a
collection of environment variables, which are system
defined variables that are accessible from anywhere inside
the PHP code ("superglobals“ variables),
• These variables allow the script access to server
information, form parameters, environment information,
etc
• All of these environment variables are stored by PHP as
arrays.
• Some of them can be address directly by using the variable
name in the index position. Other can only be accessed
through their arrays.

25
Some of the environment variables include:
• $_SERVER
 Contains information about the server and the HTTP connection.
• $_COOKIE
 Contains any cookie data sent back to the server from the client. Indexed by
cookie name.
• $_GET
 Contains any information sent to the server as a search string as
part of the URL.
• $_POST
 Contains any information sent to the server as a POST style posting
from a client form.
• $_FILE
 Contains information about any uploaded files.
• $_ENV
 Contains information about environmental variables on the server.
26
PHP Variable Scopes
• PHP has four different variable scopes:
 local
 global
 static
Local scope

• A variable declared within a PHP function is local and can


only be accessed within that function:
<?php
$x=5; // global scope
function myTest()
{
$x=6; // local scope
echo $x; // local scope
}
myTest();
?>
• Local variables are deleted as soon as the function is
completed
Global scope

• A variable declared outside a function has a GLOBAL SCOPE


and can only be accessed outside a function:
• The global keyword is used to access a global variable from
within a function(use the global keyword before the variables
(inside the function))
<?php
$x=5; // global scope
$y=10; // global scope
function myTest(){
global $x,$y;
$y=$x+$y; }
myTest();
echo $y; // outputs 15
?>
• PHP also stores all global variables in an array called
$GLOBALS[index].
• The index holds the name of the variable.
• This array is also accessible from within functions and can be used
to update global variables directly.
<?php
$x=5;
$y=10;
function myTest()
{
$GLOBALS['y']=$GLOBALS['x']+$GLOBALS['y'];
}
myTest();
echo $y; // outputs 15
?>
Static scope

• When a function is completed/executed, all of its variables are normally


deleted. However, sometimes you want a local variable to not be deleted
for future use.
• To do this, use the static keyword when you first declare the variable:
<?php
function myTest()
{
static $x=0;
echo $x;
$x++;
}
myTest(); // 0
echo "<br/>";
myTest(); // 1
echo "<br/>";
myTest(); // 2
?>
PHP Data Types
• Variables can store data of different types, and different data
types can do different things.
• PHP supports the following data types:
• String
• Integer
• Float (floating point numbers - also called double)
• Boolean
• Array
• Object
• NULL
• Resource

32
Fundamental variable types
• Numeric
 integer. Integers (±2 raised 31); values outside this range
are converted to floating-point.
 float. Floating-point numbers.
• Boolean: true or false; PHP internally resolves these to 1 (one)
and 0 (zero) respectively.
• string: String of characters.
• array: An array stores multiple values in one single variable.
(an array of values, possibly other arrays )
• object :an object is a data type which stores data and
information on how to process that data. In PHP, an object
must be explicitly declared.

33
Cont…
• Resource:
• A handle to something that is not PHP data (e.g., image data,
database query result).
• Or in other words, Resource is to represent a PHP extension
resource (e.g. Database query, open file, database connection,
etc). You will never directly touch this type, it will be passed
to the relevant functions that know how to interact with the
specified resource.
• Null :
• data type with only one possible value: null. Marks variables
as being empty. Works with the isset() operator; will return
‘false’ for null. Example: $var=NULL;

34
Cont....
• PHP has a useful function named var_dump() that prints the
current type and value for one or more variables.
• Arrays and objects are printed recursively with their values
indented to show structure.
<?php
$a = 35; Output of the code
int(35)
$b = "Programming is fun!";
string(19) "Programming is
$c = array(1, 1, 2, 3.5); fun!"
array(4) {
var_dump($a,$b,$c); [0]=> int(1)
?> [1]=>int(1)
[2]=>int(2)
[3]=>float(3.5)) }
}}}]]]]]]]]]][[[[[

35
PHP Strings
• A string is a sequence of characters, like "Hello world!".
• A string can be any text inside quotes. You can use single or
double quotes.
'I am a string in single quotes’ 
"I am a string in double quotes" 
• The PHP parser determines strings by finding matching quote
pairs. So, all strings must start and finish with the same type of
quote - single or double. 
• Only one type of quote mark is important when defining any
string, single (') or double (").
$string_1 = "This is a string in double quotes";
$string_0 = ‘’ // a string with zero characters

36
String Concatenation Operator
• To concatenate two string variables together, use the dot (.)
operator:
E.g
<?php
$txt1="Hello World!";
$txt2="What a nice day!";
echo $txt1 ." " .$txt2;
?>
Output
Hello World! What a nice day!
The strlen()function

• The strlen() function is used to find the length of a string.


E.G
<?php
echo strlen("Hello world!");
?>
Output
12
• The length of a string is often used in loops or other functions,
when it is important to know when the string ends.
The strpos()function
• The strpos() function is used to search for a string or character
within a string. (first position in the string is 0, and not 1.)
• If a match is found in the string, this function will return the
position of the first match. If no match is found, it will return
FALSE.
E.g
<?php
echo strpos("Hello world!","world"); // output=6
?>
The str_word_count() function
• The PHP str_word_count() function counts the number of
words in a string:
E.g
<?php
echo str_word_count("Hello world!"); //output =2
?>
Reverse a String
• The PHP strrev() function reverses a string:
E.g <?php
echo strrev("Hello world!"); //output=!dlrow olleH
?> 
The str_replace() function
• The PHP str_replace() function replaces some
characters with some other characters in a string.
<?php
echo str_replace("world", “PHP", "Hello world!");
?>   Output: Hello PHP!
• The example below replaces the text "world" with
“PHP":
PHP Constants
• A constant is an identifier (name) for a simple value. The value cannot be
changed during the script.
• A valid constant name starts with a letter or underscore (no $ sign before
the constant name).
Note: Unlike variables, constants are automatically global across the entire
script.
• Syntax
define(name, value, case-insensitive)
// name: Specifies the name of the constant // value: Specifies the value of
the constant //case-insensitive: Specifies whether the constant name should
be case-insensitive. Default is false
• E. g
<?php
// case-sensitive constant name
define("GREETING", "Welcome to Mekdela Amba University!");
echo GREETING;
?>  
Example PHP String functions

<?php
$txt1="Hello World!";
$txt2="What a nice day!";
echo $txt1 ." " .$txt2; // String concatenation function
echo "<br/>";
echo strlen($txt1); // string length function
echo "<br/>";
echo strpos("Hello world!","world"); // String position function
echo "<br/>";
echo str_word_count($txt1); // string words count function
echo "<br/>";
echo strrev($txt1); // string reverse function
echo "<br/>";
echo str_replace("world", "PHP", "Hello world!");// string replace function
?>
PHP Operators

• Operators are used to perform operations on variables


and values.
• PHP divides the operators in the following groups:
 Arithmetic operators
 Assignment operators
 Comparison operators
 Increment/Decrement operators
 Logical operators
 String operators
 Array operators
PHP Arithmetic Operators
Operator Name Example Result

+ Addition $x + $y Sum of $x and $y

- Subtraction $x - $y Difference of $x and $y

* Multiplication $x * $y Product of $x and $y

/ Division $x / $y Quotient of $x and $y

% Modulus $x % $y Remainder of $x divided by $y

** Exponentiation $x ** $y Result of raising $x to the $y'th power


(Introduced in PHP 5.6)
PHP Assignment Operators
Assignment Same as... Description

x=y x=y The left operand gets set to the value of


the expression on the right

x += y x=x+y Addition

x -= y x=x-y Subtraction

x *= y x=x*y Multiplication

x /= y x=x/y Division

x %= y x=x%y Modulus
PHP Comparison Operators
Operator Name Example Result
== Equal $x == $y Returns true if $x is equal to $y

=== Identical $x === $y Returns true if $x is equal to $y, and they are of the same
type

!= Not equal $x != $y Returns true if $x is not equal to $y

<> Not equal $x <> $y Returns true if $x is not equal to $y

!== Not identical $x !== $y Returns true if $x is not equal to $y, or they are not of the
same type

> Greater than $x > $y Returns true if $x is greater than $y

< Less than $x < $y Returns true if $x is less than $y

>= Greater than or $x >= $y Returns true if $x is greater than or equal to $y


equal to

<= Less than or equal to $x <= $y Returns true if $x is less than or equal to $y
PHP Increment / Decrement Operators

Operator Name Description

++$x Pre-increment Increments $x by one,


then returns $x
$x++ Post-increment Returns $x, then
increments $x by one
--$x Pre-decrement Decrements $x by one,
then returns $x

$x-- Post-decrement Returns $x, then


decrements $x by one
PHP Logical Operators

Operato Name Example Result


r
and And $x and $y True if both $x and $y are true

or Or $x or $y True if either $x or $y is true

xor Xor $x xor $y True if either $x or $y is true,


but not both

&& And $x && $y True if both $x and $y are true

|| Or $x || $y True if either $x or $y is true

! Not !$x True if $x is not true


PHP String Operators

Operator Name Example Result

. Concatenati $txt1 . $txt2 Concatenation of


on $txt1 and $txt2

.= Concatenati $txt1 .= $txt2 Appends $txt2 to


on $txt1
assignment
PHP Array Operators
Operator Name Example Result
+ Union $x + $y Union of $x and $y. The union of two
sets A and B is the set of elements which
are in A, in B, or in both A and B.

== Equality $x == $y Returns true if $x and $y have


the same key/value pairs

=== Identity $x === $y Returns true if $x and $y have


the same key/value pairs in the
same order and of the same
types

!= Inequality $x != $y Returns true if $x is not equal to


$y

<> Inequality $x <> $y Returns true if $x is not equal to


$y

!== Non-identity $x !== $y Returns true if $x is not


identical to $y
PHP Conditional Statements

• Conditional statements are used to perform different


actions based on different conditions
• In PHP we have the following conditional statements:
• if statement - executes some code only if a specified
condition is true
• if...else statement - executes some code if a condition
is true and another code if the condition is false
• if...elseif....else statement - specifies a new condition
to test, if the first condition is false
• switch statement - selects one of many blocks of code
to be executed
PHP - The if Statement

• The if statement is used to execute some code only if a specified


condition is true or ignored if the condition fails.
• Syntax
if (condition) {
    code to be executed if condition is true;
}
• Example
<?php
$t = date("H"); //24 hours format of an hour
if ($t < "15") {
echo "Have a good day!";
}
?>
PHP - The if...else Statement

The “if else” statement allows us to specify two alternative statements:


• One which will be executed if a condition is satisfied and
• Another which will be executed if the condition is not satisfied.
• Syntax
if (condition) {
    code to be executed if condition is true;
} else {
    code to be executed if condition is false;
}
• Example
<?php
$t = date("H");
if ($t < "20") {
echo "Have a good day!";
}
else {
echo "Have a good night!";
} ?>
PHP - The if...elseif....else Statement

• The “if else if” statement allows us to specify more than two alternative
statements each will be executed based on testing one or more conditions.
• Syntax
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;
}
Example
<?php
$d=date("D"); // A textual representation of a day (three letters)
if($d=="Fri")
echo "Have a nice weekend!";
Else if($d=="Sun")
echo "Have a nice Sunday!";
else
echo "Have a nice day!";
?>
PHP switch statement
•The Switch statement in PHP is used to perform one of several different
actions based on one of several different conditions.
•If you want to select one of many blocks of code to be executed, use the
Switch statement.

Syntax: switch (expression)


{
case label1:
code to be executed if expression = label1;
break;
case label2:
code to be executed if expression = label2;
break;
default:
code to be executed
if expression is different
from both label1 and label2;
}
Example PHP switch statement
<html><body>
<?php
$x=2;
switch ($x)
{
case 1:
echo "Number 1";
break;
case 2:
echo "Number 2";
break;
case 3:
echo "Number 3";
break;
default:
echo "No number between 1 and 3";
}
?>
</body>
</html>
PHP looping statements
While Loops
 The while statement (also called while loop) provides a way of repeating
a statement or a block as long as a condition is true.
while(expression)
<?php statements;
$i=1;  

while($i<=5)
{
echo "The number is " . $i . "<br />";
$i++;
}
?>
PHP Looping - For Loops

• The “for” statement (also called loop) is used to repeatedly execute a


block of instructions until a specific condition fails.

E.g
<!DOCTYPE html> for(initialization; condition; increment)
<html> statements;
<body>  

<?php 
for ($x = 0; $x <= 10; $x++) {
   echo "The number is: $x <br>";
}
?>   
</body>
</html>
Foreach loop

• The foreach loop works only on arrays, and is used to loop through each
key/value pair in an array.
• Syntax foreach($array as $key=>$value)
foreach ($array as $value) { {
    code to be executed; Code to be executed;
} }

• For every loop 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.
E.g.
<?php
$x=array("one","two","three");
foreach($x as $value)
{
echo $value . "<br />";
}
?>
PHP Functions

• A function is a self-contained block of code that can be called


by your script.
• When called (or invoked), the function’s code is executed and
performs a particular task.
• In PHP, functions come in two flavors – those built in to the
language(e.g strtoupper()), and those that you define yourself.
• Naming conventions for functions are the same as for normal
variables in PHP.
• Note: variables names are case sensitive in PHP, function
names are not!)
Example
<html>
<head><title>Writing PHP Function</title></head><body>
<?php
function writeMessage(){ // Defining a PHP Function
echo "You are really a nice person, Have a nice time!<br/>";
}
writeMessage(); /* Calling a PHP Function */
function addFunction($num1, $num2)
//Writing PHP Function with Parameters
{
$sum = $num1 + $num2;
return $sum;
}
$result= addFunction(10, 20); // Calling a PHP Function with parameter
echo "Sum of the two numbers is : $result<br/>";
?></body></html>
PHP Functions - Return values

<?php
function add($x,$y)
{
$total=$x+$y;
Return $total;
}
echo "1 + 16 = " . add(1,16);
?>
PHP Arrays

• An array is a data structure that stores one or more similar type of


values in a single value.
• In PHP, there are three types of arrays:
 Numeric array - An array with a numeric index. Values are
stored and accessed in linear fashion
 Associative array - An array with strings as index. This stores
element values in association with key values rather than in a
strict linear index order.
 Multidimensional arrays- Arrays containing one or more
arrays
Numeric Array
• A numeric array stores each array element with a numeric
index.
E.g
<html><body>
<?php
$numbers = array(1, 2, 3, 4, 5);
foreach( $numbers as $value )
{
echo "Value is $value <br/>";
}
?>
</body>
</html>
Associative array

• Associative array will have their index as string so that you


can establish a strong association between key and values.
• 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.
<?php
$salary= array("abel"=>3200, "Sam"=>3000, "bet"=>3400);
echo "Salary of Abel is ". $salary['abel'] . "<br />";
echo "Salary of bet is ". $salary['bet'] . "<br />";
echo "Salary of sam is ". $salary['Sam'] . "<br />";
?>
Multidimensional array

• In a multidimensional 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.
$families = array(
“animal"=>array (“birds",“fish",“mammals"),
“plant"=>array (“Trees"),
"Brown"=>array("Cleveland","Loretta","Junior")
);
echo "Is " . $families[‘animal'][2] . “ are a type of Animals?";
<html><body>
<?php /*Accessing multi-dimensional
array values */
$marks = array(
echo "Marks for abel in physics : " ;
"abel" => array(
echo $marks['abel']['physics'] .
"physics" => 35,
"<br />";
"maths" => 30, echo "Marks for sam in maths : ";
"chemistry" => 39 ), echo $marks['sam']['maths'] .
"sam" => array( "<br />";
"physics" => 30, echo "Marks for sam in chemistry :
"maths" => 32, ";
"chemistry" => 29 ), echo $marks['sam']['chemistry'] .
"<br />";
"beti" => array ?> </body></html>
(
"physics" => 31,
"maths" => 22,
68
"chemistry" => 39) );
Cont…..

In the example below, three literal arrays are declared as follows: 


1. A numerically indexed array with indices running from 0 to 4.
2. An associative array with string indices.
3. A numerically indexed array, with indices running from 5 to 7.
If you set the first numeric key value, the added values will be keyed incrementally
thereafter:
– $days = array (1 => 'Sun', 'Mon', 'Tue');
– echo $days[3]; // Tue
Example
<?php
$array1 = array(2, 3, 5, 7, 11);
$array2 = array("one" => 1,
"two" => 2,
"three" => 3);
$array3 = array(5 => "five", "six", "seven");
Print ($array1[3].",".$array2["one"].",".$array3[6]);
?>
Get The Length of an Array

<?php
$cars=array("Volvo","BMW","Toyota");
echo count($cars);
?>
Loop Through an Indexed Array
<?php
$cars=array("Volvo","BMW","Toyota");
$arrlength=count($cars);
for($x=0;$x<$arrlength;$x++)
{
echo $cars[$x];
echo "<br>";
}
?>
Loop Through an Associative Array

<?php
$age=array("Peter"=>"35","Ben"=>"37","Joe"=>"4
3");
foreach($age as $x=>$x_value)
{
echo "Key=" . $x. ", Value=" . $x_value;
echo "<br>";
}
?>
PHP - Sort Functions For Arrays

• 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 ke
Example: $names = array (‘ruta', ‘abel’,’Mohammed');
– sort($names);
• y
Example
<?php
$numbers=array(4,6,2,22,11);
sort($numbers);
$arrlength=count($numbers);
for($x=0;$x<$arrlength;$x++)
{
echo $numbers[$x];
echo "<br>";
}
?>
Handling User Input:
Using HTML forms
with PHP
User Input Manipulation

 One of the advantages of PHP is the ability to easily


manipulate information submitted by the user through an
HTML form.
 Sending data to a script via an HTML form with name and value
pairs using either post or get method.
What is a HTML FORM?
• A form basically contains Text boxes and buttons
• Provides two-way communication between web servers and
browsers.
FORM Tags and Attributes

• This tag is used to enclose HTML form. All objects


must be inside of a form tag
<form action=“registration.php" name=“reg" method=“post">
</form>
Attributes
 Action - the URL of the script that the data will be sent to -this
is the page that will display once the submit button is clicked
 Name - the name of the form
 Method - the way the data is sent to the script.Two main
attributes: get, post
<INPUT> Tag

• This tag defines a basic form element.


• Several attributes are possible:
• TYPE, NAME, SIZE, MAXLENGTH, VALUE, SRC,
ALIGN
<TEXTAREA> … </TEXTAREA> Tag
• Can be used to accommodate multiple text lines in a
box.
• Attributes are:
 NAME: name of the field.
 ROWS: number of lines of text that can fit into the box.
 COLS: width of the text area on the screen.
<SELECT> …. </SELECT> Tag

• Used to define a selectable list of elements along with


the <OPTION> tag.
• The list appears as a scrollable menu or a pop-up
menu (depends on browser).
• Attributes are:
• NAME: name of the field.
• SIZE: specifies the number of option elements that
will be displayed at a time on the menu. (If actual
number exceeds SIZE, a scrollbar will appear).
• MULTIPLE: specifies that multiple selections from
the list can be made.
78
PHP Forms and User Input

• The PHP $_GET and $_POST variables are used to retrieve


information from different forms.
• E.g Registration.html
<html><body>
<form action="display.php" method=“post">
<p>First Name: <input type="text" name="fname" /></p>
<p>Last Name: <input type="text" name="lname" /></p>
<p>User Name: <input type="text" name="uname" /></p>
<p>Password: <input type="password" name="pass" /></p>
<input type="submit" value="Register" />
</form></body></html>
Output of the Form
• When the user fills out the form and clicks the submit button, the
form data is sent for processing to a PHP file named
“display.php".
• The form data is sent with the HTTP POST method.
display.php
<html>
<body>
<h1>Welcome <?php echo $_POST["fname"]; ?>
<?php echo $_POST["lname"]; ?><br></h1>
Your user Name: <?php echo $_POST["uname"]; ?><br>
Your Password: <?php echo $_POST["pass"]; ?>
</body></html>
Calculator.html

<html>
<h1><center>Calculator</center></h1>
<form action="calculator.php" method="post">
<table align="center">
<th> Choose arithmetic operator<th>Enter the values </th>
<tr>
<td>+<input type="radio" name="arithmetic" value="add" checked>
<td><input type="text" name="v1">
<tr>
<td>- <input type="radio" name="arithmetic" value="minus">
<td><input type="text" name="v2">
<tr>
<td>/ <input type="radio" name="arithmetic" value="divide">
<tr>
<td>*<input type="radio" name="arithmetic" value="multiply">
<tr>
<td><input type="submit" value="Execute" >
</table>
<h3> the Result</h3>
</form>
</html>
82
Calculator.php
<?php
$v1=$_POST['v1'];
$v2=$_POST['v2'];
$a=$_POST['arithmetic'];
require('calculator.html');
switch($a){
case 'add':
echo $v1+$v2; break;
case 'minus':
echo $v1-$v2; break;
case 'divide':
{if ($v2==0)echo"Cannot divide by zero";
else echo $v1/$v2; break;
}
case 'multiply':
echo $v1*$v2; break;
}
?> 83
Calculator.html

84
PHP GET and POST Methods

• The PHP $_GET and $_POST variables are used to retrieve


information from forms, like user input
• Form elements in an HTML/PHP page will automatically be
available to your PHP scripts.
• 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 non-alphanumeric characters are replaced with a
hexadecimal values.
• After the information is encoded it is sent to the server .
85
$_POST
• The $_POST variable is an array of variable names and values
sent by the HTTP POST method
• The $_POST variable is used to collect values from a form
with method="post“
• Information sent from a form with the POST method is
invisible to others and has no limits on the amount of
information to send

86
Example - $_POST

<!--“welcome.html” file --> <!--“welcome.php” file -->

<html> <body> <html> <head>


<form action=“welcome.php" <title>Grab form values</title>
method="post"> </head> <body>
Name: <input type="text" Welcome <?php echo
name="name"> $_POST["name"];?>.<br/>
Age: <input type="text" You are <?php echo
name="age"> $_POST["age"];?> years old
<input type="submit">
</form> </body> </html>
</body></html>

87
$_GET
• The $_GET variable is an array of variable names and values
sent by the HTTP GET method
• The $_GET variable is used to collect values from a form
with method="get“
• This method should not be used when sending passwords or
other sensitive information!
• Information sent from a form with the GET method is visible
to everyone (it will be displayed in the browser's address bar)
and it has limits on the amount of information to send (max.
2000 characters)

88
Example - $_GET

<!--“welcome.html” file --> <!--“welcome.php” file -->

<html> <html>
<head>
<body> <title>Grab form values</title>
<form action=“welcome.php" </head>
method="get">
<body>
Name: <input type="text" Welcome <?php echo
name="name"> $_GET["name"];?>.<br/>
Age: <input type="text" name="age">
You are <?php echo $_GET["age"];?>
<input type="submit"> years old
</form>
</body>
</body>
</html> </html>

89
The $_REQUEST Variable Why use $_POST?

• The PHP $_REQUEST variable • Variables sent with HTTP POST


can be used to get the result are not shown in the URL.
from form data sent with both • The POST requests are not
the GET and POST methods as idempotent. This means that
well as $_COOKIE. they cannot be cached, and
Example the server is recontacted
Welcome <?php echo every time the page is
$_REQUEST["name"]; ?>.<br /> displayed. Because of this, it is
You are <?php echo not possible to bookmark the
$_REQUEST["age"]; ?> years old! page.
• Variables have no length limit

90
Form Validation with PHP
What is form validation?
• validation: ensuring that form's values are correct
• some types of validation:
 preventing blank values (email address)
 ensuring the type of values
 integer, real number, currency, phone number, Social Security
number, postal address, email address, date, credit card
number, ...
 ensuring the format and range of values (ZIP code must
be a 5-digit integer)
 ensuring that values fit together (user types email twice,
and the two must match)
91
A real Form that uses validation

92
Client vs. server-side validation
• Validation can be performed:
 client-side (before the form is submitted)
 can lead to a better user experience, but not secure (why
not?)
 server-side (in PHP code, after the form is
submitted)
 needed for truly secure validation, but slower
 both
 best mix of convenience and security, but requires most
effort to program

93
Form validation
<html><head><style>.error {color: #FF0000;} </style></head>
<body>
<?php
include ('validate.php');
?>
<h2>PHP Form Validation Example</h2>
<p>*required field.</span></p>
<form method="post” action='<?php $_SERVER["PHP_SELF"]?>' >
Name: <input type="text" name="name" value="">
<span class="error">* <?php echo $nameErr;?></span>
<br><br>
E-mail: <input type="text" name="email" value="">
<span class="error">* <?php echo $emailErr;?></span>
<br><br>
<input type="submit" name="submit" value="Submit">
</form>
</body>
<html>

• Let's validate this form's data on the server...


• The $_SERVER["PHP_SELF"] is a super global variable that returns the filename of the
currently executing script. It sends the submitted form data to the page itself
94
Basic server-side validation code
<?php
$nameErr = $emailErr = $genderErr = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["name"])) {
$nameErr = "Name is required";
}
if (empty($_POST["email"])) {
$emailErr = "Email is required";
}
}
?>

• basic idea: examine parameter values, and if they are bad, show
an error message and abort

95
Main PHP Validation Functions

• The first step in validation is making sure variables


aren’t empty
• Unfortunately, a field filled with spaces is not
technically empty
• That’s why you need the trim() function
• How it works:
 Pass it a variable and It removes white spaces before
or after a field entry (in the variable)
 Do it like so
$name = trim($name);
Main PHP Validation Functions
• empty() – checks to see if a variable is empty or not
 Pass it a variable
 E.g if( empty($_POST["name"])){
}
 If the variable has no value (it’s empty), it returns True
▪ “Yes, it is empty”
 If the variable does have a value (not empty), it returns False
▪ “No, it’s not empty”
 Typically, you use the empty() function to check to see if it is
not empty
▪ Place the exclamation mark (NOT) in front of the function
E.g if( !empty($_POST["name"])){
}
 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).
• Example:
//Validate the gender:
if (isset($_REQUEST['gender'])) {
$gender = $_REQUEST['gender'];
if ($gender == 'M') {
echo '<p><b>Good day, Sir!</b></p>';
} elseif ($gender == 'F') {
echo '<p><b>Good day, Madam!</b></p>';
}
else { // Unacceptable value.
$gender = NULL;
echo '<p class="error">Gender should be either "M" or
"F"!</p>';}
} else { // $_REQUEST['gender'] is not set.
$gender = NULL;
echo '<p class="error">You forgot to select your gender!</p>';}

98
Basic Regular Expression

/abc/
• Regexes is a sequence of characters that forms a particular
pattern.
• Provide the foundation for pattern-matching functionality
• In PHP, regexes are strings that begin and end with /
• the simplest regexes simply match a particular substring
• the above regular expression matches any string containing
"abc":
– YES: "abc", "abcdef", "defabc", ".=.abc.=.", ...
– NO: "fedcba", "ab c", "PHP", ...

99
Regular expressions
• /[a-z]/at #cat, rat, bat…
• /[a-zA-Z]/
• ~[^a-z]~ #not a-z
• (very){1, 3} #counting “very” up to 3
• /^www/ #www at the beginning
• /com$/ #com at the end
Wildcards
• A dot . matches any character except a \n line break
 "/.oo.y/" matches "Doocy", "goofy", "LooNy", ...
• A trailing i at the end of a regex (after the closing /) signifies
a case-insensitive match
 "/xen/i" matches “Xenia", “xenophobic", “Xena the warrior
princess", “XEN technologies” ...
Special characters: |, (), ^, \
• | means OR
 "/abc|def|g/" matches "abc", "def", or "g"
• () are for grouping
 "/(Homer|Marge) Simpson/" matches "Homer Simpson" or
"Marge Simpson"
• ^ matches the beginning of a line;
• $ the end
 "/^<!--$/" matches a line that consists entirely of "<!--“
• \ starts an escape sequence
 many characters must be escaped to match them literally: / \ $
.[]()^*+?
 "/<br \/>/" matches lines containing <br /> tags
101
Quantifiers: *, +, ?
• * means 0 or more occurrences
 "/abc*/" matches "ab", "abc", "abcc", "abccc", ...
 "/a(bc)*/" matches "a", "abc", "abcbc", "abcbcbc", ...
 "/a.*a/" matches "aa", "aba", "a8qa", "a!?_a", ...
• + means 1 or more occurrences
 "/a(bc)+/" matches "abc", "abcbc", "abcbcbc", ...
 "/Goo+gle/" matches "Google", "Gooogle", "Goooogle", ...
• ? means 0 or 1 occurrences
 "/a(bc)?/" matches "a" or "abc"

102
More quantifiers: {min,max}
• {min,max} means between min and max
occurrences (inclusive)
– "/a(bc){2,4}/" matches "abcbc", "abcbcbc", or
"abcbcbcbc"
• min or max may be omitted to specify any
number
 {2,} means 2 or more
 {,6} means up to 6
 {3} means exactly 3

103
Character sets: []
• [] group characters into a character set; will match
any single character from the set
 "/[bcd]art/" matches strings containing "bart", "cart",
and "dart"
 equivalent to "/(b|c|d)art/" but shorter
• inside [], many of the modifier keys act as normal
characters
 "/what[!*?]*/" matches "what", "what!", "what?**!",
"what??!",
• What regular expression matches (strings of A, C, G,
or T)?
104
Character ranges: [start-end]
• inside a character set, specify a range of characters with -
 "/[a-z]/" matches any lowercase letter
 "/[a-zA-Z0-9]/" matches any lower- or uppercase
letter or digit
• an initial ^ inside a character set negates it
 "/[^abcd]/" matches any character other than a, b, c,
or d
 "/[+\-]?[0-9]+/" matches an optional + or -, followed
by at least one digit
• What regular expression matches letter grades such as A,
B+, or D- ?
105
Escape sequences

• special escape sequence character sets:


 \d matches any digit (same as [0-9]); \D any non-
digit ([^0-9])
 \w matches any “word character” (same as [a-zA-
Z_0-9]); \W any non-word
• char
 \s matches any whitespace character ( , \t, \n,
etc.); \S any non-whitespace
• What regular expression matches dollar
amounts of at least $100.00 ?
106
Regular expressions in PHP
• regex syntax: strings that begin and end
with /, such as "/[AEIOU]+/"
Function description
preg_match(regex, string) returns TRUE if string matches
regex
returns a new string with all
preg_replace(regex, substrings that match regex
replacement, string)
replaced by replacement
returns an array of strings from
given string broken apart using
preg_split(regex, string) the given regex as the
delimiter (similar to explode
but more powerful)
CS382 107
Regular expressions example
# replace vowels with stars
$str = "the quick brown fox";
$str = preg_replace("/[aeiou]/", "*", $str);
# "th* q**ck br*wn f*x"
# break apart into words
$words = preg_split("/[ ]+/", $str);
# ("th*", "q**ck", "br*wn", "f*x")

108
PHP form validation w/ regexes
$state = $_REQUEST["state"];
if (!preg_match("/[A-Z]{2}/", $state)) {
?>
<h2>Error, invalid state submitted.</h2>
<?php
}
PHP

• using preg_match and well-chosen regexes allows you to


quickly validate query parameters against complex
patterns

109
• Use the preg_match() function stands for
perform a regular expressions match
Example
<?php
$age=$_POST["age"];
if(!preg_match("/^[0-9]$/",$age))
echo "You entered invalid input, please try again";
else
echo "Your age is ". $age;
?>

110
<?php
$age=$_POST["age"];
if(!preg_match("/^[0-9]{1,3}$/",$age))
echo "You enterd invaid input, please try
again";
else
echo "Your age is ". $age;
?>

111
Cont..
• Using the preg_match function()
• preg_match() is a case sensitiv function, which means
it treats “a” and “A” differently.
• Example
function check_field1($field_name_1)
{
  if(!preg_match("/^ [a-zA-Z0-9]+$/”, $field_name_1))
  return TRUE;
  else The slashes “/” and “/” are delimiters, “^”
  return FALSE; marks the start of string or line and the
Dollar sign “$” the end of the string, or
} line. The plus-symbol “+” means required.
112
Cont....
/^[a-zA-Z0-9 _.,:"']+$/
• We translate this regexp as:
• From the beginning to the end of the address
string check if our character is one of the
following a-z, A-Z, 0-9, space, underscore,
dash, dot, comma, semicolons, double and
sigle quotes. You can add any character that
you think may be part of an address(+).

113

You might also like