0% found this document useful (0 votes)
12 views

Chapter 2 PHP

Uploaded by

ephitsegaye7878
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views

Chapter 2 PHP

Uploaded by

ephitsegaye7878
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 105

Chapter 2

Server Side Programs


Introduction to PHP
 PHP is the web development language written by and for
Web developers.
 PHP stands for Hypertext Preprocessor.
 PHP is currently in its fifth major version called PHP5.

 PHP is a server-side scripting language, which can be


embedded in HTML or used as a standalone binary.
 Proprietary products in this niche are:
 Microsoft’s Active Server Pages (ASP)
 Macromedia’s ColdFusion, and
 Sun’s Java Server Pages (JSP).

 Over the past few years, PHP and server-side Java have
gained momentum, while ASP has lost its share.
Introduction to PHP…
 PHP is a server-side scripting language, which means that the
scripts are executed on the server, the computer where the
Web site is located.
 This is different than JavaScript, another popular language for
dynamic Web sites.
 JavaScript is executed by the browser, on the user’s computer.
 Thus, JavaScript is a client-side language.

 Because PHP scripts execute on the server, PHP can


dynamically create the HTML code that generates the Web
page.
 This allows individual users to see customized Web pages.
 Web page visitors see the output from scripts, but not the
scripts themselves.
Introduction to PHP…
 PHP is particularly strong in its ability to interact with databases.
 PHP supports pretty much every database you’ve ever heard of and
some you haven’t.
 PHP handles connecting to the database and communicating with it,
avoiding the knowledge of technical details for connecting to a
database.
 You tell PHP the name of the database and where it is, and PHP handles
the details.
 It connects to the database, passes your instructions to the database,
and returns the database response to you.

 Major databases currently supported by PHP include the following:


 dBASE
 Informix
 Ingres
 Microsoft SQL Server
 mSQL
 MySQL
 Oracle
 PostgreSQL
Introduction to PHP…
 In addition, PHP supports ODBC (Open Database
Connectivity).
 ODBC is a standard that allows you to communicate
with even more databases, such as Access and IBM
DB2.

 PHP works well for a database-driven Web site.


 PHP scripts in the Web site can store data in and
retrieve data from any supported database.
 PHP also can interact with supported databases
outside a Web environment.
 Database use is one of PHP’s best features.
Software Requirements
 To work with PHP, you need to install a web server, PHP, and
database server.
 The most commonly used web server is Apache(free)
 Similarly, for database, there are many options to use.
 The most popular database server for web pages is MySQL (free).
 PHP is also available freely on the internet.

 Software producers integrate the three software and offer them as


bundle.
 Some of such bundles are:
 Vertrigo(Apache, PHP, Mysql)
 Wamp (Windows) (Apache, Mysql, PHP)
 Xampp(Apache, Mysql, PHP, Perl)
 Lamp (Linux)(Apache, PHP, Mysql)

 PHP files are executed through the web server only, not directly
http://127.0.0.1/test.php
Writing PHP
 You add PHP code to your web page by using tags, similar to
other tags in the HTML file.
 The PHP code section is enclosed in PHP tags with the following
form:
<?php
PHP statements
?>

 For example, you can add the following PHP section to your HTML
file.
<?php
echo “This line brought to you by PHP”;
?>
 Web pages that contains PHP should be saved with .php
extension.
 You can also add several PHP sections to a Web page.
Writing PHP…
 There are actually four different styles of PHP tags we can use.
 Short style
<?
echo “<p>Order processed. </p>”;
?>
 This style of tag is the simplest and follows the style of an
SGML.
 To use this tag, you either need to enable short tags in your
config file (short_open_tag = On), or compile PHP with short
tags enabled.
 XML style
<?php
echo “<p>Order processed. </p>”;
?>
 This style of tag can be used with XML documents.
 Most commonly used tag in literatures
Writing PHP…
 SCRIPT style
<SCRIPT LANGUAGE=”php”>
echo “<p>Order processed. </p>”;
</SCRIPT>
 This style of tag is the longest and will be familiar if you’ve
used JavaScript.
 ASP style
<%
echo “<p>Order processed. </p>”;
%>
 This style of tag is the same as used in Active Server Pages
(ASP).
 It can be used if you have enabled the asp_tags configuration
setting.
Writing PHP…
 Example: your first hello world PHP script
<html>
<head><title>Hello World Script</title></head>
<body>
<?php
echo “<p>Hello World!</p>”
?>
</body>
</html>

 When the PHP section is processed, it is replaced with the


output.
 In this case, the output is as follows:
<p>Hello World!</p>
Attaching PHP to Web Pages
 PHP file is attached to web pages by using the <form> tag.
 Since PHP is written to process data sent from client computers and
form is the means to get that data, this is a logical place to attach the
PHP to HTML.

 We use the action attribute to specify the PHP to execute when the
web page is submitted.
<form name=”formname” method=”submitingmethod”
action=”phpfile.php”>
form elements
</form>

 Example: to attach a php called saver.php to an HTML page


<form name=”detail” method=”post” action=”saver.php”>
form content
</form>
 When this form is submitted, the web server looks for saver.php and
executes it.
Output Statements
 The two most basic ways for displaying output in PHP are echo
and print.
 Both can be used either with parentheses or without them.
 Function calls always have the name of the function first,
followed by a parenthesized list of the arguments to the
function.

 The general format of the echo statement is as follows:


echo outputitem1, outputitem2, outputitem3, . . .;
echo (output);

 The parameterized version of echo does not accept multiple


arguments.
 The general format of the print statement is as follows:
print output;
print(output);
Output Statements…
 Example: different ways of echo and print
echo 123; //output: 123
echo “Hello World!”; //output: Hello world!
echo (“Hello World!”); //output: Hello world!
echo “Hello”,”World!”; //output: Hello World!
echo Hello World!; //error, string should be in quotes
print (“Hello world!”); //output: Hello world!
print “Hello world!”; //output: Hello world!

 The command print is very similar to echo, with two


important differences:
 Unlike echo, print can accept only one argument.

 Unlike echo, print returns a value, which represents whether

the print statement succeeded.


Output Statements…
 The value returned by print will be 1 if the printing was
successful and 0 if unsuccessful.
 It is rare that a syntactically correct print statement
will fail.
 But in theory this return value provides a means to
test, for example, if the user’s browser has closed the
connection.
 It is possible to embed HTML tags in echo or print
statements.
 The browser will parse and interpret them like any tag
included in HTML page and display the page
accordingly.
Output Statements…

echo/print statement PHP output web page display

echo “Hello World!”; Hello World! Hello World!

echo “Hello”; HelloWorld! HelloWorld!


echo “World!”;
echo “Hello\nWorld!”; Hello Hello World!
World!
echo “Hello<br>World!”; Hello<br>World Hello
World!
echo“<u><i>Hello world!</i></u>”; <u><i>Hello world! </i></u> Hello world!
Comments
 PHP supports two types of comments:
 single-line comment (short comment), and
 multi-line comment (long comment).

 The format for multi-line comments is as follows:


/* comment text
more comment text
*/
 Your comments can be as long or as short as you
need.
Comments…
 PHP has a short comment format too.
 You can specify a single line comment by using the # or //
# This is comment line 1
// This is comment line 2

 It is customary and useful to put a block of comments at


the top of your script giving information about the script
and an overview of what it does.
/*
name: hello.php
description: Displays “Hello World!” on a Web page.
written by: John Steve
created: 2/1/11
modified: 3/15/11
*/
1.2 Working with
Variables
 In PHP, all variable names should start with a dollar
sign ($).
 This tells PHP that it is a variable name.
 To store information in a variable you use a single
equal sign (=).
 For example:
$age = 21;
$price = 20.52;
$temperature = -5;
$name = “Clark Kent”;
echo “Your age is $age”;
1.2 Working with
Variables…
 PHP has a total of eight types: integers, doubles,
Booleans, strings, arrays, objects, NULL, and resources:
 Integers are whole numbers, without a decimal point, like
495.
 Doubles are floating-point numbers, like 3.14159 or 49.0.
 Booleans have only two possible values: TRUE and FALSE.
 Strings are sequences of characters, like “PHP is very
interesting”.
 Arrays are named and indexed collections of other values.
 Objects are instances of programmer-defined classes.
 Resources are special variables that hold references to
resources external to PHP such as database connections.
 NULL is a special type that only has one value: NULL.
1.2 Working with
Variables…
 PHP is a loosely typed language.
 This means that a single variable may contain any type
of data.
 This could be a number, a string of text, or some other
kind of value, and may change types over its lifetime.

 Example:
$testvar = 3 + 4;
echo “The value is $testvar”; //output: The value is 7
$testvar = “three”;
echo “The value is $testvar”; //output: The value is
three
1.2 Working with
Variables…
Displaying variable values
 You can display the value stored in a variable with print statement.

You can output the value of a variable as in the following


statements:
$today = “Sunday”;
print(“The day today is $today”);
 The output from the preceding statements is “The day today is

Sunday”.

Removing Variables
 You can uncreate the variable by using this statement:

unset($age);

 After this statement, the variable $age no longer exists.


 If you try to echo it, you get an “undefined variable” notice.
 You can unset more than one variable at once, as follows:
unset($age, $name, $address);
1.2 Working with
Variables…
Checking variable content
 Sometimes you just need to know whether a variable

exists or what type of data is in the variable.


 Here are some common ways to test variables:

 isset($varname) - true if variable is set, even if nothing


is stored in it.
 empty($varname) - true if value is 0 or is a string with
no characters in it or is not set.

 You can also test what type of data is in the variable.


 For example, to see if the value is an integer:
 is_int($number) - the comparison is TRUE if the value in
$number is an integer.
1.2 Working with
Variables…
 Some other tests provided by PHP are as follows:
 is_integer($var): same as is_int($var)
 is_array($var2): Checks to see if $var2 is an array
 is_float($number): Checks if $number is a floating point number
 is_null($var1): Checks to see if $var1 is equal to 0
 is_numeric($string): Checks to see if $string is a numeric string
 is_string($string): Checks to see if $string is a string
 is_bool($var): finds out whether a variable is a boolean

 You can test for a negative, as well, by using not operator (!)
in front of the expression.
 For example, the following statement returns TRUE if the
variable does not exist at all:
 !isset($varname)
1.2 Working with
Variables…
<?php
$a = "test";
$b = "anothertest";
echo isset($a); // TRUE
echo isset($a, $b); //TRUE
unset ($a);
echo isset($a, $b); //FALSE
$foo = NULL;
print isset($foo); // FALSE
$var = 0;
if (empty($var)) // evaluates TRUE
echo '$var is either 0 or not set at all';
?>
1.2 Working with
Variables…
Type Casting
 We often work with multiple data types at once.

 Converting one data type to another one is a common

task in programming.
 Type conversion or typecasting refers to changing an

variable of one data type into another.


 There are two types of conversion.

 Implicit and
 Explicit

 Implicit type conversion is an automatic type conversion


by the compiler.
 Example:
echo "45" + 12; //output: 57
1.2 Working with
Variables…
 Explicit conversion happens, when we use the
cast constructs.
 There are two ways to do this:
 Using bool settype ( mixed var, string type) function
 Using cast methods

 The cast methods are:


 (int), (integer) - cast to integer
 (bool), (boolean) - cast to boolean
 (float), (double), (real) - cast to float
 (string) - cast to string
 (array) - cast to array
 (object) - cast to object
1.2 Working with
Variables…
 Settype sets the type of a variable.

 The syntax is:


bool settype ( mixed var, string type)
 Possibles values of type are:
 "boolean" (or, since PHP 4.2.0, "bool")
 "integer" (or, since PHP 4.2.0, "int")
 "float" (since PHP 4.2.0, for older versions use
"double")
 "string"
 "array"
 "object"
 "null" (since PHP 4.2.0)
1.2 Working with
Variables…
Example:
$foo = "321.456number";
settype($foo, "float");
print("<br>Float: $foo"); //output: Float: 321.456
$foo = "321.456number";
settype($foo, "integer");
print("<br>Integer: $foo"); //output: Integer: 321

$foo = 321.456;
settype($foo, "string");
print("<br>String: $foo"); //output: String: 321.456

$foo = “10.7S”; // $foo is string


$bar = (float) $foo; // $bar is float
$val = (int) $foo; //$val is int
1.2 Working with
Variables…
Creating Constants
 We use constants to define values that do not change like

PI in maths(3.14..), number of days in a week(7), number of


minutes in an hour(60), etc.

 Constants are set by using the define statement.


 The general format is as follows:
define(“constantname”, ”constantvalue”);

 For example, to set a constant with the weather, use the


following statement:
define(“PI”,”3.141”);
 This statement creates a constant called PI and sets its
value to “3.141”.
1.2 Working with
Variables…
 unlike variables, constant names do not begin with a dollar sign
($).
 By convention, constants are given names that are all
uppercase
 so you can see easily that they’re constants.
 However, PHP accepts lowercase letters without complaint.

 You can store either a string or a number in a constant.


 Example:
define (“INTEREST”,0.01);

 Constants should not be given names that are keywords for PHP.
 Keywords are words that have meaning for PHP, such as echo,
and they can’t be used as constants because PHP treats them
as the PHP feature of the same name.
1.2 Working with
Variables…
Displaying constants
 You can determine the value of a constant by using print as

follows:
print(INTEREST);

 You can also use a constant in an echo statement:


echo INTEREST;

 When you echo a constant, you can’t enclose it in quotes.


 If you do, it echoes the constant name rather than the value.
 You can build more complicated output statements by using
commas, as in the following example:
echo “The Canadian exchange rate is $”, INTEREST;
1.2 Working with
Variables…
$test_val = 5.5466;
settype($test_val, "integer");
echo $test_val;
output: 5

$num = 33;
(boolean) $num;
echo $num;
Output: 33

echo gettype("4");
Output: String
1.3 Using Operators
 PHP supports many operators.

Mathematical Operators
 Arithmetic operators are straightforward—they

are just the normal mathematical operators.


Operator Description
+ Adds two numbers together.
- Subtracts the second number from the first number.
* Multiplies two numbers together.

/ Divides the first number by the second number.


% Finds the remainder when the first number is divided by the
second number.
1.3 Using Operators…
 Example: a program that performs all
mathematical operation on two numbers
$a = 10;
$b = 20;
$c = $a + $b; //result: 30
$c = $a - $b; //result: -10
$c = $a * $b; //result: 200
$c = $a / $b; //result: 0.5
$c = $a % $b; //result: 10
1.3 Using Operators…
 You should note that arithmetic operators are
usually applied to integers or doubles.
 If you apply them to strings, PHP will try and
convert the string to a number.

 If it contains an “e” or an “E”, it will be converted


to a double; otherwise it will be converted to an
int.
 PHP will look for digits at the start of the string and
use those as the value
 If there are none, the value of the string will be
zero.
1.3 Using Operators…
Pre- and Post-Increment and Decrement operators
operator description example meaning

++ postfix increment $x++ $x = $x+1

-- postfix decrement $x-- $x = $x-1

++ prefix increment ++$x $x = $x+1

-- prefix decrement --$x $x = $x+1

Example: a program that performs postfix and prefix operations


$a = 4;
echo “<br>”, ++$a;
$b = 10;
echo “<br>”, $b++;
echo “<br>”, $b;
1.3 Using Operators…
 All the increment operators have two effects—they increment and assign
a value.
$a=4;
echo ++$a;
 The second line uses the prefix increment operator.
 First, $a incremented by 1, and second, returns the incremented value.
 In this case, $a is incremented to 5 and then the value 5 is returned and
printed.

 However, if the ++ is after the $a, we are using the postfix increment
operator.
 This has a different effect.
$a=4;
echo $a++;

 In this case, first, the value of $a is returned and printed, and second, it is
incremented.
 The value that is printed is 4.
 However, the value of $a after this statement is executed is 5.
1.3 Using Operators…
Operator description example meaning

+= add and assign $x += 5 $x = $x + 5

-= subtract and assign $x -= 5 $x = $x – 5

/= divide and assign $x /= 5 $x = $x / 5

*= multiply and assign $x *= 5 $x = $x * 5

%= modulate and assign $x %= 5 $x = $x % 5

.= concatenate and assign $x .= " test" $x = $x." test"


1.3 Using Operators…
Comparison operators
 The comparison operators are used to compare two
values.
operator Expressions using these operators return either

name description
== true
equal or false
True if its arguments are equal to each other, false otherwise
!= not equal False if its arguments are equal to each other, true otherwise
< less than True if the left-hand argument is less than its right-hand argument, but false
otherwise
> greater than True if the left-hand argument is greater than its right-hand argument, but
false otherwise
<= less or equal True if the left-hand argument is less than its right-hand argument or equal to
it, but false otherwise
>= greater or equal True if the left-hand argument is greater than its right- hand argument or
equal to it, but false otherwise
=== identical True if its arguments are equal to each other and of the same type, but false
otherwise
1.3 Using Operators…
 Example:
<?php
$var = "30";
$num = 30;
if($var == $num)
print "They are equal.<br>";
if($var === $num)
print "They are equal and same data type.<br>";
$var = (int) “30”;
if($var === $num)
print "2. They are equal and same data type.<br>";
?>

Output:
They are equal
1.3 Using Operators…
Logical Operators
 The logical operators are used to combine the

results of logical conditions.


 For example, we might be interested in a case

where the value of a variable is between 0 and


100.
 We would need to test the conditions $a >= 0

and $a <= 100, using the AND operator, as


follows:
if($a >= 0 && $a <=100)
1.3 Using Operators…

operator description

and Is true if and only if both of its arguments are true

or Is true if either (or both) of its arguments are true.

xor Is true if either (but not both) of its arguments are true

! Is true if its single argument (to the right) is false and false if its argument is true

&& Same as and, but binds to its arguments more tightly

|| Same as or but binds to its arguments more tightly


1.3 Using Operators…
 Bitwise Operators
Operator Name Result
& And Sets result bit to 1 if both bits are set
| Or Sets result bit to 1 if either of the bits are set
^ Xor Sets result bit to 1 if either of the bits but not both are set
~ Not Bits that are set first are not set, and vice versa.
<< Shift left Shift the bits of $a $b steps to the left (each step means
multiply by two)

>> Shift right Shift the bits of $a $b steps to the right (each step means
divide by two)
1.3 Using Operators…
<?php
echo 12 ^ 9; // Outputs '5'
echo "1" ^ "9"; // Outputs the Backspace (ascii 8)
// ('1' (ascii 49)) ^ ('9' (ascii 57)) = #8

echo "hallo" ^ "hello"; // Outputs the ascii values #0

//#4 #0 #0 #0 -> 'a' ^ 'e' = #4


echo 2 ^ "3"; // Outputs 1 -> 2 ^ ((int)"3") == 1
echo "2" ^ 3; // Outputs 1 -> ((int)"2") ^ 3 == 1
echo “2” + “3”; //outputs 5
?>
Associativity Operators
non-associative new
right [
right ! ~ ++ -- (int) (float) (string) (array) (object) @
left */%
left +-.
left << >>
non-associative < <= > >=
non-associative == != === !==
left &
left ^
left |
left &&
left ||
left ?:
left = += -= *= /= .= %= &= |= ^= ~= <<= >>=
right print
left and
left xor
left or
left ,
1.3 Using Operators…
The ternary operator
 It plays a role somewhere between a Boolean operator and a
true branching construct.
 Its job is to take three expressions and use the truth value of
the first expression to decide which of the other two
expressions to return.
 The syntax looks like:
test-expression ? yes-expression : no-expression

 The value of this expression is the result of yes-expression if


test-expression is true; otherwise, it returns no-expression.
 For example, assigning to $max either $first or $second,
whichever is larger:
$max_num = $first > $second ? $first : $second;
1.4 Conditional Statements

1.4.1 if Statements
 We can use an if statement to make a decision.

 You should give the if statement a condition that is evaluated to

true or false.
 If the condition is true, the associated block of code will be

executed.
 Conditions in if statements must be surrounded by brackets ().

 The syntax of if statement:


if(condition) {
statements;
}

 Example: an if statement that checks if a variable value is less than


50 (student failed course)
if($mark<50){
print(“You have to improve your mark”);
1.4 Conditional
Statements…
if..else statements
 An else statement allows you to define an alternative action

to be taken when the condition in an if statement is false.


 This allows to take one action when the condition is true and

another action when the condition is false.

 The syntax of if statement:


if(condition) {
statements;
}
else {
statements;
}
1.4 Conditional
Statements…
 Example:
if($mark<50) {
print(“You failed this course”);
}
else{
print(“You have passed the course”);
}
1.4 Conditional
Statements…
else if Statements
 For many of the decisions we make, there are more than two options.

 We can create a sequence of many options using the elseif statement.

 By providing a sequence of conditions, the program can check each

until it finds one that is true.

 Example: a program that checks if a variable value is between 1 and 5


and display message accordingly
if ($day == 5)
print(“Five golden rings<BR>”);
elseif ($day == 4)
print(“Four calling birds<BR>”);
elseif ($day == 3)
print(“Three French hens<BR>”);
elseif ($day == 2)
print(“Two turtledoves<BR>”);
elseif ($day == 1)
print(“A partridge in a pear tree<BR>”);
1.4 Conditional
Statements…
1.4.2 switch statements
 The switch statement works in a similar way to the if
statement, but allows the condition to take more than
two values.
 In an if statement, the condition can be either true or
false.
 In a switch statement, the condition can take any
number of different values, as long as it evaluates to a
simple type (integer, string, or double).
 You need to provide a case statement to handle each
value you want to react to and, optionally, a default
case to handle any that you do not provide a specific
case statement for.
1.4 Conditional
Statements…
switch (expression) {
case result1:
//execute this if expression results in result1
break;
case result2:
//execute this if expression results in result2
break;
default:
//execute this if no break statement
//has been encountered
}

 The expression used in a switch statement is often just a variable.


 Within the switch statement's block of code, you find a number of case
statements.
 Each of these cases tests a value against the result of the switch
expression.
 If the case is equivalent to the expression result, the code after the case
1.4 Conditional
Statements…
 The break statement ends the execution of the switch
statement altogether.
 If the break statement is left out, the next case
statement is evaluated.
 If the optional default statement is reached, its code
is executed.
 It is important to include a break statement at the end
of any code that will be executed as part of a case
statement.
 Without a break statement, the program flow will
continue to the next case statement and ultimately to
the default statement.
 In most cases, this will result in unexpected behavior,
likely incorrect!
Example: switch statement that checks the mood of the person
<html>
<head>
<title>Listing 5.4</title>
</head>
<body>
<?php
$mood = "sad";
switch ($mood)
{
case "happy":
echo "Hooray, I'm in a good mood";
break;
case "sad":
echo "Awww. Don't be down!";
break;
default:
print "Neither happy nor sad but $mood";
break;
}
?>
</body>
</html>
1.5 Using Loops
 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.
 For example, a loop that echoes the names of all the files in a directory
needs to repeat until it runs out of files, regardless of how many files there
are.
 There are three types of loops:
 for loop: Sets up a counter; repeats a block of statements until the
counter reaches a specified number
 while loop: Sets up a condition; checks the condition, and if it’s
true, repeats a block of statements until the condition becomes
false
 do..while loop: Sets up a condition; executes a block of statements;
checks the condition; if the condition is true, repeats the block of
statements until the condition becomes false
1.5 Using Loops…
1.5.1 for loop
 The most basic for loops are based on a counter.
 You set the beginning value for the counter, set the ending value, and set
how the counter is incremented/decremented each time the statement
block is executed.
 The general format is as follows:
for (startingvalue; endingcondition; increment)
{
block of statements;
}

 Example:
for ($i = 1; $i <= 3; $i++) {
echo “$i. Hello World!<br>”;
}
The following is the output from these statements:
1. Hello World!
2. Hello World!
 You can nest for loops inside of for loops.
 Suppose you want to print out the times tables from 1 to 9.
1x1=1
...
1x9=9
2x1=2
...
2 x 9 = 18

9x1=9

9 x 9 = 81

 You can use the following nested loop statements:


for($i=1; $i<=9; $i++)
{
for($j=1; $j<=9; $j++)
{
$result = $i * $j;
echo “$i x $j = $result\n”;
}
}
1.5 Using Loops…
1.5.2 while loop
 One of PHP looping construct is while, which has the following

syntax:
while (condition)
{
statement
}

 The while loop evaluates the condition expression as a Boolean


— if it is true, it executes statement and then starts again by
evaluating condition.
 If the condition is false, the while loop terminates.
 Of course, just as with if, statement may be a single statement
or it may be a brace-enclosed block.
 The body of a while loop may not execute even once, as in:
while (FALSE)
1.5 Using Loops…
 Or it may execute forever, as in this code snippet:
while (TRUE)
print(“All work and no play makes Jack a dull boy.<BR>”);

 or it may execute a predictable number of times, as in:


$count = 1;
while ($count <= 10)
{
print(“count is $count<BR>”);
$count = $count + 1;
}
 which will print exactly 10 lines.
1.5 Using Loops…
1.5.3 do..while loop
 A do..while loop is very similar to a while loop.

 Like a while loop, a do..while loop continues repeating as long

as certain conditions are true.


 Unlike while loops, however, those conditions are tested at the

bottom of each loop.


 If the condition is true, the loop repeats.

 When the condition is not true, the loop stops.

 The general format for a do..while loop is as follows:


do
{
block of statements
} while (condition);
1.5 Using Loops…
 Example: a loop that displays numbers from 1 to 10
$count = 1;
do
{
print(“count is $count<BR>”);
$count = $count + 1;
}while ($count <= 10);

Avoiding infinite loops


 You can easily set up loops so that they never stop.

 These are called infinite loops.

 They repeat forever.

 However, seldom does anyone create an infinite loop intentionally.

 It is usually a mistake in the programming.

 If your loop is running infinitely, your script is running for an infinite

amount of time.
 This is very stressful on your Web server, and renders the Web page in
1.5 Using Loops…
 Example: infinite loop
$i = 1;
while($i < 10)
{
print(“i is $i”);
}

 output:
i is 1
i is 1
...
 The variable $i is not incremented in the body of the
while loop.
 As a result, the value of $i is always 1 making the while
1.5 Using Loops…
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.
1.5 Using Loops…
Example: break statement
$counter = 0;
while ( $counter < 5 ) {
$counter++;
if ( $counter == 3 ) {
echo “break\n”;
break;
}
echo “Last line in loop: counter=$counter\n”;
}
echo “First line after loop\n\n”;

The output of this statement is the following:


Last line in loop: counter=1
Last line in loop: counter=2
break
1.6 Arrays
 An array is a variable that stores a set or sequence of values.
 One array can have many elements.
 Each element can hold a single value, such as text or numbers, or
another array.
 An array containing other arrays is known as a multidimensional
array.
 A scalar variable is a named location in which to store a single
value
 Similarly, an array is a named place to store a set of values,
thereby allowing you to group common scalars.
 The values stored in an array are called the array elements.
 Each array element has an associated index (also called a key)
that is used to access the element.
 Arrays in most programming languages have numerical indexes
that typically start from zero or one.
 PHP supports this type of array.
1.6 Arrays…
 In addition to numerical indexes, PHP also supports associative arrays.
 Associative arrays can have almost anything as the array indices, but
typically use strings.

Creating Arrays
 There are different ways to create an array in a PHP script:
 by assigning a value into one (and thereby implicitly creating it),
 by using the array() construct, or
 by calling a function that happens to return an array as its value.

 The simplest way to create an array is to act as though a variable is


already an array and assign a value into it.
 Example: the following code will create an array called $products by
assigning value:
$products[0] = “Tires”;
$products[1] = “Oil”;
$products[2] = “Spark Plugs”;
$products[3] = “battery”;
$products[4] = “jar”;
1.6 Arrays…
 If $products does not already exist (which is true in this case), the
first line will create a new array with just one element.
 The subsequent lines add values to the array.

 The other way to create an array is via the array() construct


 This creates a new array from the specification of its elements
and associated keys.
 In its simplest version, array() is called with no arguments, which
creates a new empty array.
 In its next simplest version, array() takes a comma-separated list
of elements to be stored, without any specification of keys.
 The result is that the elements are stored in the array in the order
specified and are assigned integer keys beginning with zero.

 For example, the statement:


$fruit = array(“apple”, “orange”, “banana”, “pear”);
1.6 Arrays…
 This causes the variable $fruit to be assigned to an array with four
string elements(‘apple’, ‘banana’, ‘orange’, ‘pear’), with the indexes 0,
1, 2, and 3, respectively.
 In addition, the array will remember the order in which the elements
were stored.

Associative Arrays
 In the products array, we allowed PHP to give each item the default

index.
 PHP also supports associative arrays.

 In an associative array, we can associate any key or index we want

with each value.

 An associative array can be viewed as a list of key/value pairs, stored


as follows:
$arrayname[‘key1’] = value1;
$arrayname[‘key2’] = value2;
$arrayname[‘key3’] = value3;
1.6 Arrays…
 Initializing an Associative Array
$person = array("name" => "Bob", "occupation" =>
"engineer", "age" => 30, "special power" => "x-ray
vision");

 The four keys in the $person array are called name,


occupation, age, and special power.
 The associated values are Bob, engineer, 30, and x-ray
vision.
 You can reference specific elements of an associative
array using the specific key.

 Example: to access associative array element


echo $person['occupation']; //output: engineer
1.6 Arrays…
Walking through Array
 It is possible to traverse through an array in different

ways.
 One is by using loop together with array index.

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


print(“\n$product[$i]”);

 output:
Tires
Oil
Spark Plugs
battery
Jar
1.6 Arrays…
Using foreach to walk through an array
 You can use foreach to walk through an array one value at a

time and execute a block of statements by using each value in


the array.
 The general format is as follows:

foreach ( $arrayname as $keyname => $valuename)


{
block of statements;
}
 In this format, you need to fill in the following information:
 arrayname: The name of the array you are walking through.
 keyname: The name of the variable where you want to store the key.
The keyname variable is optional. If you leave out $keyname =>,
only the value is stored into $valuename.
 valuename: The name of the variable where you want to store the
value.
1.6 Arrays…
 Example: foreach loop
$population = array ( “Oro” => 25000, “Amh” => 20000, “Tig”
=> 5000);
ksort($population);
foreach($population as $state => $pop)
{
$pop = number_format($pop);
echo “$state: $pop.<br>”;
}

Multidimensional Arrays
 Arrays do not have to be a simple list of keys and values—

each location in the array can hold another array.


 This way, we can create a two-dimensional array.

 You can think of a two dimensional array as a matrix, or grid,


1.6 Arrays…
 If we want to store more than one piece of data
about products, we could use a two-dimensional
array.
1.6 Arrays…
 Using array() construct:
$products = array( array( “TIR”, “Tires”, 100 ),
array( “OIL”, “Oil”, 10 ),
array( “SPK”, “Spark Plugs”, 4 ) );

 Using assigning values:


$product[0][0] = “TIR”;
$product[0][1] = “Tires”;
$product[0][2] = “100”;
$product[1][0] = “OIL”;
$product[1][1] = “Oil”;
$product[1][2] = “10”;
$product[2][0] = “SPK”;
$product[2][1] = “Spark Plugs”;
$product[2][2] = “4”;
1.6 Arrays…
Array Functions
Sorting Arrays
 It is often useful to sort data stored in an array.

 Taking a one-dimensional array and sorting it into order is quite

easy.
 The following code results in the array being sorted into

ascending alphabetical order:


$products = array( “Tires”, “Oil”, “Spark Plugs” );
sort($products);
Output: Oil, Spark Plugs, Tires.

 Note that the sort function is case sensitive.


 All capital letters come before all lowercase letters.
 So ‘A’ is less than ‘Z’, but ‘Z’ is less than ‘a’.
1.6 Arrays…
 Example:
$streets[0] = “Elm St.”;
$streets[1] = “Oak Dr.”;
$streets[2] = “7th Ave.”;
 You enter the following sort statement:
sort($streets);
 Now the array becomes as follows:
$streets[0] = “7th Ave.”;
$streets[1] = “Elm St.”;
$streets[2] = “Oak Dr.”;
1.6 Arrays…
 If we are using an associative array to store items and their
prices, we need to use different kinds of sort functions to keep
keys and values together as they are sorted.
 In this case, we use either assort() or ksort().
 The function asort() orders the array according to the value of
each element.
 If the sorting should be done by key instead of value, we use
ksort().

 The following code creates an associative array and then sorts the
array into ascending price order.
$prices = array( “Tires”=>100, “Oil”=>10, “Spark Plugs”=>4 );
asort($prices);
$prices = array( “Tires”=>100, “Oil”=>10, “Spark Plugs”=>4 );
ksort($prices);
1.6 Arrays…
 Example:
$capitals[1] = “Sacramento”;
$capitals[2] = “Austin”;
$capitals[3] = “Salem”;

 After an asort() statement, the new array would


be as follows:
$capitals[2] = Austin
$capitals[1] = Sacramento
$capitals[3] = Salem
1.6 Arrays…
Sort Statement What It Does

sort($arrayname) Sorts by value; assigns new numbers as index.

asort($arrayname) Sorts by value; keeps the same key/index.

rsort($arrayname) Sorts by value in reverse order; assigns new numbers as the keys.

arsort($arrayname) Sorts by value in reverse order; keeps the same key/index.

ksort($arrayname) Sorts by key.

krsort($arrayname) Sorts by key in reverse order.

natsort($arrayname) Sorts mixed string/number values in natural order. For example, given an
array with values day1, day5, day11, day2, it sorts into the following order:
day1, day2, day5, day11. The previous sort functions sort the array into this
order: day1, day11, day2, day5.
1.6 Arrays…
Determining Size of Array
 You can find out the size of your array by using either the count

statement or a sizeof statement.


 The format for these statements is as follows:

$n = count($arrayname);
$n = sizeof($arrayname);
 After either of these statements, $n will contain the number of

elements in the array.

Built-in Arrays
 PHP has several built-in arrays that you can use when writing PHP

scripts.
 Different types of information are stored in different arrays.

 For example, information about your server (such as headers, paths,

and script locations) is stored in an array called $_SERVER


Array Description
$GLOBALS Contains all the global variables. For example, if you use the statement, $testvar = 1, you
can then access the variable as $GLOBALS [‘testvar’].
$ _POST Contains all the variables contained in a form if the form uses method=”post”.

$HTTP_POST_VARS Same as $ _POST.


$ _GET Contains all the variables passed from a previous page as part of the URL. This includes
variables passed in a form using method=”get”.
$HTTP_GET_VARS Same as $ _GET.
$ _COOKIE Contains all the cookie variables.
$HTTP_COOKIE_VARS Same as $ _COOKIE.

$ _SESSION Contains all the session variables.


$HTTP_SESSION_VARS Same as $ _SESSION.

$_REQUEST Contains all the variables together that are in $_POST, $_GET, and $_SESSION.

$_FILES Contains the names of files that have been uploaded.


$HTTP_FILES_VARS Same as $_FILES.
$_SERVER Contains information about your server. Because your Web server provides the
information, the information that’s available depends on what server you’re using.

$HTTP_SERVER_VARS Same as $_SERVER.

$_ENV Contains information provided by your operating system, such as the operating system
name, the system drive, and the path to your temp directory. This info varies depending
on your operating system
$HTTP_ENV_VARS Same as $_ENV.
1.6 Arrays…
 The $_SERVER and $_ENV arrays contain different
information, depending on the server and
operating system you’re using.
 You can see what information is in the arrays for
your particular server and operating system by
using the following statements:
foreach($_SERVER as $key =>$value)
echo “Key=$key, Value=$value\n”;
1.6 Arrays…
 The output includes such lines as the following:
Key=HTTP_HOST, Value=127.0.0.1
Key=HTTP_ACCEPT, Value=text/html,application/xhtml+xml,
application/xml;q=0.9,*/*;q=0.8
Key=HTTP_ACCEPT_LANGUAGE, Value=en-us,en;q=0.5
Key=HTTP_ACCEPT_ENCODING, Value=gzip, deflate
Key=HTTP_ACCEPT_CHARSET, Value=ISO-8859-1,utf-8;q=0.7,*;q=0.7
Key=HTTP_CONNECTION, Value=keep-alive
Key=WINDIR, Value=C:\Windows
Key=SERVER_SIGNATURE, Value=
Key=SERVER_SOFTWARE, Value=Apache/2.2.17 (Win32) PHP/5.3.6
Key=SERVER_ADDR, Value=127.0.0.1
Key=SERVER_PORT, Value=80
Key=REMOTE_ADDR, Value=127.0.0.1
Key=DOCUMENT_ROOT, Value=C:/Program Files (x86)/VertrigoServ/www
Key=SERVER_ADMIN, [email protected]
Key=SCRIPT_FILENAME, Value=C:/Program Files
(x86)/VertrigoServ/www/environment.php
Key=REMOTE_PORT, Value=2005
Key=GATEWAY_INTERFACE, Value=CGI/1.1
Key=SERVER_PROTOCOL, Value=HTTP/1.1
Key=REQUEST_METHOD, Value=GET
Key=QUERY_STRING, Value=
1.6 Arrays…
 The PHP_SELF element shows the file that
contains the script that is currently
running.
 You can see the information in the $_ENV
array by using the phpinfo() statement
with a 16 to specify the environmental
variables, as follows:
phpinfo(16);
1.7 Functions in PHP
 Applications often perform the same task at different points in the
script or in different scripts.
 This is when functions come in handy.
 A function is a group of PHP statements that perform a specific task.
 You can use the function wherever you need to perform the task.

Defining Functions
 You can create a function by putting the code into a function block.

 The general format is as follows:

function functionname($argument1, $argument2, ….)


{
block of statements;
return value;
}
1.7 Functions in PHP…
 Example:
function addNumbers($a, $b)
{
$sum = $a +$b;
return $sum
}

Calling a function
 The following line is the simplest possible call to a function:

functionName();
 This calls a function called functionName that does not

require parameters.
 This line of code ignores any value that might be returned by

this function.
1.7 Functions in PHP…
 Most functions do require one or more parameters.
 We pass parameters by placing the data or the name of a
variable holding the data inside parentheses after the
function name.
 A call to a function with a parameter resembles the
following:
function_name(parameter);

 Example: other possible calls


function_name(2);
function_name(7.993);
function_name($variable);
 In the last line, $variable might be any type of PHP
variable, including an array.
 A parameter can be any type of data
1.7 Functions in PHP…
 You can call functions by passing multiple values to the function
by putting the values between the parentheses as follows:
functionname(value1,value2,...);

 Example: to call the above addNumbers function:


$result = addNumbers(30,20);

Pass by Reference Versus Pass by Value


 If we want to write a function called increment() that allows us to

increment a value, we might be tempted to try writing it as


follows:
function increment($value, $amount)
{
$value = $value +$amount;
}
1.7 Functions in PHP…
 This code will be of no use. The output from the following test
code will be “10”.
$value = 10;
increment ($value, 1);
echo $value;

 The contents of $value have not changed.


 This is because of the scope rules.
 This code creates a variable called $value which contains 10 &
calls the function increment().
 The variable $value in the function is created when the function
is called.
 One is added to it, so the value of $value is 11 inside the
function, until the function ends.
 In calling code, the variable $value is a different variable, with
global scope, and therefore unchanged.
1.7 Functions in PHP…
 The normal way that function parameters are called is called
pass by value.
 When you pass a parameter, a new variable is created which
contains the value passed in.
 It is a copy of the original.
 You are free to modify this value in any way, but the value of
the original variable outside the function remains unchanged.

 The better approach is to use pass by reference.


 When a parameter is passed by reference, rather than creating
a new variable, the function receives a reference to the original
variable.
 This variable rather than having a value of its own, it merely
refers to the original.
 Any modifications made to the reference also affect the original.
1.7 Functions in PHP…
 We specify that a parameter is to use pass by
reference by placing an ampersand (&) before the
parameter name in the function’s definition.
 No change is required in the function call.

 The preceding increment() example can be modified


to have one parameter passed by reference, and it
will work correctly.
function increment(&$value, $amount = 1)
{
$value = $value +$amount;
}
1.7 Functions in PHP…
Variable Scope
 A variable declared within a function remains local to that function.

 In other words, it will not be available outside the function or within

other functions.
 A variable’s scope controls where that variable is visible and

useable.
 PHP has fairly simple rules:
 Variables declared inside a function are in scope from the statement in
which they are declared to the closing brace at the end of the function.
This is called function scope. These variables are called local variables.
 Variables declared outside of functions are in scope from the statement in
which they are declared to the end of the file, but not inside functions.
This is called global scope. These variables are called global variables.
 Using require() and include() statements does not affect scope. If the
statement is used within a function, function scope applies. If it is not
inside a function, global scope applies.
 The keyword global can be used to manually specify that a variable
defined or used within a function will have global scope.
1.7 Functions in PHP…
 Example: local variable
<?php
function test()
{
$testvariable = "this is a test variable";
}
echo "test variable: $testvariable<br>";
?>

 The value of the variable $testvariable is not printed.


 This is because no such variable exists outside the test() function.
 Note that the attempt to access a nonexistent variable does not
cause an error.
 Similarly, a variable declared outside a function will not
automatically be available within it.
1.7 Functions in PHP…
 If you want a variable created within a function to be global, we
can use the keyword global as follows:
function fn()
{
global $var;
$var = “contents”;
echo “inside the function, \$var = “.$var.”<br>”;
}
fn();
echo “outside the function, \$var = “.$var.”<br>”;

 output:
inside the function, $var = contents
outside the function, $var = contents
1.8 Cookies and Sessions
1.8.1 Cookies
 You can store information in cookies and then retrieve it.

 You store cookies by using the setcookie function.

 The general format is as follows:

setcookie(“variable”,”value”);
 The variable is the variable name, but you do not include

the dollar sign ($).


 This statement stores the information only until the user

leaves your Web site.


 For example, the following statement stores the pair


city=Jimma in the cookie file on the user’s computer:
setcookie(“city”,”Jimma”);
1.8 Cookies and
Sessions…
 When the user moves to the next page, the cookie
information is available in the built-in array called $_COOKIE.
 The next Web page can display the information from the
cookie by using the following statement.
echo “Your home city is “.$_COOKIE[‘city’];

 The output from this statement is as follows:


Your home city is Jimma

 Setting expiration dates


 If you want the information stored in a cookie to remain in a
file on the user’s computer after the user leaves your Web
site, set your cookie with an expiration time, as follows:
setcookie(“variable”,”value”,expiretime);
1.8 Cookies and
Sessions…
 The expiretime value sets the time when the cookie expires.
 The value for expiretime is usually set by using either the time or
mktime function as follows:
 time: This function returns the current time in a format the computer
can understand. You use the time function plus a number of seconds
to set the expiration time of the cookie:
setcookie(“state”, ”CA”, time()+3600); #expires in one hour
setcookie(“Name”, $Name, time()+(3*86400)) #expires 3 days

 mktime: This function returns a date and time in a format that the
computer can understand. You must provide the desired date and time
in the following order: hour, minute, second, month, day, and year. If
any value is not included, the current value is used.

 This is shown in the following statements:


setcookie(“state”, ”CA”, mktime(3,0,0,4,1,2003)); #expires at 3:00 AM on April
1, 2003
setcookie(“state”, ”CA”, mktime(13,0,0,,,)); /#expires at 1:00 PM today
1.8 Cookies and
Sessions…
 Deleting a Cookie
 Officially, to delete a cookie, you should call setcookie()
with the name argument only:
setcookie("vegetable");
 This approach does not always work well, however, and
should not be relied on.

 It is safest to set the cookie with a date you are sure has
already expired:
setcookie("vegetable", "", time()-60);
 You should also ensure that you pass setcookie() the same
path, domain, and secure parameters as you did when
originally setting the cookie.
1.8 Cookies and
Sessions…
1.8.2 Session
 A session is the time that a user spends at your Web site.

 Users may view many Web pages between the time they enter your site

and leave it.


 Often you want information to be available for a complete session.

 Beginning with version 4.0, PHP provides a way to do this.

 After you create a session, the session variables are available for your
use on any other Web page. To make session information available, PHP
does the following:
 PHP assigns a session ID number.
 The number is a really long nonsense number that is unique for the user
and that no one could possibly guess. The session ID is stored in a PHP
system variable named PHPSESSID.
 PHP stores the variables that you want saved for the session in a file on the
server.
 The file is named with the session ID number.
 It’s stored in a directory specified by session.save_path in the php.ini file.
 PHP passes the session ID number to every page.
1.8 Cookies and
Sessions…
 If the user has cookies turned on, PHP passes the
session ID by using cookies.
 If the user has cookies turned off, PHP behavior
depends on whether trans-sid is turned on in
php.ini.
 PHP gets the variables from the session file for
each new session page.
 Whenever a user opens a new page that is part of
the session, PHP gets the variables from the file by
using the session ID number that was passed from
the previous page.
 The variables are available in the $_SESSION array.
1.8 Cookies and
Sessions…
Opening and closing sessions
 You should open a session at the beginning of each Web page.

 Open the session with the session_start function, as follows:

session_start();

 The function first checks for an existing session ID number.


 If it finds one, it sets up the session variables.
 If it doesn’t find one, it starts a new session by creating a new
session ID number.

 Because sessions use cookies, if the user has them turned on,
session_start is subject to the same limitation as cookies.
 That is, to avoid an error, the session_start function must be
called before any output is sent.
 This means that it is must be the first line code in your program.
1.8 Cookies and
Sessions…
 You may want to restrict your site to users with a valid user ID and
password.
 For restricted sessions that users log into, you often want users to
log out when they’re finished.
 To close a session, use the following statement wherever to want
to close the session:
session_destroy();

Using PHP session variables


 To save a variable in a session so that it’s available on later Web

pages, store the value in the $_SESSION array, as follows:


$_SESSION[‘varname’] = “John Bonson”;
 When you open a session on any subsequent Web page, the values

stored in the $_SESSION array are available.

 If you want to stop storing any variable at any time, you can unset
the variable by using the following statement:
unset($_SESSION[‘varname’]);
1.8 Cookies and
Sessions…
 The following two scripts show how to use sessions to pass information
from one page to the next.
<?php
/* Script name: sessionTest1.php
* Description: Starts a session. Saves a session variable.
*/
session_start();
$_SESSION[‘fullName’] = “David John Antony”;
?>
<html>
<head><title>Testing Sessions page 1</title></head>
<body>
<p>This is a test of the sessions feature.
<form action=”sessionTest2.php” method=”POST”>
<input type=”text” name=”form_var” value=”testing”>
<input type=”submit” value=”Go to Next Page”>
</form>
</body>
1.8 Cookies and
Sessions…
 In this script, a session is started and one session variable called fullName is
stored.
 A form is also displayed with one text field where the user can enter some text.
 When the submit button from this form, labeled “Go to Next Page” is clicked, the
sessionTest2.php script runs.
<?php
/* Script name: sessionTest2.php
* Description: Gets a variable from an existing session.
*/
session_start();
?>
<html>
<head><title>Testing Sessions page 2</title></head>
<body>
<?php
$session_var = $_SESSION[‘fullName’];
$form_var = $_POST[‘form_var’];
echo “session_var = $session_var<br>\n”;
echo “form_var = $form_var<br>\n”;
?>
</body>
1.8 Cookies and
Sessions…
 output:
session_var = “David John Antony”;
form_var = testing

You might also like