You are on page 1of 131

Objectives

At the end of this session, you will be able to:


Define an array Create and use arrays Merge arrays Use single and multidimensional arrays );> Use array- related functions

Introduction
Programming languages use variables to store values. An array is a variable that can store a list of values. Arrays can be single-dimensional or multidimensional. All the values are referred by the same array name. In this session, we will learn how to create and use arrays. We will also learn how to initialize arrays, use single-dimensional and multidimensional arrays. In addition, we will learn to use array-related functions.

111 Defining. an A
A variable can store only one value at a time- We can change the value of the variable as many times as we want in the program. However, we can store only one value in the variable. An array is a variable that can store a set of values of the same data type. Each value in an array is termed as an element. All the elements are referenced by a common name- Each element of an array can be referred by an array name and an index. An array index is used to access an element. An index can be a number or a string. If the index is a string, the array is an associative array. If the index is a number, the array is an indexed array. By default, the index value in an array starts at zero. As a result, the index number of the last element in an array is one less than the total number of elements. For example, if there is in an array of five elements, the index number of the last element will be four.

'Neb Scripting with PHP

V 1.0 (9 2004 Aptech Limited

Page 153 of 274

6
Session 13

WIDE

Working with Arrays

PHP provides us with two ways of initializing an array: array () function Enables to assign value to all the elements of an array array identifier Enables to assign value to a specific element of an array

13.2.1 The arrayoFunction


We can create an array and set the initial values of array elements using the array ( ) function. The array () function uses key value pairs separated by a comma to create an array. The number of key value pairs in the array() function determines the number of elements in an array. The syntax for creating an array using the array() function is: $array-name = array([key Where, array_name - Specifies the array name key - Specifies the index value of the array element. The key can be a string or an integer. value - Specifies the value of the element Using the array () function, we can initialize both indexed and associative arrays. Indexed Arrays An indexed array is an array where the index type is integer. By default, PHP creates an indexed array, if the index type is not specified at the time of creating an array. The index value can start with any integer, such as 1, 20, or 123. To create an indexed array named department: $department = array (1 => 'Purchase') 'Finance', .2 'Sales', value) `HR' , 4 value, [key

Page 154 of 274

session 13

~_~AprIE
R LOWIDE

To view the value of the first element, enter the following: echo $department[1]
Note the result of the above code would be Finance.

Associative Arrays An associative array is an array where the index type is string. In associative arrays, the index value must be specified within double quotes. To create an associative array named department: $department = array("a" => 'Finance', 'HR', "d" => 'Purchase') 'Sales',

In the above code snippet, the array index type is a string. Note the index value starts from a. The index values are specified within double quotes. The department array contains .three values Finance, Sales, and HR.

To view the value of the third element, enter the following: echo $department["c"];
Note the result of the above code would be HR.

13.2.2 The.-Array Identifier


Using the array identifier, we can initialize value of a specific element in an array. The syntax for creating an array using the array identifier is: $array_name[key] Where, arryname - Specifies the name of the array key - Specifies the index value of the array element. The key type can be a string or an integer. Working with Arrays ).-eiement_vaiue - Specifies the value assigned to the element of the array "elementvalue";

Page 155 of 274

.'.,-eb Scripting with PHP

V 3.0 C) 2004 Aptech Limited

A P- FW C H,

Session 13

WORLDWIDE

Working with Arrays


For example, to create the array named department containing four values, Finance, Sales, HR, and Purchase enter the following:

$department[01= $department[11= $department[21= $department[31=

"Finance"; "Sales"; "HR"; "Purchase";

To view the value of all the elements in the department array along with their respective index values, enter the following code:

$no_of_element = count($department); for ($i=0; $i< $no_of_element; { $rec = each($department); echo "$rec[keyl $rec[valuel echo "<br>";

In the above code snippet, the count () function calculates the number of elements that the array contains and stores the result in the $no_of_element variable. The each ( ) function retrieves each key value pair of an array and stores the result in the $rec variable. The for statement Y."11 continue to retrieve values of the array, till it reaches the last key value pair. The following will be the result of the above code:

0 1 2 3

Finance Sales HR Purchase

13.3 Merging- Arrays


We can combine the element values of two or more arrays. This process is called as merging: arrays. To combine the element values of two or more arrays, we must use the array--merge function. The syntax for merging arrays is:

$merged_array_name = array_merge($first_array, $second_array);


Page 156 of 274 V 1.4 2004 Aptech Limited Web Scripting with F`

Session 13

(APrECM ~= L D W I D E
Working with Arrays

Where, $merged_array_name - Specifies the name of the new array that will contain the merged element values $first array and $second_array - Specifies the names of the arrays whose elements are to be merged For example, we have two arrays, ITdept and SalesPurchasedept. The array, ITdept, contains values such as, Testing and Training. The second array, SalesPurchasedept, contains values such as Advertising and Marketing. To merge ITdept and SalesPurchasedept, use the following code: <?php $ITdept = array(O => "Testing", 1 => "Training"); $SalesPurcahsedept = array(O => "Advertising", 1 => "Marketing");

$AdminDept

array_merge($ITdept, $SalesPurchasedept);

The array AdminDept, will have values, such as Testing, Training, Advertising, and Marketing. Note that the element of the array that is mentioned first in the array merge( ) function gets the first index number. By default, PHP allots zero as the index number to the first array element. The first element value of the next array, SalesPurchasedept is allotted index numbers after allotting index numbers to the first array. The following code snippet would display $AdminDept [O] = Testing: echo "\$AdminDept[0] = ", $AdminDept[O]; Now, try to interchange the order of the arrays in the array merge following code: function, as shown in the

$AdminDept = arraymerge($SalesPurchasedept, $ITdept); echo "\$Ad-TninDept[O] = ", $ AdminDept[O],In the above code snippet, we have changed the order of the arrays' specified in the array_merge ( ) function. The output for this code snippet would be, $AdminDept [ 0 1 I Advertising.

Page 157 of 274

.:)

Scripting with PHP

V 1.5 CO 2004 Aptech Limited

Eil-PFECH

Session 13

WORLDWIDE

Working with Arrays

In a multidimensional array, one array is stored within another array. All the arrays specified in the earlier sections are single-dimensional arrays. In a single-dimensional array, the element includes only one level of key value pairs. Each element in a single-dimensional array requires an array name and an index. In the multidimensional array, each element is an array. Each element requires an array name and multiple set of indices. For example, in case of the two-dimensional array, each element requires array name and two set of indices instead of one. The syntax for creating a multidimensional array is: $array name = array(array(key => value), array(key => value)); Where,
$arrayname Specifies the name of the multidimensional array key - Specifies the index number of the array element

value - Specifies the value of the array element Note that we have one array() function within another. For example, to create an array named country_mdlist containing another array that includes information such as capital and currency of each country: $country_mdlist array( "USA" => array( "Capital" => "Washington D.C.", "Currency" => "US Dollar"), "England" => a.rray( "Capital" => "London", "Currency" => "Pound Sterling") , "Australia" => array( "Capital" => "Canberra", "Currency" => "Australian Dollar"), "New Zealand" => array( "Capital" => "Wellington", "Currency" => "NZ Dollar")); In the above code snippet, country_mdlist is a multidimensional associative array. It contains k e y i n d i c e s s u c h a s U S A , E n g l a n d , A u s t r a l i a , a n d N e v a E a c h a r r a y e l e m e n t of a multidimensional array includes another set of array within it that contains key indices such as Capital and Currency.

Page 158 of 274

V 1.0 Cc 2004 Aptech Limited

Web Scripting with PH"'

_-sssion 13

(A_PYTCM woRLowIoE
Working with Arrays

- : view the currency of England, enter the following code:

`o $country--mdlist["England"]["Currency"];

We can also create a multidimensional indexed array or a combination of associative and indexed array. Suppose we want to create an array that stores commission details of all the employees of an organization earned during the last six months, we can use a two-dimensional array. The first level of the array will store the names of the employees and the second level of array will store the commission of the employee earned during the last six months. To create the array that stores the employee commission details, enter the following code: e-moloyee_det = array( "Joe Brown" => array( 1 "$100", 2 "$150", 3 "$100", 4 "$160", 5 "$250", 6 -$148-), "T odd Mar tin" => array(
1
z

2 3 4 5 6

=> => => => => =>

"$180", ) "$195", "$200", ; "$130", "$280", " $ 21.8 "

In the above code, we have used both associative and indexed indices to create a multi-dimensional array. To view the amount of commission earned by Todd Martin during the fifth month, enter the following code: echo $employee_detf"Todd Martiri")[5]; The result of the above code will be $280.

.13.5 Array-related ~Tun.dtion.s.


PHP provides us with a number of functions that enable us to manipulate the arrays. We can perform a number of tasks with these functions, such as change the order of the element values, or the key indices and swap the element values between key indices.

Scripting with PHP

(APrecm

Session 13

WOR LDWIDE

Working with Arrays 13.5.1 sort ()

Function
function arranges the

PHP enables us to sort an array based on the element value. The sort element values into an alphabetical order. The syntax for the sort sort(ArrayName) For example, to sort the department array, enter the following code: sort($department); After using the sort ( ) function, the order of the element values will be: 0 1 2 3 Finance HR Purchase Sales function is:

Note the order of the element values have changed and not the order of the index values.

13.6.2 rsort ()

Function

The rsort ( ) function is similar to the sort ( ) function- The only difference between the two is that instead of sorting in ascending alphabetical order the rsort function sorts the element values in the descending alphabetical order. The syntax for the rsort ( ) function is: roost (ArrayName) For example, to sort the department array in the descending alphabetical order, enter the following code: rsort($department); After using the rsort. ) function, the order of the element values will be: 0 1 2 3 Sales Purchase HR Finance

Page 160 of 274 V 1.0 2004 Aptech Limited

Web Scripting with PHF

Note the order of the element values have changed and not the order of the index values.

~PTEC'/SiWORLDWID

Session 13
Working with Arrays

13.5.3 arsort 0function


The arsort and arsort arrays. function is similar to the rsortfunction. The only difference between rsort ( ) function is that the arsort function can sort both associative and indexed

The syntax for the arsort arsort(ArrayName) For example, to apply arsort arsort($department);

function is:

on the array, country, use the following code snippet:

The above code snippet instructs PHP to modify the array, as shown in the following output. 1 3 2 0 Sales Purchase HR Finance

13.5.4 Other Array-related


Apart from the above functions that enable us to sort arrays, PHP provides some other functions. These functions enable us to manipulate arrays. Table 13.1 lists some other functions that are related to arrays:

Table 13.1 : Other Functions Related to Arrays

Et.i117FECH

Session 13

LOWtOE

Working with Arrays


Some of the examples of the array functions are: To flip the element values to the index values and the index values to the element values of the department array, enter the following code:
$dept = array_flip($departmenU);

After using the array_f lip () function, the department array will be as follows:
F inance 0 Sales 1 HR 3 Purchase 3

To reverse the order of elements of the department array, enter the following code:
$dept 0 1 2 3 array_reverse($department);

After using the a r r a y r e v e r s e (


Purchase HR Sales Finance

function, the department array will be as follows:

To view all the key values of the department array, enter the following code:
array_keys($department);

After using the array_keys () function, the output will be as follows: 0

I
2 3

F unctio n Name e n o t p i r c s D

count

nue n Iinb er dm ta c rma a o sy t f in ee s l h sizeof To remove an element value from the department array, enter the following code: Idaseu br nitt nme ce h array_pop ($departizient) ; olmnaay eautif fe eti nr . cnsh e s aW es n ) ( d a e o t c n u Kmem )plnm (eeebe o lf a c aov a vlt s tren uul n sc u ta ius hy f rn e Ia r .s o sm ch m After using the array-pop ()function, the department array will be as follows: array 0 Finance _flip 1 Sales Cneh ovre s t 2 HR emnaeidxaenidxae e vut ua n ut l et l snevl s d evl s o u a v n m l e o array To add an element value to the department array, enter the following code: _intersec array_push($deparUrient, "Marketing"); t Ietsnrrse diadtn n et f uh e cm oemtaemnaruo o mn ev a ogop e u l nl g f s y r a After using the arraypush ( ) function, the department array will be as follows: () 0 Finance D p s ir y a l h t k e n d c o f 1 Sales array 2 11 R reverse 3 Purchase Re vt een te sl rf s h o d r h tm y a 4 Marketing () V 1.0 2004 Aptech Limited Scripting with PHP Re m etr asa sef no rv ut to dn l r i fy h m () I hterir deaos etnkty nrgie f iex i on t ond w ya s vn array push V 1.0 2004 Aptech Limited Page 162 of 274 Ase omtted dnr rl eho do e nnf ome s o Web Scripting with PH: ar n a y
o o o o

(A P rECH

Session 13

\1WORLDWID E

s y a A h t w g n i k r o W

A variable can store only one value at a time. An array is a variable that can store a set of values of the same data type. Each value in an array is termed as an element. All the elements are referenced by a common name. An array index is used to access an element. An index can be a number or a string. If the index is a string, the array is an associative array. If the index is a number, the array is an indexed array. We can combine the element values of two or more arrays. This process is called as merging arrays. In a single-dimensional array, the element includes only one level of key value pairs. In the multidimensional array, each element is an array. Each element requires an array name and multiple set of indices. There are two types of arrays: Indexed array Associative array

An indexed array is an array where the index type is integer. An associative array is an array where the index type is string. In associative arrays, the index value must be specified within double quotes. We can combine the element values of two or more arrays. This process is called as merging arrays. Multidimensional arrays are arrays that store another array within it. In a single-dimensional array, the element includes only one level of key value pairs. In the multidimensional array, each element is an array. Each element requires an array name and multiple set of indices.

m*_t Scripting with PHP

V 1.0

~PTE'CH

Session 13

WORLDWID E

Working with Arrays

Some of the array related functions are:

sort ( )

arsort rsort ksort

The sort() function arranges the element values into an alphabetical order. The rsort ( ) function sorts the element values in the descending alphabetical order. The arsort function can sort both associative and indexed arrays.

Some of the other array-related function are:


Page 164 of 274 V 1.0 Oc 2004 Aptech Limited Web Scripting with PHP

count()

array_count_values() array flipo array_intersect() array _-keyso array pop( array push
o

.:;Sion 13
Working with Arrays

;1~11

Use the _________________________ to specify a value to a specific element at once.

a. b.
C.

array

f u n c t i o n

array identifier count() function sort function


I

d.

Use the __________________ to assign values for all the elements in an array at once.

a. c.
C.

arrayO function array identifier count() function sort() function

d.

To combine the element values of the two arrays, we use _______________________ function.

a. b.
C.

array_merge() merge array (


function arranges the element values into an alphabetic ascending
o)

arraycombine( )

d The order

a. b.
C.

arsorz() ksort sort () asort


function keeps a count of the occurrences of same element values

d.

in an array. aarraycount( b.
C.

count() count values


o)

d.

array_countvalueso

4*b Scripting with PHP

V 1.0 2004 Aptech Limited

Page 13 of 274

Elf:PFECII

Session 13

WORLDWIDE

Working with Arrays

function identifies the common element value among a specified group of array.

a. b.
C.
d.

array --intersecto arraymerge{ arraygroup( arraycountvalues(

7.

a. b.
C.
d.

array_intersect_keys() array_keyso array_key_exist() array_count:_va1uesO


t u l . v y k h a s e r o i c n f

Page 14 of 274

Objectives
At the end of this session, you will be able to:

>

Create and use arrays Merge arrays Use single and multidimensional arrays Use array- related functions

The steps given in the session are detailed, comprehensive and carefully thought through. This has been done so that the learning objectives are m6t and the understanding of the tool is complete. Please follow the steps carefully. Part I - For the first 1.5 Hours:

14.,JIJI &I

ftift-fe arrayo %pp9tion

We can create an array and set the initial values of array elements using the array() function. The arrayo function uses key value pairs separated by a comma to create an array. The number of key value pairs in the arrayo function determines the number of elements in an array. Using arrayo function, we can create both associative and indexed arrays.

We will create an array that contains names of various programming languages such as, VB,
Java, Perl, PHP, VC++, C++, .NET, and Delphi_ 1. 2. Open the gedit text editor. To create an array named lang, enter the following code: <?php $ 1 2 3 4 5 6 lang = array
=> - "VB",

=> "Java", => "Perl", => "PHP",


=> I'Vc++,

=> ".NET",

7 => "Delphi")

,Veb Scripting with PHP

V 1.0 2004 Aptech Limited

Page 167 of 274

A P - T IE C A - i l l -

W Z ALLD W 4-0-4E

Session 14
Working with Arrays ,6w It'd M , 6 tf

-he'rArM 00-Mb store it in -a - varnts

in

The each () function retrieves each key value pair of an array and stores the result in the $row variable. The for statement will.continue to retrieve values of the array till it reaches the last key

value pair. After entering the code, the PHP file appears as shown in Figure 14.1.

ew

Open
0 n~

Save Nnt Undo Redo

Cut , C6py P

Paste

R#W'Replace

Untitled 1* x

<?php Slang = array( 1 => "VB", 2 => "Java", 3 => "Perl", 4 => "PHP", S => "VC++", 6 => "NET", 7 => "Delphi"); Selnits = count($lang); for ($i=O; $i<$elmts; $i++) f L $row=each($1ang); echo "$row[key] $row[value] echo "<br>";

Ln 2-3, Col. 3 .. . ..... ...

INS

Figure 14.1 : Using the array() Function

Page 16 of 274

V 1.0 Cc 2004 Aptech Limited

Web Scripting with PHP

Sessuon 14

APTECH

waa~ow1ae

W o r k i n g w i th A r r ay s P under 6. Open the Mozilla Web browser. var/

Figure 14.2 : Viewing Contents of an Array

142 Using
We can initialize value of a specific element in an array using the array identifier. The array identifier also helps us to create both associative and indexed arrays. We can also create the lang array using the array identifier.

Scripting with PHP

V 1.0 2004 Aptech Limited

ds'

ViPage 169 of 274

Session 14

_ __________________________________________
Working with Arrays

To calculate the total number of elements in the array and store it in a variable,. enter the following code:
4e2mts
,

count ($1ang),;

B isplay' all: he values enter the following code;


for ($item=O;

fangiarray.,along.~ h th-jr.respecti h e . . , v e d e x , v a l u e s ,

After entering the code, the PHP file appears as shown in Figure 14.3.
Untitled! ~ _ t q gedit j f q (modified) ~ -

<?php $lang[] "U"; Slang[] "Java"; $1 ancy"Pert", Slang[] PHP Slang[] " VC++ Slang[] "'.NET" Slang[] "Delphi"; $elints = count($lang); for ($i=0; $i<$elmts; $i++) $ro;v=each($lang); echo "$row[key] $row[value] echo "<br>";

Ln 20, Col. 3

INS

Figure 14.3 : Using the Array Identifier 5. Save the file as mylang.php under the Open the Mozilla Web browser.
/var/www/html

directory.

Session 14

wonLowIoe Crte

Working with Arrays

Type http: //localhost/mylang.php in the address bar and press Enter. The PHP. script is executed and all the element values of the array along with their respective index values are displayed, as shown in:. Figure 14.4.

File Edit View Go Bookmarks Tools Window Help Back OVB I Java 2 Per] 3 PHP 4 VC++ 5 .NET 6 Delphi Forward Reload Stop http:/Aocalhostfmylanlv LASearchl Print

!~j Home I *Bookmarks Red Hat Network 6Support (Shop eft Products Training

offilmawaffigm 1-*-Idl Figure 14.4 Viewing Array Contents

Note the index value starts from 0. PHP automatically assigns the index value from zero when
we do not specify the index value.

14.3 Merging Arrays


PHP enables us to merge the element values of two or more arrays. We can merge indexed arrays and associative arrays. Suppose we have two arrays, such as $serveros and $applicationOS that contain names of the operating systems. To combine the element values of these two arrays into one, we must use the array_merge function. Open the gedit text editor.

To: create . arrays named $serveio PHP code:


?php

a nnna ter the following ti

s ,:and
,

$applic

"Windows 2003");

=> "Windows. NT", - 1 => . "Windows 2000"..


=> "Windows
9811,

$appiication0S=arraY(1, => "Windows 95", "Windows ME");

=>

zz Scripting

with PHP

Sess~

n 14

(,-4PY-,EC,M

LMW I'DE

Working with Arrays


Web Scripting with PHP

logo*##94Wray, enter the

zz Scripting

with PHP

Working with Arrays


Page 173 of 274

echo, -$rec [keyl X echo -<br>-;

$rec[valuel

Save -.'the'. fi I ` 'op~ : i e- as ~' pt.pqj&~ der -the

recto

ht n on
sN;

Back

jWoad Stop

http./Aociilhostjop -Ij I&*,

Search

Home Server Operating systems


0 Windows NT

51i[440~ toduels~~

1 Windows 2000 2 Windows 2003 Application Operating systems 1 Windows 95 2 Windows 98 3 Windows ME Merged array ofOperatin g Systems Windows NT 1 Windows 2000 2 Windows 200 3 Windows 95 4 Windows 98 5 Windows ME
Q

Figure 14.5 : Content of the individual and Merged Arrays

1 4 . 4 U in, g Multidimen

nsional Array

In the Multidimensional array, one array is stored within another. Each element in the multidimensional array is an array. Each element is referenced by an array name and multiple sets of indices. For example, in case of the two-dimensional array, each element requires array name and two set of indices instead of one.Web

Scripting with PHP

V 1.21 Cc) 2004 Aptech Limited

WOWk, S e s s i o n 1 4

A P rECITI

D W I'D -9

I-

Session 14

APTECK
WO, R'L'U W1 D E

Working with Arrays


For example, to create and display a two-dimensional array to store the information such as the name, address, email address, and grade of four students: OP
fie gedit '1

text editor.

Enter the following code to -create:

".Luce -

'GrAc.

'%ff6i 1 0:
"Grade-; "Gender"
=>

lace .'d 0

"Female"),

004 => array( "Name" => "Jack Thompson", "Email" => "jack.t@flaymore.edu", "Grade" => "B+ "Gender" => "Male"),

Note that the $student array is a multi-dimensional array. 001, 002, 003, and 004 are the index values of the elements which in turn are arrays that includes student information, such as the name, email address, grade and gender.

3.

display 11 n ormation stored in the $student array.-,, enter the .:code as To ~!gpi theAid;
,

shown in Figure 14.6.

Page 22 of 274

V 1.0 2004 Aptech Limited

Web Scripting with PHP

Session 14

W0 A

A Pvo W I DIE Y"ECH


1 I

Working with Arrays

VElie Edit I untitled


New Open Urvided 1

View

Search

Tools

p o c u m e n t s Eelp

ID t: [q 9
Save Print Undo Redo Cut Copy Paste

Find Replace

$totalelint = count($student); for($i=0; Si<Stota1_e1mt; $i++)

$row=each($student); $val= $row[key]; echo "$val echo "<br>"; Svalcount=count($student[Sval]); for ($t=0; $t<$valcount; $t++) $rec=each($student[$va1]); echo "Srec[key] Srec[valuej"; echo "<br>"; echo "<br>";

1'f.FAM3,CoIAT

Figure 14.6 - Displaying Contents of the Multi-dimensional Array

mozilla

;x

Sle Edit Ylew Qo Rookmarks Iods Window

4 G4

S~;-:~,
Formel

Back

Reload Stop -

31

! , & hI,,:j0..host/swdemDN.php *_Search Print

_B

&

!,j Home;

X} Bookmarks %#Red Hat Network .-Support EIShop OProducts EA paining

001 : -NanK: Chris Edwards Email : chris.eO'na% awre.edU Grade : A Gender - Male (X)2 : Nmw Marlin. Lake Email. martina.K&Ilaynxire.edu Grade A+ Gender : Female 003 : Name Luce Grace Email lucc.g. eflaviwre.edu Grade B Gender : Female 004 Nam : Jack Thompson Grade : 13+ Gender: Male
-j-_ L.1 ~~ LA)

(V I Done

1 .1 ............

Figure 14.7 : Viewing Contents of the Multi-dimensional Array

Scripting with PHP

V 1.23 Cc) 2004 Aptech Limited

Session 14

W0::RLDWVD:E

Working with Arrays

.1 4.5-:'Sorting PHP provides us with various functions, such as s o r t enables us to sort the element values of an-array.

rsort

and arsort

that

We will use the various functions to sort the elements of the Slang array.

echo echo

for($i=0;

$i<$total_elmt;.

$rec = each ($lang)echo "$rec (key] 6 c [value] echo "<br>"; echo "<br>"; To sort. the $immcr array inthe w alphabetical .
777
P H P s c r i p t :

"qr,,.:.~enter, hefoIIO.wiing~, code ~-iin the

sort
($1axit'r)

The PHP file appears, as shown in Figure 14.8.

Page 24 of 274

V 1.0 2004 Aptech Limited

Web Scripting with PHP

Session 14

(APrEcm 0 R'L D W I VE

fn rx Elie Edit View Search gods Documents Help

New Open Untitled I* x <?php

Save Print Undo Redo Cut Copy Paste Find :Replace

Slang = array( 1 => "VB", 2 => "Java", 3 => "PHP", 4 => "Delphi",); $totalelmt = count($lang); echo "Original array"; echo "<br>"; for ($i=0; $i<Stotalelmt; $i++) $rec = each($lang); echo "$rec[key] $rec[value] echo "<br>";

I
echo "<br>"; sort($1ang);j
~
"

M A

~~IMINJ'/

Figure 14.8 : Sorting the Array Alphabetically 5. To display all the: .- elements of. --,`tKfIIani'g following code:
4rrayi, e prItIh, th ',Viriray en erW, enter

the

for($i=0; $i<$tota1e1mt; $i++) $rec = each($lang); echo "$rec (key] $rec [value]"; echo "<br>";

6. 7. 8.

Save the file as modLang.php under the jv6tjww/htxnI dIfW ry. Open the Mozilla Web browser. Type http://localhost/mbdLang.php in the address bar and press Enter. All the elements of the lang array before and after sorting are displayed, as shown in Figure 14.9.

Scripting with IHP

Session 14

rAPywcm
11WOR VDW11-0Z

Working with Arrays

'i Ble Edit Mew


I -

Go pockmarks Tools Vindow Help

It F

:..A.ack Forward
j Home 1(

h
-

1v

Reload Stop

jp-Search

C-4 , Print

Marks* Red Hat Network 6S.ppwt (gs hop CdPr ducts (:lTraining

Original array 1 VB 2 Java 3 PHP 4 Delphi Modified array 0 Delphi 1 Java 2 PHI? 3VB

Figure 14.9 :

utput of the sort ( Function

Tqoj.ried) - gedit
R i i Edit
I ew

Bids

olk

U T41

-f-

Save Open

e Print Undo' Redo Cut Copy Paste Find Replace -- ------- --

7j' modLang.php* x
echo "<br>

echo "<br>"; rsort($1ang);1 $total_elmt = count($lang); echo "Modified array"; echo "<br>"; for ($i=0; $i<$total_elmt; $i++) $rec = each($lang); echo "$rec[key] $rec[value] echo "<br>"; I

Ln 20, Col.

INS

~Z I

Figure 14.10 : Sorting the Array in the Descending Order

Page 26 of 274

V 1.0 @ 2004 Aptech Limited

Web Scripting ,: :- =

Session 14

(A'Prrcm WORLDWIDE
Working with Arrays

11.

Save the modLang.php file under the /var/www/htmi directory.

12. Open the Mozilla Web browser. pe http://localhois.tlmodLan bp and press Enter T- e .,b inal
Rip

,-the

s000

ar

4 i , Zg r a y 4 . . . ~

-sh6

ppe p

0~gure

-WRIP'M

Figure 14.11 : Output of the roort () Function

Web Scripting with PHP

V 1.0 0 2004 Aptech Limited

Page 179 of 274 E l l e E d i t V i e w G o B o o k m ar k s T o o l s w i n d o w H el p

(APT.PCH

Session 14

7" LOWIDE

s y a A h t w g n i k r o W Part II - For the next half an hour: Venture Capital Inc. is a trading company that deals in automobile parts. It has branches in countries, such as USA, Australia, Russia, Japan, Africa, China, and New Zealand. 13. Create an indexed array that includes the names of the seven countries where the branches of Venture Capital Inc. are located using the array identifier. Also, display the contents of the indexed array. 14. Sort the contents of the indexed array in the alphabetical order. 15. Sort the contents of the associative array in the descending alphabetical order. 16. Create and display the contents of a multi-dimensional array that contains the following information:

F L E S U O I Y R T I

Page 28 of 274

V 1.0 Ccj 2004 Aptech Limited

Web Scripting with PHP

Objectives
At the end of this session, you will be able to:
Discuss about Database APIs Connect to the database Use data access functions );11 Perform SQL queries using PHP Build HTML tables using SQL queries

Introduction
A database is used to store the data. Many RDBMS such as Access, Oracle, and MySQL are available. On the Linux operating system, MySQL is mostly preferred because it is open source software. It is easy to use and can run on any platform. In this session, we will learn how to connect to a database through PHP. We will also learn how to use the data access functions and perform SQL queries using PHP. In addition, we will learn to display the records of the table in HTML tables using SQL queries.

15.1 Database APIs -)


Database APIs allows developers to write applications that are movable or easily accessible between the database products. API stands for Application Program Interface. The common database APIs is Native-Interface, ODBC, JDBC, and CORBA. ODBC stands for Open Database Connectivity. It is a method for accessing data from the database using any application. PHP supports MySQL database for accessing data from the database server MySQL is a RDBMS and a portable SQL server. PHP enables us to work with the database using MySQL as it is a database server.

15.2 Connecting to a Database


A database is connected to establish the database properties to the Web sites. It is done with the help of a data source name. A data source name is normally set up by uploading the database to the account and place it in the database directory location. In order to access the database, we need to perform few steps. The steps for connecting to a database are: Open the database connection Work with the database Close the database connection
V 1.0 Cc 2004 Aptech Limited Page 181 of 274

Web Scripting with PHP

6-4py-'Ecm S es s i on 1 5
W"LDW D

Handling Databases with PHP

15.2.1 Connecting to the MySQL Server


PHP and MySQL get installed while installing Linux operating system. PHP supports MySQL database for accessing data from the database server. We connect MySQL server to PHP with the help of the mysqlconnec t ( ) function. This function takes three arguments, the name of the machine on which the database is running, the database username, and the database user password. The syntax to connect to the MySQL server is: $link_id = mysqlconnect("hostname","username","password"); Where, host name Specifies the name of the server on which the database is running. The
default lotation of MySQL server is localhost. user name Specifies the user name-This is an optional argument.. This value can be

entered later in the codes

password Specifies the user password. This is an optional argument. This value can be entered later in the codes
link_id Stores the return value of the connection. This variable is used to check

whether the connection is established or not. For example, to connect to the MySQL server: $linkid = mysql_connect("localhostl,"rooL","abc123"); Here, the user is considered as root. It has localhost as the server name and abc123 is password.
r-:z

15.2.2 Working .with the


Before we start to work with the database, we have to establish a connection with the MySCserver. PHP provides us with the following functions to work with the MySQL database: mysq1_1ist dbs() Displays all the databases available on the server. The syntax for the mysql_l-ist_dbs function is: niysq1_1istdbs($1ink_id);
Where, link_id specifies the return value of the connection.

Session 15

(APr,ECJV
WORLDWIDE WO

Handling Databases with PHP


For example, to display all the databases present on the server, enter the following code:
<?php

$server $username = "root"; $password = ""; $connectmysql = mysqlconnect($server, $username, $password); $db_list = mysqllist_dbs($connectmysql); echo "Connected to the Server"; echo $db_list;

The above codes show the connection to MySQL server. The hostname or the server name and the password are left blank. Here, the root user is not assigned to any specific host. As well as it does not have any password. The username is assigned as root. In the above code, connection is established with the MySQL server. All the names of the databases on the server are stored in the $dblist variable. mysq1_se1ect_dbO Sets the specified database as the current database. The syntax for the mysqlselect_db() function is:

mysqlselectdb("database_name", $link_id);
Where,

database_name Specifies the database name linkid Specifies the return value of the connection

For example, to connect to the MySQL database:


<?php

$server $username $password

"root"; mysql_connect($server, $username, $password);


I

$connect m sql Y

$mysqldb = mysqlselectdb("mysql", $connectmysql); if(!$inysql_db) d i e C onnec t i on failed"); } else

Session 15
echo "Current Database is selected";

Oft-LDWIE

Handling Databases with PHP

In the above code, we have set the mysql database on the server as the current database. If the database is present on the server, the message with the echo command is displayed. If the connection fails with the server, the message with the die () function is displayed. A die ( ) function is equivalent to the exit function. This function terminates the current program>
mysq1_1ist_tab1es () - Displays a list of all the tables available in the specified database.

The syntax for the mysqllisttables ( ) function is: mysql_list_tables("databasename", $link_id); Where, database name Specifies the database name linkid Specifies the return value of the connection For example, to list all the tables of the mysql database: <?php $server $username = "root"; $password = ""; $connectmysql = mysql_connect($server, $username, $password); $tab_list = mysqllisttables("inysql", $connectmysql); it(!$tablist) echo "Database does not contains tables"; exit; else echo "$tab_list";

In the above code, connection is established with the server. All the tables available in the mysq.l database are listed and stored in the $tab list variable. If the database contains the tables, they will be displayed. If the table does not exist in the database, the message with the echo command is displayed and the execution will come to an end. mysqlnum_rows () Displays the number of rows present in the specified table.

Page 32 of 274

V 1.0 Ccj 2004 Aptech Limited

Web Scripting with PHP

Session 15

('APr,FCM
11~

w" LOWIDE

Handling Databases with PHP The syntax for the mysalnumrows ( )function is-, mysqlnumrows("tablename"); Where, table_name specifies the name of the table for displaying the number of rows present in it. For example, to list the number of rows of the specified table: <?php $server $username $password
.11 ;

"root";

$connectmysql = mysal_connect($server, $username, $password); $row_num = mysqlnumrows("usercontact"); if(!$row_num) { echo "Table does not contains any data"; exit; else echo "Row number.

In the above code, the numbers of rows from the table are listed. If there are no rows in the table, the message specified with the echo command is displayed. If the rows are present in the table, the total numbers of rows are displayed.

15.2.3 Closing4he Connection


The connection with MySQL server can be closed with the help of the mv,, ;ql close The syntax for the mysql__close() function is: mysqlclose($link_id); Where, link_i d specifies the return value of the connection Fo r e x a m p l e , t o a c c e s s t h e M y S Q L d a t a b a s e :
V 1 . 0 C c
,

function.

2 0 0 4

A p t e c h

L i m i t e d

Page 185 of 274

<?php $se.rver

Web Scripting with PHP

(4,-;]7PECif

Session 15

L D W A O-E

Handling Databases with P HP echo "Current Database is selected";

In the above code, we have set the mysql database on the server as the current database. If the database is present on the server, the message with the echo command is displayed. If the connection fails with the server, the message with the die () function is displayed. A die () function is equivalent to the exit function. This function terminates the current program. mysq1_1ist_tab1es () - Displays a list of all the tables available in the specified database. The syntax for the mysqllisttables() function is:

mysql_list_tables("databasename", $link_id);
Where,

databasename Specifies the database name linkid Specifies the return value of the connection
For example, to list all the tables of the mysql database:

<?php $server $username = "root"; $password = "" $connect_mysql = mysql_connect($server, $username, $password); $tab_list = mysql_list_tables("mysql", $connect_mysql); if(!$tab_list) echo "Database does not contains tables"; exit; } else echo "$tab list";

In the above code, connection is established with the server. All the tables available in the mysql database are listed and stored in the $ , c.ab list variable. If the database contains the tables, they will be displayed. If the table does not exist in the database, the message with the echo command is displayed and the execution will come to an end.
mysq1_num_rows () Displays the number of rows present. in the specified table.

Web Scripting with PHP

(APY-ECM

Session 15

WORLDWORLDWIDE

Hnl g abss i P P ad Dt aewh H i a t n The syntax for the rnysalnumrows ( )function is: mysqlnumrows("tablenaiiie"); Where, table name specifies the name of the table for displaying the number of rows present in it. For example, to list the number of rows of the specified table:
<?php

$server $username $password

"rooL";
11 It ;

$connect_mysql = mysql_connect($server, $username, $password); $row_num = mysql_numrows("usercontact"); if(!$row_num) echo "Table does not contains any data"; exit; else echo "Row number I $row_num";

In the above code, the numbers of rows from the table are listed. If there are no rows in the table, the message specified with the echo command is displayed. If the rows are present in the table, the total numbers of rows are displayed.

15.2.3 Closing the Connection


The connection with MySQL server can be closed with the help of the mysqlclose () function. The syntax for the mysql close mysqlclose($link_id); Where, linkid specifies the return value of the connection For example, to access the MySQL database:
<?php

function is:

$server

," 'eb Scripting with PHP


,

ARTECAW

Session 15

WO R L D W I D E

Handling Databases with PHP


$username = "root"; $password = ""; $connect_mysql $tab_list myscil-connect($server, $username, $password); rctysql_list_tables("mysql", $connect-mysql);

if(!$tab_list) f echo "Database does not contains any table"; exit; else $row-nuin = roysql_num_rows($tab_list); I if(!$row_num) echo "Table does not contains any data"; exit; I else echo $row_num;

mysql_close($connect_mYsql); echo "Connection is closed";

15.3: Data - Access


PHP p r ovi des u s with th e f ol lo wing f un ct ion s f o r ac ces sing d at a f ro m t h e d atab as e:
m y s q 1 q u e r y 0 - E x e c u t e s M y S Q L q u e r y f o r re t r i e v i n g d a t a f ro m t a b l e s . T h i s f u n c t i o n

s end s q u erie s t o the a ctiv e d at aba se . T h e My SQL co m mand s su ch as SE L EC T , S H C - . , - , EXPLAIN, and DESCRIBE works with this function The syntax fo r the irvsql_query( )function is: inysal_query(querv, link-id); Where,
Page 36 of 274

query Specifies the MySQL query. 1 1, inkid Specifies the return value of the connection
F-

Session 15

('APTECM Handling Databases with PHP

The queries must be enclosed within the double quotes and must not end with a semicolon (;) symbol. The link-id. is optional. > mysq1_fetch_rowO- Fetches the resultant rows as an array. Each row of the table is placed in an array. These rows are accessed with the index numbers starting from 0. The syntax for the mysql_fetch-rowo function is: mysql_fetch_row("table_name"); Where, result specifies the table argument of the () function.

mY9q1_fetch_arrayO- Fetches the rows of the table and saves it as an array. It is an extended version of () function. The syntax for the mysql_fetch-array ()function is: mysql-fetch-array("table-name"); Where, table namespecifies the name of the selected table. myogl - fetch - fieldo- Displays the details of the column, such as the column name, table name, and maximum length of the column, column constraints, and column type. The syntax for the mysql-fetch-field( ()function is: mysql-fetch-field("table_name"); Where, table namespecifies the table name. mysq1_fie1d_1enO- Displays the length of the specified field The syntax for the mysql-field-leri ()function is: n)ysql_field_].eri("table_name", "field-name."); Where, table-name - Specifies the table name field name - Specifies the field name for which the length needs to be displayed mysq1_num fields O- Displays the number of fields in the specified table. The syntax for the mysql_num-f fields ()function is: rr,ysql_num_1"ields (" table-na.me") Where, table_name specifies the table name.
V 1.0 Oc 2004 Aptech Limited Page 187 of 274

-'.ab

Scripting with PHP

Session 15
Handling Databases with PHF To display the records of the table from the USER database, enter the following code:

<?3Dhp $server $usernam "root"; e $ $connectmysql = mysql_connect($server, $username, $password);


1 11 ; 11 if ;

if($connectmysql) f echo 'Connection established"; I else die("Unable to connect"); $mysqldb = mysqlselectdb(-USER"); if($mysqldb) echo "Connected to the database"; I else die("Unable to connect to the database");
I

$sqlquery = mysql.-query ("SELECT

FROM usercontact;");

while($row = mysqlfetcharray($sqlquerv)) echo "<BR><BR>$row[user_idj"; echo "&nbsp;$row[user_namel"; echo "&nbsp;$row[user_einail__id1"I if(mysql_num_rows($sqlquery)<1) echo "No result";

Page 38 of 274

V 1.0 C 2004 Aptech Limited

Web Scripting wi-. _-= -

C4-PTIECII

Session 15

R LOM IV 6
1

Handling Databases with PHP

15.4 -.Executing SQL Queries in PHP


Before executing the SOL queries in PHP, we must establish the database connection. Create a table named USERCONTACT in the USER database with the following fields: Field Name Data Type C i a r t s n o

Table 15.1 : user contactTable To create a table using the SOL commands in PHP: 1. 2. Open the gedit text editor. Enter the following code:

USER ID INT N NLRA O U PMY T L IR K E Y USERNAME CHAR( 25) N L U T O USEREMAIL ID C ) 5 2 ( R A H

<?php $server $username $password

U";

"root";

$connectmysql = mysqlconnect($server, $username, $password); if($connect_inysql) echo "Connection established"; else die("Unable to connect");

$mysql_db = MYsql_select_db(,'USER"); if($mysqldb) echo "Connected to the database"; el se die("Unable to connect to.the database");

39

.9b Scripting with PHP

V 1.0 Oc, 2004 Aptech Limited

Session 15

Wamllulb?. lam

Handling Databases with PHP


$sqltable = PR1M:
L!

"CREATE TABLE USER CONTACT(".-USERID INT NOT NULL .RY KEY,-."USERNAME CHAR(25) NOT `d LL, "-"USEREYLAILID CHAR(25)".

if(jnysq1query($sqltable)) echo "Table is created"; } else die(" Unable to cr e a te a t a b le " );

In the above code, the USER CONTACT table is created in the USER database. The table is created using the CREATE command of SQL. 3. 4. 5. Save the file as mysqltable.php under the, /var/www/html directory. Open the Mozilla Web browser. Type http: // localhost/mysql table. php in the address bar and press the Enter key. The output appears, as shown in Figure 15.1.

0 a

File Edit View Go Bookmarks Tools Window Help Back Forward Reload Stop
4*f

http://loci

Search
I

Print

!jHorne 'jBookmarks

S upport "' Red Hat Network (:

~ ;' Shop ~C Products QTrainl j

Coollc~noll cstahfishcd conlicc(cd to the database Table is created

Done

Figure 15.1 : Creating a Table We need to insert records in the table once we have created the table. PHP enables us to store the form data in the database. The records in the table are inserted with the HTML method.

Page 40 of 274

V 1.0 --P 2004 Aptcch Limited

Wet.) Scripting with PHP

Ei-PTE-CDA 0 R V WWA
Handling Databases with PHP
To insert records in the USER CONTACTtable:
< ?php

$server Susername = "root"; $p a ss wo r d = $connectmysql = mysq1connect(Sserver, $username, $password); if($connect_mysql) echo "Connection established"; else I
r

die("Unable to connect"); I $db = "user"; $mysqldb = mysql_select_db($db); if($mysql_db) echo "<BR><BR>Connected to the database"; else die("Unable to connect to the database"); I "INSERT INTO user contac $S UJ_ 4 n se rt ( u s e r i d , u s e r n a me , u s e r e m a i - l i d) V A I - I I JE S ( 10 1 , ' Jo h n ' , ' j o l i r i @ m a i i . c o m ' Sresult = mysqlcruEry(';sql--irisei-t) ;
4 1

ult)

{ f($res echo "<BR><BR>THE RECORDS ARE INSERTED"; else e c h o " R E C O R D S C O U L D N O T B E I N S E R T E D I N TH E TA B L E " ; mysql_erroro;

In the above code, records are inserted in the table using the 1 N S E R T command. If there exist any error, the m sqi erl or() function returns the error message that is sent by the MySQL server.
y

V 1.0 K ) 2 004 Ap te c h Limi ted

Page 191 of 274

.'.-41b Scripting with PHP

AprITCA41

Session 15
Handling Databases with PHP
Using the SELIECT command, we can access data from the tables. For example, to display all the records from the user contact table: <?php

$server $username = "root"; $password = ""; $connectmysql = mysql_connect($server, $username, $password); if: ($connectmysal.) echo "Connection established"; } else die("Unable to connect"); I $db = "user"; $mysqldb = mysql_select_db($db); if($mysqldb) { echo "Connected to the database"; else die("Unable to connect to the database"); $sql_disp=("SEIIECT FROM usercontact;");

$result=mysql_query($sql_disp,); while($row = mysqi_fetcharray($rcsult)) f echo "<BR><BR>$row(userid1"; echo "&nbsp;$row[usernamej"; echo "&nbsp;$row[user-_emai1--id1";

if (Mvsqlnumrows ($sqlq-,,](-.r-y) l) I echo "No result"; I

Page 42 of 274

V 1.0 (c) 2004 Aptech Limited

Web Scripting with PHP

session 15

A4

( .A;~PrFcm
WO-K L; WW 10 E

Hnl g aaaewh H a d Dtbss i P P i n t In the above code, the records such as USERID, USERNAME, and USEREMAILID from the user contacttable are displayed. The DELETE and UPDATE commands helps to modify the contents of the table. For example, to delete a record from the table: <?php

$server $username = "root"; $password = ""; $connectmysql = mysqlconnect($server, $username, $password); Jf($connectmysql) echo "Connection established"; else die("Unable to connect");
I

$mysqldb if($mysal_db)

mysql_selectdb("USER");

ecl-)o "Connected to the database"; else die("Unable to connect 4-o the database"); $sq7 dolete= ("DELEETE FROM usercontact ',,,7.HERE user_id $resul-t=mysqlqiiery($sql._delete); if($result) echo "$result- RECORDS ARE DELETED"; } else echo "RECORDS NOT FOOND IN THE TABLE"; mvsql_erroro; '101

Page 43 of 274

V 1.0 (c) 2004 Aptech Limited

Web Scripting with PHP

Session 15

W *0 RALID W 1-10-6

Handling Databases with PHP After deleting the records from the table, check the table contents at the MySQL command prompt using the SELECT command. For example, to update a record in the table: <?iDhp $server $username $password

"root"; "";

$connect_mysql = mysql_connect($server, $username, $password); if($connect_mysql)


f

echo "Connection established"; else die("Unable to connect"); $mysql_db = mysqlselect_db("USER");if($mYsaldb) echo "Connected to the database";
I

else die("Unable to connect to the database"); I I


Y~sqi

update= ("UPDATE user contact SET username ='Jenniffer' WHERE userid ='101'");

$resulll=mysql_qLiery($sql_t2pd,ate); if($result) echo "RECORDS ARE UPDATED"; else echo "RECORDS COULD NOT BE UPDATED !N THE TABLE"; mysql _error() ;

After updating the records in the table, check the table contents at the MySQL command prompt by using the SELECT command.

Page 44 of 274

V 1.0 (c) 2004 Aptech Limited

Web Scripting with PHP

Session 15

64 P T E C H O RLDWIDE

Handling Databases with PHP

15.5 Building HTML Tables using SQL Queries


HTML supports the database application components for accessing the database. The contents of the SQL tables can be displayed on the Web browser by building an HTML table structure. The HTML table structure will display the contents of the table along with its field names. For example, to display all the records of the usercontact table using the HTML table structure:
<HTML>

<BODY> <?php $server $username = "root"; $password = "'; $connectmysql = mysql_connect($server, $username, $password); if($connectmysql) echo "Connection established"; $mysqldb = mysqlselectdb("USER"); if ($my-sql_djD) echo " <BR><BR >Connected to the datahase<BR><BR>"; echo "<TABLE BORDER BGCOLOR="WIIITE">"; echo <TR><T]I>USERI*Y)<'!'H><TH>US"--RNAME<Tll><TII>USEREMAI'LID </TH>"; e c h o " < D B Q U E R Y q > s e l e c t * f ro m u s er c ont a ct "; echo "<DBROW><TR><TD><? qJJSERID>-:::/TD><TD><? q.USERNAME></ TD><TD><? q.USEP--EM---"LLI])><./TD><iTR>"; echo "</DBQUERY>"; echo "<I/TR>"; echo "</TAI3LE>"; </BODY> </IITML>

The above code will display the records of the user contact table on the Web browser in the tabular format. The DBQUE:i? y and the DBI R low are the HTML tags. The DDQUERY tag executes records for the SQL query. The i)RRow tag is used for placing text in the row.

Page 195 of 274

Web Scripting with PHP

1.0 C(`

2004

Aptech Limited

Sess qn 15
o

EifprEchr

O WLOAV1404r.

HdDaiPP algastH n teh n w i b

Database APIs allows developers to write applications that are movable or between the database products. The common databases APIs are Native-Interface
,

easily accessible

ODBC, JDBC, and CORBA.

PHP is connected to MySQL using three arguments. The three arguments are the MySQL server host name, the MySQL u ser name, and the MySQL user password. The connection with e server is established with the help of mysq1_connect( ) function The b sic PHP functions those are used with respect to the database are

ysqllistdbso, mysqlselectdbo, mysq1_1ist_Uab1esO, num_rows()


The mysqlclose () function closes the connection with the MySQL server. The data access functions used in PHP are mysql_query () ,

() mysqlfetchrowo,mysqlfetchfieldo,mysql_fieldleno, mysq1numfieldso'

-77

--

Web Scripting with PHP

1.0 C(`

2004

Aptech Limited

Session 15

(-4-12TECH

0 UL W: O IO 3 0

Handling Databases with PHP

1.

The database server is connected to PHP with the help of the a. b.


C.

function.

mysq1.se1ectdbO mysgl_connect() connect_mysq1() function displays the total number of rows of the specified table. mysgl_fetch_array() mysgl_select_db() mysgl_list_tables()

2.

The a. b.
C. d.

mysqlnumrowso function displays the details of the columns of the table. mysqlfetchfieldo mysgl_fetch_row() mysal_fetch_array() mysgl_num_rows()

3. Th a. b.
C.
d.

4.

The _____________ function executes MySQL queries. a. b.


C.

Mysqi_Quer,y () mysgl_connect() mysalquery () connect-.mysq1.()

5.

Records can be inserted in the table using the

_________________________

command in PHP. a. b. C.
d.

INSERT UPDATE SELECT DELETE

Web Scripting with PHP

Handling Databases with PHP

Records can be modified in the table using the ___________ command in PHP.
a. b. C. DELETE INSERT SELECT UPDATE

d.

Page 48 of 274

V 1.0 2004 Aptech Limited

Web Scripting with --=

Obi ecflves
At the end of this session, you will be able to: Set a cookie > Retrieve a cookie in PHP Delete a cookie

Identify problems with cookies

I n t r o : - thon..
Web sites store information of registered users in databases to keep a track of regular visitors. There are majority of users who do not register with the Web site but frequently visit the Web site. For storing information of such visitors, we use cookies. Cookies enable Web sites to store user information. In this session, we will learn how to set, retrieve, and delete cookies in PHP. In addition, we will learn about the various security issues relating to cookies.

id.--i -Injor'odudin-ra-. Cookie.HTTP is a stateless protocol because the execution of the Web commands happens independently. The execution of the current command is without the knowledge of commands that came before it. When a Web browser requests for a static Web page, the server responds by sending the Web page the browser requested for. The process does not involve any interaction with the user. The user simply clicks the hyperlink on the Web site and accesses the Web page having some content. Figure 16.1 shows the transfer of static data from Web server to Web browser.

Request Response

)01

Figure 16.1 : Transfer of Static Web Page For dynamic Web pages that require user interaction, scripting languages such as JavaScript, PHP and ASP are used. Dynamic Web pages take in information from the user and record it for further processing. For example, on an online shopping Web site, the user browses through the Web site. The product that the user purchases are added to the shopping cart. On completion

..3b Scripting with PHP

V 49.0 K) 2004 Aptech Lhnied

Page 199 of 274

APYIEC"
Sessuon 16
W00 : R L D W9.0 19

Working with Cookies of the order, the Web site prompts the user to enter personal details for order confirmation and delivery. Figure 16.2 shows the working of the dynamic Web pages. Data sent for Processing Data is A Processed Processed Data to Web server

Request made Processed Data to Web

Figure 16.2 : Transfer of Dynamic Web Page Web sites store two types of data, such as temporary and permanent data. Temporary information is stored in cookies for a certain period. Web site stores permanent data in cookies for a certain period and then saves the required information in the database. Web sites use two types of cookies: Persistent - Exist in the Web browser for a period specified at the time of its creation Non-persistent - Deleted from the Web browser as soon as the user exits the browser For example, on an online shopping Web site, a user selects few products and adds them to a shopping cart. The user moves on to the next page to select some other products. In such a situation, the user information needs to be stored somewhere before the user moves to the next page. Although the user has not completed the transaction, the Web site stores the data in a temporary variable called cookie. Figure 16.3 shows the temporary data being stored in a cookie.
User adds a product to shopping cart confirmation

................... .
Temporary data For

Beforeorder

Figure 16.3 : Storage of Temporary Data

When a user cancels the order, the products added to the cart are no longer useful to the Web server and the Web browser. Such temporary data stored in the cookie is deleted as soon as the user cancels an order or exits the Web browser. Figure 16.4 shows the deletion of the temporary cookie when the user cancels the order.
V 1.0 :D 2004 Aptech Lin)ited

User cancels the order

........... ...... 1-1 ...... Temporary cookie deleted


'

Web Scripting with Pr-7

Figure 16.4 : Deletion of Temporary Data

Page 50 of 274

Working with Cookies


The user enters sensitive information, such as the full name, address, credit card details on order confirmation. Such sensitive and confidential information is stored in the database of the Web server. Web sites often use cookies to determine: Number of times the user has visited the Web site Number of new visitors Number of regular users Frequency of a user visiting the Web site Date on which the user had last visited the Web site Customized Web page settings for a user

When a user visits the Web site for the first time, the Web server creates a unique ID and sends the ID in the cookie to the Web browser. The browser stores the cookie and sends it back to the Web site in subsequent requests. The Web server can read the information stored in the cookie only when it is related to the Web site. The life of a cookie depends on the expiration time and date. The cookie is stored on the hard disk of the user. This enables the Web site to keep a track on the user visiting the Web site. The information about the user is generally stored in the name-value pair. Web servers and Web browsers send cookies to each other in HTTP headers. The Web server sends the cookie to the browser in the Set-Cookie header field. This field is a part of the HTTP response. The Web browser stores the cookie and uses the same in subsequent requests to the same Web server. Consider the following HTTP response header: HTTP/2.0 207 Content-Lengch: 8451 Coast e,n(:.-Type: text/]"itrnl Date: Hon, 27 Dec 2004 05:29:24 GMT Expires: Mon, 27 Dec 2004 05:29:44 GIRT Set.-Cookie: city-(_,asL-(-:oasL._USa In the above HTTP response header, the following is displayed: > > Version number of the HTTP protocol Size of the content Type of the content Date and time of response Expiry date and time of the cookie Cookie header

Web Scripting with PHP

Sessuon 16

WORLDWISS .4 R F, U Cif

Session 16
Working with Cookies
wn~ The Web browser records the cookie information and saves it on the hard disk of the system. In subsequent requests made to the Web server for a Web page, the information is sent along with the HTTP request header. Consider the following HTTP request header:

GET /usa/florida.Dhp HTTP/21.0 Connection: Keep-Alive Cookie: city=east-coast-usa Host: www.Webworldmaps.com Referrer: hLtp://vAN-,v.Webworld-maps.com/
Note the cookie in the above sample request. This cookie can be set by using the set-cookie function. The above code snippet shows the subsequent request that a Web browser sends to the Web server.

'16.2 Setting a Cookie


Cookies are incorporated in HTTP request and response headers. Setting a cookie means sending the cookie to the browser. PHP uses two functions, setcookie () and setrawcookie ()to set a cookie. Programmers prefer using the setcookie () function because the setrawcookie ( ) function sends a cookie without urlencoding the cookie value. There are certain special characters that cannot appear in a URL and have to be encoded to retrieve information. Urlencoding is a process where the Web browser takes special characters, such as a tab, space, exclamation mark, hash, and quotes and replaces them with code values. The setcookie ( ) function generates the cookie header field that is sent along with the rest of the header information. The syntax for the setcookie ( ) function is:

setcookie(name, value, expiry date, path, domain, secure)


Where,

name - Indicates the name of the cookie. This is a mandatory attribute.

value - Refers to the value of the cookie that is stored on the client system. This is a mandatory attribute.
expiry daL.C., - Indicates the date and time (UNIX timestamp) when the cookie will expire. The cookie is not used once the expiry date is reached. This is an optional attribute.
6;~- UNIX

timestamp signifies the time and date that the time H function returns. The time is measured in the number of seconds from 'Is' January 1970 00:00:00 GMT.

Page 52 of 274

V 1.0 (c) 2004 Aptech Limited

Web Scripting with PHP

Working with Cookies


path - Refers to the path on the server where the cookie will be available. It specifies the

subset of the URLs present in the domain where the cookie is applicable. If the path attribute is not specified in the setcookie function, the path of the document present in the header is taken. domain - Refers to the domain name where the cookie is made available Indicates the type of HTTP connection that the cookies will pass through.
When the value of the secure parameter is set to 1; the bookie will be'-set only if a secure

secure -

HTTP connection exists.

When the cookie is set, the value is automatically URL encoded- When the script retrieves a cookie, it automatically decodes the value. PHP executes codes in a particular sequence. HTTP headers are executed before the scripts. Cookies are a part of the HTTP header. There can be more than one cookie in the header but it should relate to the same domain or website- The code related to the cookies must be specified before: HTTP header Displaying any content Any white space
If any content is displayed before calling the setcookie ( ) function, the function will fail and return False. So before displaying any output or even the white space, setcookie ( ) function must be called. If the setcookie ( ) function runs successfully, the function returns True. c,- The setcookie () function returning True does not indicate that the Web browser has

accepted the cookie. Suppose, a Web site displays country maps when a user enters a country name in the search feature of the Web site. To set a cookie that expires in 1 day, enter the following code: $mapname = $_GET['fmapname'l ; setcookie("mycookie", $mapname, timeo+86400, ".Webworldmaps.com");

/Webmap/",

In the above code snippet, fmapname is the variable that contains the country name that the user enters. The $mapname variable stores the value that the GET method retrieves from the form. The setcookie ( ) function includes:

mvcookic- Name of the Bookie time ( ) -1 86400 Time when the cookie will expire /Webmap Path where the cookie will be stored l N eb)woridlmaps.com Domain that the cookie will use

Page 53 of 274

Session 16
Working with Cookies

To create a cookie that lasts till the browser is open, enter the following code: $val $GET [ 'unaino' I ; setcookie("uname",$val); In the above code snippet, uname is the variable that contains a value. The $val variable stores the value of uname that the GET method retrieves. The setcookie ( ) function in the above code snippet sets a cookie named uname. The value of $val is assigned to the cookie, uname. PHP script can include more than one setcookie ( ) function. Multiple calls to a cookie in the same script can be made in a specific order depending on the version of PHP. In PHP 3, multiple setcookie ( ) function within the same script are called in the reverse order. For example, if a cookie is to be deleted before creating another, the set cookie statement must be stated before the delete command. In PHP 4, multiple setcookie ( ) function within the same script are called in the specified order.

16.3" Retrieving Cookies in - PHP


Cookies are useful only when the Web server can retrieve the information from it. The cookie is available only when the user loads the next page. The Web browser matches the URL against a list of all the cookies present on the client system. If the Web browser finds a match, a line containing the name value pairs of the matched cookie is included in the HTTP header. The document that created the cookie can access it. All the documents that are present in the same directory can also access the cookie. To access the cookie, the documents outside the directory need to include the path or the domain name of the cookie. PHP provides three ways of retrieving a cookie value:
Passing a variable as the cookie name - To retrieve the cookie value, we can use the

variable as the cookie name. The following code displays a cookie value: echo sc(Dokiename; The above method of retrieving the cookie value is not recommended- This is because PHP will start searching all the variables present in the client system. The register_globals option must be enabled in the configuration file if we want to use this method to retrieve cookie value.
Using $HTTPCOOKIE VARS [I array - PHP uses cookie name as a variable to retrieve the

cookie value. PHP can also use an associative array called $1zTTP('O'0KIE VA.RS F 1 to retrieve the cookie value. The $HTTP_COOKIE_VARS [I is a global variable that reads a

Page 54 of 274

Sessoon 16

WO N L-0 W 1-*D'Z

APTECH

Working with Cookies


value of the cookie. The name of the cookie must be passed as the key to the S.HJ"1'1'1_COOK1E_VARS[', array as follows:
E'(-.'110 $11TTP__COOKI EVARS

( $ cook i enanie

T h e a b o v e m e t h o d i s m o r e r e l i a b l e a n d f a s t e r t h a n r e t ri e v i n g t h e c o o k i e v a l u e t h r o u g h a variable.
Using

$--COOKIE[

] variable -

We can also use the following to retrieve the cookie value:

$_COOKIE['$cooki.e_name'1;
The above method of ret ri ev ing the cookie value is recommended, but it requires PHP 4.1. It is also considered the best method. It is also known to be simpler and more secured than using the $HTTP_C00KIE_VARS [ ] associative array. To retrieve a cookie value using the $IJTTP COOKIE VARS [] global variable, enter the following code snippet: <?php

$cookieval

$HTTP_COOKIE_VARS['unam4'];

<HTML> <BODY> <?rjhp if (isseu($cookieval)) echo "Welconie $cookieval "; } else echo "You need W log -in

</F301)y> </HTML> In the above -code snippet, stores the cookie value. The function checks whether the cookie is set. If the cookie is set, the echo statement will display a welcome message along with the cookie value. I f the cookie is not set, the message appears prompting the user to log in.

Page 55 of 274

Session 16

Wo"ALID-W401E

Working with Cookies

16'.4. Deleting ..-CI

C o d k i e . :

Cookies can be deleted automatically or manually. There are two ways to delete a cookie: > Resetting the expiry time of the cookie to a time in the past Resetting a cookie by specifying the name of the cookie Deleting the cookie with the same name and a time in the past forces the Web browser to delete the cookie from the client system. To delete a cookie with a date in the past, enter the following code snippet: setcookie("$cookie i-iame", "", timeo-8000);

In the above code snippet, $cookie name refers to the name of the cookie. The value of the cookie is not specified and the time ( ) function takes in the expiration date in the past.
M

We can use a new cookie statement with the cookie name as the variable to delete a cookie. This process is called as deconstructing the variable. To delete a cookie through deconstruction, use the following syntax: setcook-ie($cookiename); For example, to delete the cookie named uname, use the following code: setcookie($uname);

16.5 Problen

,with Coo

Web sites store user-related information on the client system. Cookies are not secure and reliable because the user-related information can be accessed by anyone who has full access to the client system. The user-related information can contain sensitive information, such as credit card information, passport number, password, or an identification number. Following are some of the drawbacks of cookies: Cookies cannot contain more than a certain amount of information. The cookies work well when the size limits to 4 KB. Web sites cannot use cookies to store a large amount of data. Only a maximum of 20 cookies of a domain can be maintained.

>

Page 56 of 274

V 1.0 (c) 2004 Aptech Limited

Web Scripting with PHP

Session 16

W0. L DW*IDE

Working with Cookies A browser can maintain a maximum of 300 cookies. Older cookies that were stored earlier are deleted to accommodate the newer cookies of the different Web site. Storing large number of cookie files slows down the system. To enhance the performance of the system, users often delete temporary files that contain cookies. Web site statistics may go wrong when users delete such cookies to improve the performance. Some users disable cookies while accessing Web sites. The Web sites that depend on cookies lose information of such users. There can be multiple users using the same system visiting the same Web site. Web sites assign cookies to the system and not to the user. This can hamper the number of visitors' statistics. Cookies need to be called on each Web page. There might be instances when there is lots of information that we want to retrieve from a cookie. Retrieving larger amount of information on each page requires repetitive coding across the pages.

Page 207 of 274 Web SCtI.pz I,) g with FIHP V 1.0


rc7

2004 Aptech Limited ,04 Aptech U

Session

AprECH
II

w:-0.e

L D WJ'Dle

Working with Cookies

>

Web sites use cookies to store user-specific information. Cookies are stored on the hard disk of the client system.

);> In the static Web pages, there is no user interaction. Dynamic Web pages gets information from the user and record it for further processing > Types of cookies: Persistent Non-persistent Persistent cookie is stored in the Web browser for a period specified during the time of its creation Non-persistent cookie is deleted from the Web browser as soon as the user exits the browser. Web servers and Web browsers send each other cookies in HTTP headers. Web server sends the cookie in a Set-Cookie header field. PHP provides three ways of retrieving a cookie value: Passing a variable as cookie name
0'

Using $._COOKIE[] Using $HTTP--COOKIEVARS[]

PHP uses the following functions to set a cookie: setcookie() setrawcookie() Two ways to delete a cookie:
Resetting the expiry time of the cookie to a time in the past Resetting the cookie by specifying the name of the cookie

Page 208 of 274

lotech Limited

Web Scripting with PHP

Session 16

(A'pr,Ecm WORLDWID
E

W k r o w g n ii h t C

>

Some of the drawbacks of cookies: Cookies cannot contain more than a certain amount of information Only a maximum of 20 cookies of a domain can be maintained A browser can maintain a maximum of 300 cookies Storing large number of cookie files slows down the system Some users disable cookies while accessing Web sites

Web Scripting with PHP

Sesskon 16

-0 R.L.DIS.a W,

? py-Ecm

Working with Cookies

1.

is a global variable that reads a value of the cookie.

a. b.
C.

d. 2.

$COOKIE[] $HTTPCOOKIEVARS[I setcookie() isset (


requires PHP 4.1 to retrieve cookie value.

a. b. C.
d. 3. a. b.
C.

$COOKIE() $HTTPCOOKIE VARSH setcookie() isset


Maxim um of 20 30 200 300 cookies of a domain can be maintained :

d. 4.

A browser can maintain a maximum of _______________________ cookies. ab.


C.

20 30 200 300 function checks whether the cookie is set.

d5.

The _____

a. b.
C. d.

$_COOKIE[] $HTT)-)_COOKIE_VARS setcookie()


isset

6.

The __________________________ option must be enabled in the configuration file to pass a variable as cookie name.

a. b.
C.
d.

registercookies enableregistercookies reqister I o;:) a- I s


_gl
V 1.0 2004 Aptech Limited i Wel) Scr pting with PH"

er)ab1e_register__g1.oba1,,

P a g e

6 0

o f

2 7 4

Objectives
At the end of this session, you will be able to:
Set a cookie Retrieve a cookie in PHP

Delete a cookie

The steps given in the session are detailed, comprehensive and carefully thought through. This has been done so that the learning objectives are met and the understanding of the tool is complete. Please follow the steps carefully. Part I - For the first 1.5 Hours:

Cookies are incorporated in HTTP request and response headers. Setting a cookie means sending the cookie to the browser. The setcookie () function generates the cookie header field that is sent along with the rest of the header information'. Suppose a Web site accepts username and password to login before they can shop online. The Web site saves the user information in a cookie- The subsequent Web pages retrieve the user details from the cookie. To create a form that accepts the username and password: 1. 2. Open the gedit text editor. Enter the following code:

<HTML> <HEAD> <TITLE> Login Page </TITLE> </HEAD> <BODY> <H4> Please enter your details </H4> <FORM ACTION="validate.php" METHOD="GET"> <TABLE> <TR> <TD>Login name</TD>

Web Scripting with PHP

V 1.0 200 4 Ap te c h Li mite d

Page 61 of 274

14,0F,,EC,f,F

Session 17

W L!WW-"1;0:* 0R

Working with Cookies ~T'><I14PUT TYPE="text" NAME="logname"></TD> </TR> TR> <TD>Password</TD> <TD><INPUT TYPE="password" NAME="pass"></TD>. </TR>. </-TABLE> <INPUT TYPE="submit" VALUE="LOGIN"> <FORM> </BODY> </HTML>

Save. the file ,as InformatioriAtmi under the,Jv r/ a , . To validate the information that the user enters in the form:

/ 4.~mi A rye c t o . . ir

W,

[: logname %

~t~Mk_

$vall = $__GET $va12 = $__GET[ 'pass']

Enter the following code to set a cookie for logname that does not expire for a

week: setcookie("logname",$vall)
The above code snippet sets a cookie named logname that expires as soon as the user closes the browser. The value that gets stored in the $val variable is assigned

to the cookie. Enter the following code to validate whether the Login Name and Password fields are left blank: if ($vali==) echo "Please enter the name!"; echo "<HTML>',; echo "<H7_AD>"; echo "<TITLE> Validate< /,1,i-.TLE>"; Page 212 of 274 'v C,, 2004 Aptuc,;, Llirlted
_;.1, DUD

Et2_17TECif

Session 17

LOWIDE

Working with Cookies

echo "<BODY>"; "<A H EF='Information.htm1'> Back </A>"; </ echo' </14TML>",


B O DY >"

echo `<HEAI)>"; echo '<TITLE> Val idate< /TITLE>" echo "</1HEAD>",

Header("Location:. homepage.php");

The above code snippet uses the ,leader that is the home page of the Web site To create the home page of the Web site:

function to redirect the information to homepage.php

1.

Enter the following code to retrieve the login name from the cookie and store it in the variable:
<?php

//Store the value of the cookie logname $1oc-icoo'kie $HTTP COOKTE _VARS['logname'];
L

2.

Enter the following code to display the various items available for shopping: echo "<HTML>11 ; echo "<HEAD>";

Web Scripting with PHP

V 1 .0 @ 2 004 Ap te c h Li mite d

Page 63 of 274

Session 17

WOULOW1,02 AprIC-CH

Working with Cookies

//Display the value of the cookie 16 olkie, echo "Welcome $logcookie echo '<BR><A HREF='logout.php'>Logout</A>";. echo "<CENTER>";

. echo "<TR..ALIGN='center'.>"; echo "<TD><A HREF=Iaccess.php'>Accessories</A></TD>"; echo "</TR>"; echo "<TR ALIGN='center'>"; echo "<TD><A HREF='perf.php'>Perfumes</A></TD>"; echo "</TR>"; echo "<TR AL!GN='centcr'>"; echo "<TD> <A HREF='apparel.php'>Apparel</A></TD>"; echo "</TR>"; echo "</TABLE>";

echo "</CENTER>"; echo "</BODY>", echo "</HTML>fl The above code displays the cookie value stored in the variable, $logcookie. It also displays items such as, Confectionery, Flowers, Accessories, Perfumes, and Apparel on the Web page.

Page 64 of 274

V 1.0 Cc-) 2004 Aptech Limited

Web Scripting with PHP

Session 17

APrecm
WORLDWIDE

Working with Cookies


3. 4. 5. Save the file as homepage.php under the /var/www/html directory. Open a new file in the text editor. Enter the following code to log out the user from the Web site:

<?php $logcookie
:

$HTTP_C00KIE_VARS['logname'1;

//Deletes .,.logname cookie setcookie("logname"); //Redirects sers. to the main. Information.ht-n page for login Header("Location: Inf6rmation.-Mm");

Widdigs"

(V

. Q

j-

77

File Edit View Go Bookmarks Tools Window Help Back


Home

Forward

Reload Stop

,4 http-alh.st/inform

/A.

jp -s Search] Print

Bookmarks

Red Hat Network ;-'I Support (I`iShop L1 Products EftTraining

Please enter your details Login name Password


LOGIN I

<~_,7 1--Done

Figure 17.1 : Login Page 9. Click the LOGIN button. The Validate page appears, as shown in Figure 17.2.

Web Scripting with PHP

APTECH
Session 17
Working with Cookies
I..".:

i,.File

Edit View

Go Bookmarks Tools Reload Stop

Window

Help

i21! x
1

;!,114orne
5
,

Back

h,tp:j/loi:alhost/homepaq

F o r w a r d

E, Search] ~O

C-4

Print i

dBookmarks "Red Hat Network CtSupport JEjShop (ZiProducts L-jTraining

Plea-v-- enter the name'.


Rack

UA. C4 -,?, 93 G9

Done

OGIN

File Edit View Go Bookmarks Tools Window Help

Back
3 Ho me

F.)nvxJ

Reload Stop

http://1oi:alhostjhomepagf
I .. ......... ....

Print Training

Bookmarks _ 00Red Hat Network :_4SUpport i

Shop j:; _Products Lj

Shop till you

Con1*1.Ci:01)er%,

L.,s.::::sories

Perl'unu-,
Apparel

4 z

GE2

Done

............ -

........... -

Figure 17.3 : Home Page

d n i g m o f I h t l a V : 2 . 7 1 e r u F
n h J e i l o c O v N M , ~ 0 I

X L M

I
1 . 0 (c ,

0 1 D L R O W

2004 W tH ih S bP

Aptech Li it d

Web Scripting with PHP

APYIIEC

Session 1

WORLDWIDE

Working with Cookies


To create the subsequent pages of the Web site:

1. Open a new file. in the text editor. 2. Enter the following code to display the various items for the Confectionery category:.

$HTTPCOOKIEVARS['logname'

echo "<H3> Shopper's Paradise </H3>"; echo "<H5> Shop till you drop!!! <H5>"; echo "<HR>"; echo "<BR>"; echo "<TABLE BORDER-,1,>"; echo "<TR ALTGN='center'>"; echo "<TI-I>Code</TfI>"; echo "<TH>Name</TH>"; echo "<TH>Price</TH>"; echo "</TR>"; echo echo echo echo echo "<TR ALIGN='center'>"; "<TD>C001</TD>"; "<TD><A HREF= '' >Choco Delight</A></TD>"; "<TD>$40</TD>I "</TR>";

echo fi<TR ALIGN='ccnter'>"; echo "<TD>C002</TD>"; echo TD><A HREF= >Van i 1!a Crush< /A>< /'I'D>" echo " .-TD>$'110</TD>"; echo < /TR > echo "<./TABLE->";

veb Scripting with PHP

V 1.0

2004 Aptech Limited

Page 67 of 274

Session 17
Working with Cookies

echo "</CENTER>";
</BODY>

</HTML>
r

-Save the file as conf.php under the /var/www/html directory.

,Type http://localhost/Infonration.html in the address bar and press Enter


o open the Login page. rater John aiajohn as the username and password and click LOGIN. The homepage

W111 im-Al FI I I

Coo :'Bookmarks
Reload s w a r d '

I o ol s Wndow- LW 4 - '
/Axo

Back'

Ito P

dhost/conf.pl vi

&.S,.-, h

. P r i n t .1

Welcome John Logout

Shopper's Paradise
Shop till you drop!!!

C . d 7 cF N a m e
..........

;Prrcel

KtqiChoco-Dcli,zhd $4010002.1

Vanilla Grub S70


1: ---, 7

42

--.- ..... ..... . .....

tZ

nn~

G9 I Done

Figure 17.4 : Confectionery Web Page


S i m i l a r l y , c r e a t e W e b p a g e s t o d i s p l a y v a r i o u s p r o d u c t s a v a i l a b l e f o r s a l e u n d e r t h e Fl o w e rs . A c ce s s o r i e s , Pe r f u m e s , a n d Ap p a r e l c a t eg o ri e s . T a b l e 1 7 . 1 l i s t al l t h e p ro d u ct s a n d i t s d e t ai l s u n d e r t h e s e c at eg o r i e s .

Page 68 of 274

V 1.0 2004 Aptech Limited

Web Scripting with PHP

Session 17

rAJ:FrEcff
WORLDWIDE

Working with Cookies

Product Category
Flowers

Product Code
F004 F010 F011

Name
Tulip Bouquet Red Rose Lily Diamond Bracelet Diamond Ring Diamond Anklet Charlie Maui Rain Night Mist Black Suit Wrinkle-free Suit Wrinkle-free shirt

Price
$75 $10 $8 $950 $800 $500 $180 $90 $80 $480 $190 $180

Accessories

A001 A006 A012

Perfumes

P002 P008 P018

Apparel

AP001 AP018 AP020

Table 17.1 : Product Details

Web Scripting with PHP

1 . 0

O K

2 0 0 4

A p t e c h

L i m i t e d

Page 219 of 274

Session 17

CilP7'ECH
OR L DW I WE

Working with Cookies

JRY IT YOURSELF
Part II - For the next half an hour:

Full name > Address Email Address Credit Card Number Number 1. Create a cookie that stores all the above-mentioned user information. T elep hone

S h o p p e ' r s P a r a d i s e i s a s h o p p i n g c o m p a n y t h a t d e a ln s is e l i n g g o o d s o n l i n e . T h e W e b i s t e s o e fi s r t e m s , s u c h a s C o n f e c i t o n e r y , F l o w e s r , A

Page 70 of 274

Objectives
At the end of this session, you will be able to: Define a session

Work with the session Start the session Register the session End the session Work with the php.ini file

kliftodtioi'op
Cookies provide us with the functionality of storing the temporary user information. Cookies store information in the remote locations. One of the disadvantages of cookies is that it stores information on the local computer of the user. Sessions in PHP offers the same functionality of storing the user information. The only difference is that sessions enable PHP to store user information on the Web server. In this session, we will learn about sessions and session variables. We will also learn how to register and work with PHP session IDs. In addition, we will learn about the php.ini file.

18.1 Sessions.:"-..
Web browsers and Web servers have a stateless interaction. HTTP. is a stateless protocol that enables the Web browsers to communicate with the Web servers. This protocol has no methods or functions to maintain the state of a'particular user. Even the Web server is not able to distinguish user specific data. It does not recognize the user sessions. Users can browse and search for information using the hyperlinks despite of HTTP being stateless. Figure 18.1 shows the interaction between the Web browser and the Web server. Request from Browser f Response from Server

Figure 18.1 : Interaction between the Web Browser and the Web Server

.*.eh Scripting with PHP

V 1.0 (c)

2004 Aptech Limited

Page 71 of 274

rA JCPrEC,&, woe LDWIDS


Sessuon 18

Session Management in PHP


Web sites that require complex user interaction cannot depend on the HTTP or the Web servers. Sessions enable Web sites to store user requests and information on the Web. Session refers to the time the user accesses information on a particular Web site. Session management involves managing data related to a particular user in a specific session. PHP sessions enable distinguishing the user specific information during the life of the session. A session life refers to the total time a user spends on the Web site before the user exits the Web site.

.19.12 'Importance of a Session


Suppose in a particular Web site, the user has to first register and then log on to access any information. For such user authentication procedures, the Web sites require to maintain the state of the user across the Web site. Web sites traditionally use GET and POST methods to pass user information from one script to another. When these methods are used, PHP assigns user information variables in the following format:
$name = $_GET['name'];

In the above code snippet, the variable $name stores the value that the script retrieves from the form that a user fills. This process of transferring user information is unnecessary and time consuming, especially for a large Web site. Figure 18.2 shows the above code has to be used across all the Web pages of the Web site. Page 1
$na.nc S CIEF[rlalnel;

Page 2

Page 3 0.
$name =

$riarne $--Q.Ei [naMel

$--GET[name]
r-/

r-11

Figure 18.2 : Traditional Transfer of User Information The above figure shows the transfer of user information from one page to another. Imagine having to store and retrieve 20 more user information across 10 different pages. Due to this disadvantage of using the GET and POST methods, Web developers prefer using cookies. Figure 18.n shows how the Web server assigns cookies to the browser.

Web Scripting with PHP

Page 72 of 274

Session Management in PHP


Page 4 Page 3
r).3 r nar

Page 2 Page 1 naf


name = 'kin)"

rl Figure 18.3: Assignment of Cookies to the Web Browser Cookies enable us to store data into a variable and access it across all the pages of the Web site. Cookies are prone to security risks because the user information is saved at the client end. The risks involved are greater when users access Web sites from a public computer or a shared computer. Anyone who works on the computer can misuse the information. For example, a user purchases an item from a Web site from a shared computer. While placing the order, the user enters all his personal information, such as name, age, address, credit card information. All these personal information are stored in the cookies on the shared computer. There are chances that another user on the shared computer misuses the information using cookies. There are some other disadvantages of using cookies: Deletion of cookies Users can easily delete cookies from the client system. We can access a list of cookies from the systems temporary file saving location. Users often delete the temporary internet files to improve the performance of the system. Web sites allot a new cookie to the user without a cookie. This proves disadvantageous to the Web sites who keep a count of the visitors who return to their Web sites. Multiple cookies to the same user - Cookies enable Web sites identify the users according to the computers they use. Web sites aliot a different cookie to the same person every time the user accesses the Web site from different computers. The statistics of the Web site records new user entry of the same person using different computer. In addition, a user has to set all the preferences again on different computers to visit the same Web site. Size of the cookie - Cookies adds on to the page size. So more the information stored in the cookie, larger is the page size. This results to lower performance because users experience slow browsing of the Web site. Cookies disabled - Web sites store cookies on the hard disk of the client. This reduces the performance of computers with the low memory space. To improve the performance of such computers, users disable cookies. This makes the process of assigning cookies pointless.

.*.eh Scripting with PHP

V 1.0 (c)

2004 Aptech Limited

Page 73 of 274

Session 18

W O'R L 0 WIVIE

Session Management in PHP Sessions play an important role in such situations. The security of the information increases on the Web server because unauthorized users cannot access the information. Sessions eliminate the chance of deletion and new cookies assigned to the same user. The size of cookie also doesn't affect the performance of the Web site. Both the Web server and Web browser benefit because statistical information in the server database is accurate. The user information is not lost from the server database. Table 18.1 shows the difference between cookies and sessions: Cookies Stores user information on the client system (Web Browser) Available even after the user exits the Web browser Users can disable cookies Have size limits Sessions Stores user information on the Web server Destroyed when the user exits the Web browser Users cannot disable sessions Do not have size limits

i
i

Table 18.1 : Difference Between Cookies and Sessions

183. Working with. Sessions,:.


A session commences when a user accesses the session-enabled Web site. Web server assigns a unique session ID to each user when the user starts a session. The scripts store and access user information through the session ID. The scripts gain access to the session ID depending on the following two situations:
Cookies enabled - Web server allots the session ID to the Web browser through a cookie. Cookies help transfer user information between the browser and the server. PHP stores session IDs in cookies. The scripts access the required information through cookies. Web server allots a session ID to the users in the form of cookies using the setcookies function.

Cookies disabled - Web server allots the session ID to the browser using the Uniform Resource Locator (URL). URL transfers user information from the browser to the.server. PHP stores session variables in a file. PHP names the file based on the session ID. The scripts access the required user information by retrieving it through the URL. While using a session, PHP stores all the user information in a file on the Web server. The file includes session ID that is related the user's session variable. Each session ID identifies a different user and relates to a file that belongs to that user. Session ID is referred to as a key that links user and user data. PHP destroys the session file once the user exits the Web site.

Page 224 of 274

V 1.0 (0 2004 Aptech Limited

Web Scripting with PHP

Session

AprIECH WORLDWSOE
Session Management in PHP

Figure 18.4 shows the working of the session:

O
1<

First Request Response with Session ID

Subsequent Request ~ with Session ID


1<

)01

Response with Information about User

Figure 18.4 : Working of the Session

PHP works with session in the following sequence: 1. 2. 3. User accesses the session-enabled Web site Web site checks the identity of the user whether the user is a new visitor or an ongoing session user If the user is a new visitor, the Web site allocates a unique session ID to the user. We sites save the cookie containing the session ID on the Web browser. PHP engine creates a file that stores the session-related variables on the Web server. The Web browser records the cookie that holds the session ID. The browser uses the same cookie to retrieve session ID and record all the session-related information. When the user exits from the Web site, the session file is destroyed from the Web server.

4. 5.

-4'Lif6d cle- -the, Session- Y, Based on the communication between the Web browser and the Web server, there are three stages in the life cycle of a session. They are:

V 1.0

Cc,

Aptech Limited

Page 225 of 274

Web Scripting with PHP

Starting the session Registering the session variable Ending the session

Session 18

('A.kPr'EC" \'!W." LDWIQE


Session Management in PHP

A session starts when a user logs on to the Web site. In PHP, the sessionstart ( ) function enables to start a session- The process of starting a session is also called as initializing a session. PHP creates a session file on the Web server when a new session starts. The session file is created in the /tmp directory. PHP names this file on the unique session identifier value that the PHP engine generates. The session identifier is also known as the session ID. The session ID is a hexadecimal string of 32 digits. The file naming convention for the session file is:

sess_<32_digit_hexadecimal_value>
The session file name always precedes with less_ and is followed by a random 32 digit hexadecimal value. For example, Bessdenkhu7869jhnkh789jas543hk87p5u3 is a session file name containing session ID as denkhu7869jhnkh789jas543hk87p5u3. The Web server passes the session ID as a response to the browser. The Set-Cookie header field is sent along with the session ID. The response sets up a session cookie in the browser with the name PHPSESSID and the value of the identifier. PHP scripts access the value of the session ID from the $HTTP_COOKIE_VARS associative array and the $PHPSESSIID variable. The session--start ( ) function must be specified on the top of every Web page or before the start of the actual coding. The session star.( ) function always returns True. When the session starts, PHP checks whether or not the session is a valid session. If session is valid and existing, it activates the frozen variables of the session. If session is invalid or non existing, it creates a session ID for the new session. The scripts can use the session variables only when the variables are registered with the session library. The syntax for session start( ) function is:

session starto;
While using cookie-based sessions, we must call sessionstart () before anything is send to the browser as an output. For example, to start a session enter the following code in the text editor:

session start:(); ocho "The Session id is

P a g e

Session 18

O W I'D E

Er-Ecw

Session Management in PHP


Save the above code as sessl.php in 1var1wv,,w1html directory. In the above code, the session start ( ) function intializes a session. The session id ( ) function displays the session id that PHP allots to a user_ Figure 18.5 shows the output of the above code:

Figure 18.5: Session ID of a Session


PHP displays an error message when we try to display some output before calling the session start () function. For example, we will add an echo statement in the sessl.php file, as follows:

echo "Welcome to Shoppers Paradise"; <?php


s es s i on s t ar t ( ) ;
--

ethic,

"The Sessior) i d i s

sessionid

PHP shows the error message as shown in Figure 18.6:

V
File Edit View Go Bookmarks Tools Window Help Back Forwaal hUp:[/localhostisess Reload Stop ..... ......... .... ...... ... .. ... . .......
.............. ...................

Print

!Home ':;Bookmarks _e Red Hat Network t: jSupport ;Shop ;_j'Products CjTraininq echo "Wc1conic to slloppcn Paradise": Wal-ning: Cannot send session Cache 111111(cf. - headers already scent (output started at in on line 4 The session id is 324219,,0805 1 fiOcfd7 ll1)09c8',6',07',c

Figure 18.6 : Error Message

Web Scripting with PHP

V 1.0 (P 2004 Aptech Limited

No
Fil

Page 227 of 274 MpLiffla;. i*'

Edit Vi

rA P Tr CH Session 18
11!!~ L-D'W-2:tr-F

Session Management in PHP

-2 Registering the-S

ession Variable

Variables in a session file contain user specific information. To work with the sessions across all the Web pages, session variables need to be registered with the session library. Session library enables creation, serialization, and storage of session data. We can use three methods to set a session variable. They are: $-SESSION( I - Recommended for PHP 4.1.0 $HTTP-SESSION. VARS - Recommended for PHP 4.0.6 or less session register () Not recommended as it has been deprecated
-

Sessions variables can be of any data type such as integer, string, Boolean, or object. PHP stores the session variables in a session file by serializing the values. PHP automatically handles the process of serializing the session variables.

fdrmin'J". ~~racrables to:~~,yte~ e~.r~~ ~~ser~tatior~,~~1d ~s~or~e,~~as,.l~at~str~ng~~~> ~,~_..~,~ "

sd

For example, to register the value of the session variable, enter the following code in the text editor: <?php s e s s L o n - s t a r t o ; $H-,-,P SESSION VARS['mvname']= "Jessica";
. -

<HT1,dL> <HEAD> <TITLE> Session </TITLE></HEAD> <BODY>F <A HRE page. -hp"> Homepage of MyPage. corn <'A> </130DY> < / HTM 1-1> Save the file as session.php. To display the value of the session variable, enter the following code: < ? IDI-ID $myname $HT'rP-SESS-FON--,..,7, RS['ir.yna,-Qe']-

< YPM L
< .i ~

HEAD> <TITLE> Eoinepl,ge <,/'_7 1VLE>-:_ /HEAD> <BODY> Welcome < -- o l cn .: aivame > l..o M Page.com P < BODY> < HTM L >
Page 228 of 274 V 1.0 Cm 2004 Aptech Limited

EePTECIF

Session 18

ORLDWID8

Session Management in PHP


Save the file as mypage.php. In the above code, session value is retrieved and displayed. To view the output, open the Mozilla Web browser and type hULp://localhost/session.php. The Sessions page appears with a hyperlink. When the user clicks on the Homepage of MyPage.com hyperlink, the Homepage page appears with the message, Welcome Jessica to MyPage.com.

18.4.3 Ending the Session


When the user logs out of the Web site, PHP calls the session des troy() function. This function removes the session file from the system. Although the session file is deleted, the $PHPSESID cookie is not removed from the Web browser. The session must be initialized before the session destroy() function is called.
66,-

We can alter the lifetime of a session...cookie by modifying ing:theAefault, value. in; the-!PH R.

The syntax of sessiondestroy () function is: session destroy(); The Web server performs several steps to determine that the session has ended. PHP uses the following configuration directives when a session ends:

gc maxlifetimeo Enables PHP to determine the time to wait before ending a session after the user exits the browser. This process of cleaning up the old session is called as garbage collection. gc_probability() Enables PHP to determine with what probability the garbage collection routine must be invoked. If the value of this directive is set to 100%, then the process of garbage collection is performed on every request that the Web browser makes. We will use the my-page. phu file to destroy the session. To destroy a session, enter the following
code in the mypage.pi-p file: < ?ph,,) $myname = $i-:'rTP_SFSSIONVARS['myna-ne']; sessiondestorv();

To see the effect of -iession dosLroyo function, open the Sessions page in the Mozilla Web browser. Click on the Homepage ollhyperlink. Note that the message Welcome -1 . ~iypage Jessica to MyPage.com still appears. The value of the session, mvname still appears because the value of the session variable can be accessed on the current page where sessiondestroy function is used.
P a g e 2 2 9 o f 2 7 4

Web Scripting with PHP

V 1.0 'P) 2004 Aptech Limited

Session 18

WOR LOWIDIE

Session Management in PHP To destroy the variable completely from the current page, add the following code before the session_des troy() function: sessionunseLo; The session_unset ( function unregisters a session variable.

18.5 Working with the php.ini File 9


A Web server can contain multiple php.ini files. To check for the active php.ini file that PHP uses, start the terminal and enter locate php. ini at the command prompt. The path that appears signifies the path of the file that PHP refers to. We can create a php.ini file if there is no php.ini file on the Web server. Download a complete source code from http://www.php-net/ downloads .php to create a new php.ini file. PHP interpreter works according to the specifications made in the php.ini file. The Web server searches for the php.ini file in the following locations, sequentially: Directory where the PHP script was called Root of the Web directory The default .ini file of the Web server If a client system does not have a custom configuration file, the PHP configuration file of the Web server is used. On the Web server, the php.ini file is located under the /usr/ local /php4 / iib directory- Figure 18.7 shows the PHP configuration file:
V
El ie
: :;-11v I

'x
Edit Vi e w Te rm i nal Go Help
J:t

WARNING ;

This is the default settings file for new PHP installaiions. 1 By default, 1 14P installs itself with a configuration suitable for development purposes, and *NOT' for production purposes. For several y i securit -oriented considerations that should be taken before going onl ne w i t h y o u r s i t e , p l e a s e c o n s u l t p h p . i n i - r e c o m m e n d e d and lit tp: //php. net/manual/en/security. phi).

; About this file : lhi file controls many aspects of PHP's behavior. In order for PHP to read i t , i t m u t ,i t b c - W a d e d ' p h p . i n i ' . P H P l o o k s f u r i t i n t h e c u r r e n t w o r k i n g d i r , c l o r % , i n t h o p a t h d e s i g n a,t e d b y t h e e n v i r o n m e n t v a r i a b l e P H P R C . a n d i n t h e p a t h t h a t w a s d e f i n e d i t . c o m p i l e t i m e ( i n t h a t o r d e r ) . U n d e r W in d ow s, t he path is the Windows directory. 'file p a t h i n w h i c h t h e p h p . i n i f i l e i s l o o k e d f o r c a n b e o v e r r i d d e n u s i n g the -c argument in command line mode.
s

.. .......

23,1

Top

Figure 18.7: PHP Configuration File


Page 230 of 274 V 1.0 O 2004 Aptech Limited
c

64-PTEC'H

Sessuon 18

ORLDWIVE
~

S e s s io n M an a g e me n t i n P HP
T h e p h p . i n i f i l e c o n t a i n s d i r e c t i v e l i s t e d i n t h e d i r e c t i v e = va l ue f o r m a t . W e c a n u s e a semicolon to add a comment to the file. PHP ignores lines that begin with semicolon or a singl e whi t e sp a ce. W e c an edit th e php .i ni fi l e to cu sto mi ze the se tti ngs. Table 18.2 lists the categories containing various options available in the php.ini file.

Table 18.2 : Categories of the PHP Configuration File Categories Options that

Session 18

WO R LD'W I 81E

S e s s io n M a n ag e me n t in P HP Several options can modify the functionality of the PHP session. Session category of the php.ini file includes options, such as: session. save hand1er Specifies how PHP stores and retrieves session variable. We can use either of the following values for this option: files: Indicates the use of the session files. This is the default value. mm: Stores and retrieves data from a shared memory user: Stores and retrieves variables with the custom defined handlers session. savepath Specifies the name of the directory where the session files will be stored. By default, the session files are saved in the /tmp directory. session.use cookies Indicates whether PHP must send session ID to the Web browser through a cookie. By default, the cookie stores the session ID. The value to enable cookies to store a session ID is 1. session. useonlycookies Indicates whether the modules can use only cookies for storing session IDs. By default, this option is disabled. session. cookie 1 if etime Specifies the lifetime of the cookie. The value is specified in seconds. By default, the lifetime of a cookie is set to 0 which means the cookie is destroyed once the browser is closed. session . name Manages the cookie name and form attributes such as GET and POST that holds the session ID. By default, the value of this option is PHPSFSSID. session .auto '-- start Enables sessions to automatically initialize if the session ID is not found in the browser request. It is recommended to disable auto start feature because it increases overheads if not all the scripts require the session ID. Specifies whether the cookies must be sent over secured connections. By default, the cookies are not sent through secured connections. We can also change the other settings in the php.ini file, such as: register alobals Controls the functioning of server, forms, and environment variables. When we enable this option, we can directly access the forms, server, and environment variables by their names. If this option is disabled, we can retrieve variables using the GET or POST methods as follows:
' $ vari a ) . - ) 1 e n a m e ' j $ GET[ 'svariabienaiiie' I $_POST[

or

Page 232 of 274

V 1.0 O. 2004 Aptech Limited

Web Scripting with PF:

Sessaon 18

rA~Yrrcf Session Management in PHI

If the register_globals is enabled, we can directly access the variable using the variao name as follows:

$sroreValue = $var-Jable--name;
In the above code snippet, variablename is the name of the variable that holds sessio data of another Web page. The variable storeValue stores the information included in th

variable name. upload_tmp---dir. Sets the location of the temporary file that is uploaded with the HTM
form. Any user can access the uploaded files in the default location of the Web server. W can create a directory and specify the path for storing the uploaded files in the php.ini HE

display errorsand displaystartuperrors Enables PHP to display error on


the Web browser. It is recommended to disable these variables, especially while creating dynamic Web pages. Dynamic Web pages may display user sensitive information, such a password, credit card details in event of an error.

log errorsand error log Enables PHP to display logs errors. The error--c-variable stores the path of the directory where the logs get stored. It is recommended log errorsvariable, when the displayerrors and enable the displaystartupe--r-ror! variables are disabled.

Web Scripting with PHP

Session 18

WORLDWIDE

APEUCH

Session Management in PHP

Cookies provide us with the functionality of storing temporary user information. Cookies store information on local computer of the user. Sessions enable PHP store user information on the Web server. HTTP is considered a stateless protocol that enables Web browsers communicate with the Web servers. Web server is not able to distinguish a user specific data. Web sites that require complex user interaction and cannot depend only on HTTP and Web servers. Sessions enable Web sites store user requests and information on the Web. Session refers to the time the Web user accesses information on a particular Web site. Session management involves managing data related to a particular user in a specific session. Session life refers to the total time a user spends on a Web site before the user closes the Web site windowThe scripts gain access to the session ID depending on two situations, such as: Web user enables cookies Web user disables cookies
I

There are three stages in the life cycle of a session, such as: Starting a session Registering a session variable Ending a session
ituo

Page 234 of 274

V 1.0 @ 2004 Aptech Limited

Web Scripting with.

Session 18

(AprEcAr LOWIDE
Session Management in PHP

The php.ini file contains options that are grouped under categories, such a s :
V 1 . 0 O c , 2 0 0 4

Aptech

L i m i t e d

Pa

Language Options Safe Mode Font Colors Misc Resource Limits Error hanling and logging Data Handling Magic Quotes Paths and Directories File Uploads Session

Web Scripting with PHP

W 0 R L:D W PD :E

Session
Session Management in PHP

C K YOU 8 PROGRESS
1. The __________________ option indicates whether or not the modules will use only cookies for storing session IDs. a. b.
C.

session.cookies session cookie lifetim session.usecookies session.use_only_cookies

d.

2. The _________________ function enables PHP determine the time to wait before ending a session after the user closes the browser. a. b.
C.

session destroy( gcmaxlifetimeo gcprobabilityo session_unregister()

d.

3. PHP uses the ______________________ function to remove the session variable from a session. a. b.
C.

session destroy() gcmax1j. f eLime () gc_,D--obabiIityO sess-ionunregistero

d.

The _________________ option enables session to automatically initialize if the session ID is not found in the browser request. a. b.
C.

session.start sessilon.autos-:--art session. session start session.session_ auto start

d.

Page 236 of 274

V 1.0 Oc 2004 Aptech Limited

Web Scripting with PHP

Sessi

n 18

WORLDWIDE

(AiPTECiir

S e s s i o n M an a g e me n t i n P HP

5.

The ____________________ specifies whether or not the cookies should be secured connections. a. b.
C.

session.cookiesecure session.secure session.secure connection session.use secure connection

d. 6.

controls the functioning of server, forms, and environment variables, a. b.


C. d.

register_globals uploads_tmp_dir session.controlvariables session.register_variables


I

Web Scripting with PHP

V 1.0 (g) 2004 Aptech Limited

Page 237 of 274

Obi ectives
At the end of this session, you will be able to:

Send e-mails Attach files with e-mails

Introduction
E-mail is a fastest way of communicating with people across the world. It takes only few minutes to send and receive messages as compared to the usual hand written letters. PHP provides the facility to send e-mail. In this session, we will learn how to send e-mail within PHP. We will also learn how to attach files with the e-mails.

19.. 1 SendingE-mail
In PHP; we can send an e-mail using the mail () function. To work with the mail () function, we need to specify the location of the current local mail server in the php.ini configuration file. The php.ini file is present in the /etc/php. ini location of the Linux operating system. Figure 19.1shows the contents of the php.ini configuration file. x
File Fdit View Search Tools Documents Help

New Open php.ini

Save Print Undohello Cut Copy Paste Find Replace

x-

[ n a i l f u nc t io n ] ; For Win32 only. SMTP -- localhost ; For Win32 only. sendinailfrom = ineZlocalhost. coin For Unix only. You may supply arguments as well (default: sendinail -t -1 11 ). sendmail_path = /usr/sbin/seiidinail -t 4

i
Lr. __01. 16
1N5

Figure 19.1 : php.ini Configuration File The above figure shows the mail function section in the php.ini configuration file.
Web Scripting with PHP V 1.0 ( q ) 2004 Aptech Limited Page 239 of 274

Sess~un 19

L1D W 1.0-E

Handling E-mail with PHP


The syntax for the mail ( ) function is:

mail(to, subject, message


Where,

[additi.onalheaders])

to Specifies the e-mail address of the recipient subject Specifies the subject for the e-mail message Specifies the message that is to be written in the e-mail. The body of the e-mail is
the message

additionalheaders Specifies additional information such the e-mail address of the


sender, and attachments

If the e-mail reaches to the recipient address, the control is passed to the statement following the mail () function. Otherwise, PHP displays the error message. For example, to send an e-mail using the mail 0 function:

<HTML> <BODY> <?php $to"john@bluemountain-com"; $from "tom@bluemountain.com"; $subject "Ilm example"; $body = "This is an example for show i ng the usage of the mail() function."; $send = mail($to, $subject, $body, $from); if($send) echo "Mail sent to $to 'address! else echo "Mail could not be sent to $to address!!!";
i ! 11;

</BODy> </IITML>
The mail () function is also used for sending mails to more than one recipient. A comma symbol is used for separating the e-mail addresses of the recipients.
V 1.0 Cc,~ 2004 Aptech Limited Page 240 of 274 W e b S c r i p t i n g w i t h PHP (,)

Session 19

rAJi:Pr,ECff WO R L D W I D E
Handling E-mail with PHP

For example, to send an e-mail to multiple recipients:


<HTML> <BODY>

<?php $to = "john@bluemountain.com, samson@bluemountain.com, jenny@bluemountad.n.com"; $from = "tom@bluemountain.com"; for($i=0;$i<count($to);$i++) { sto[sil trim(sto(sil); $subject = "An example"; $body = "This is an example for showing the usage of the mail() function."; $send = mail($to, $subject, $body, $from); if($send) { echo "Mail was sent to all the addresses!!!"; }}

</BODY> </,IITML>

In the above code, the mail ( ) function is used to send an e-mail. If there is any blank space placed in between two recipient's e-mail address, the mail () function removes it. A comma symbol is used for separating recipient addresses. In this code, the for statement is used for

reading the number of recipient addresses. Suppose we have stored all the e-mail addresses of the recipients in the text file. PHP enables us to read the e- mail addresses of the recipients from the text file and send an e-mail to them. For example, to send e-mail to multiple recipients whose addresses are stored in the multimail.txt file:
<HTML> <BODY> <-php

$ mu i ti /va /mul. Lima i I . Lxt o_ma i i f i 10 (5AT-1 -1 t i ) ; $from =-- " toi0bli-iemountain. com";
$ -C. 1

Web Scripting with PHP

V 1.0 C0 2004 Aptech Limited

Eifir2TECifOR

Session 19
Ha

O g0E W ro 11

dling E-mail with PHP

for ($ i = 0; $ i<C0U3'1t ($ tO_Ma 11) ; $ -i A- 4-) $to_ma_il [ $ i 1 = t r i m ( $ t o _ m a i l [ $ i 1 ) ; $to = implode(",",$to_mail); $subject = "A-n example"; $body = "This is an example for the mail() function."; mail($to, $subject, $body, $from); echo "Mail was sent to all the addresses!!!"; } </BODY> </HTML> In the above code, we have used functions such as the file () , trim () , and implode (). The file () function reads the e-mail addresses from the multimail.txt file. It stores all the e-mail addresses in an array. The trim() function removes the blank spaces inserted between the email addresses. The implode () function joins all the e-mail addresses in the array by separating each one of them with a comma.

19.2 Attaching Files in E-mails.


An attachment can also be sent with e-mail. An attachment is any file that we want to send along with the e-mail. An attachment file can be any simple text file, document file, or a graphics file. A file is attached with the e-mail by setting up the header.
For example, to attach a file with an e-mail: <HTML> <BODY> < ?php $file "/var/w%,,,,v,7/htlnl/exampl-e.txt"; $fp fopen($file,"r"); $content = fread($fp,filesize($file)); fclose($fp); //$file = chiink-split(base64_encodo($fi-le))$to $from $subject, "john@bluemountain.comll; "jenny@bluenlounuain.com"; "An example";

$mimeboundary - uni(lid(""); $header.= $from; $header.= $to;

Page 242 of 274

V 1.0 2004 Aptech Limited

Web Scripting with PHP

APYIECH

Session 19

44

OLDWIDE R

Handling E-mail with PHP Sheader.= "MIME-VERSION: 1-0\r\n"; $header.="Content-type: multipart/mixed"; $header.= "bounday,y=.\"".$mimeboundary."\""; $message.="This is an example for mail attachment.",$message.="\r\n\r\n"; $message.="".$mimeboundary."\r\n"; $message.="Content-type:text/plain;charset=\"iso-88591\ " \r\n" ;
V 1.0 ~P 2004 Aptech Limited

Page 243 of 274

$inessage.="".$mimeboundary."\r\n"; $message.="Content-Disposition:attachment;\r\n"; $message.="name=\"filename extn\"\r\n"; $message.="\r\n\r\n"; $message.=$file; $message.="\r\n\r\n"; $message.="".$mimeboundary."\r\n"; $ c o n t e n t = " < P > . $ C o n t e n t < / P > " ; $content=str_replace(chr(10i,"<P></P>",$content); $mail_send = mail($to, $subject, $body, $message, $header); if($mail_send) f echo "<BR><BR>Mail sent to $to address!!!"; } else echo "<BR><BR>Mail could not be sent Lo $to address!!!";

</BODY> < /17 T- L - I1 > In the above code, a boundary is created between the actual e-mail and the attachments. The boundary is created using the uniq d O function. The uniqid O function assigns a unique identifier to the original mail. The value of this function is assigned to the $mail_boundary variable. The content-type header indicates the type of the file that will be attached with the e-mail. The fo d en () function opens the file that is attached with the e-mail in the read mode. The f read() function reads the contents of the opened file. The base64 encode and chunk_split are the two built-in PHP functions. The ._)c1,.-.,c64_encode function is used for encoding the specified string. The function is used for splitting the data into smaller chunks. These two functions can be used in the codes for reading the file content. The basc64_encode() and c1-unk_,sp*1.it() functions are optional.

Web Scripting with PHP

AprIECM

Session 19

WORLDWIDE

Handling E-mail with PHP

)>

The mail () function is the inbuilt function of PHP that is used for sending mails By default the path for the local mail server is chosen while installing Linux in the machine If there is any blank space placed in between two recipient's e-mail addresses, the trim () function removes it The implode () function is used for joining all the addresses present in the array with a comma operator An attachment can also be sent with an e-mail by setting up the header of the mail function A boundary is created in between the actual e-mail and the attachment with the help of

the

() function

The uniqid () function assigns a unique identifier to the original mail We need to specify the type of messages that will be attached to the e-mail with the help of the content-type header

The chunk split ( ) function is used for separating the data into smaller portions The base64 encode () function is used for accepting the data in the form of a string and returns the data in the original form to the user

Page 244 of 274

V 1 . 0 Cc)

2004 Aptech Limited

Web Scripting with PHP

(A,PY-,FC,ff

Session 19

7" LOWIDE

CHECK YOUR PROGRESS


1 PHP uses the ___________ function for sending e-mails. a.
b-

implode () sendmail_from() mail() file()

C .
d.

The

symbol is used for separating recipient addresses.

C.

d.

3.

The trimo function removes ______________ from the recipient address. a. b. C. d. 4. The
a. b.
C .
d.

ascii character comma operator blank space wide space function joins all the e-mail addresses in the array.
file() trim -mail implode

Handling E-mail with PHP

5.

The boundary is created using the _____________ function.


a. file ()

b.
C .

uniqid trim ()
d.

i m pl od e .... ..... ..

Page 245 of 274 Web Scripting with PHP


V 1.0 2004 Aptech Limited

Session 19

WORLDWI-DE

AprECH

Harfd1ing E-mail with PHP


er
a re.......11110aMorairameiraryk

6,

The
a.

function opens the attached file in read mode. f read() implode() uniqid fopen()

bC.
d.

7.

The _________ function splits the data into smaller portions.


a. bC. d.

chunksplit(
fread()

base64_encode()
fopen()

Page 246 of 274

V 1.0 Oc 2004 Aptech Limited

Web Scripting with PHP

Objectives
At the end of this session, you will be able to:

Send e-mails Attach files with e-mails


The steps given in the session are detailed, comprehensive and carefully thought through. This has been done so that the learning objectives are met and the understanding of the tool is complete. Please follow the steps carefully. Part ~ - For the first 1.5 Hours:

20.1 Sending E-mails


PHP provides the facility to send e-mail. In PHP, we can send an e-mail using the mail ( ) function. To send an e-mail to the multiple recipients:

2. Enter the following code to create a form that accepts the recipient address, subject, and e-mail message:

<HTML> <BODY> <FORM METHOD "GET" ACTION "multiusers.php"> To: <INPUT TYPE "TEXT" NAME "to" SIZE = 60><BR><BR> From: <INPUT TYPE "TEXT" NAME "from" VALUE "jack@bluemountain.com" SIZE=60> <BR><BR> Cc : <INPUT TYPE = "TEXT" NAME "cc" SIZE 60><BR><BR> Bcc : <INPUT TYPE = "TEXT" NAME = "bcc" SIZE 60><BR><BR>

Subject:
<INPUT TYPE = "TEXT" NAME = "subjec t " SIZE = 60> <BR><BR> "6" COLD TS <TEXTAREA NAME = "mailbody" ROWS "50"></TEX'PAREA>
Web Scripting with PHP V 1 . 0 ` 2004 Aptech Limited Page 247 of 274

Session 20

WORLDWIDE

APMCCA?

Handling E-mail with PHP


<BR><BR> <INPUT TYPE

multiusers.htmi under .the:, /var/ww/htmi directory.

Enter the following code to accept the recipient address, , - subject, and
,

message:

Al

cc; for(.$i=O;$i<count($mailto);$i++) $mailto[$i] $mail_subject trim($mail_to[$i]); $GET['subject'];

N2

0"O'

$body = $_GET['mail body']; $confirm = mai-l($mail_to,$mailsubject,$bodv,$mailheader); if($confirm) echo "To: $mail_to &nbsp"; echo "From: $mail_from <BR><BR>"; echo "Cc: $mailcc &nbsp"; echo "Bcc: $mail_bcc <BR><BR>"; echo $body; echo fl<BR><BR>Mail Sent to all the e 1 echo "<BR><BR>Mail could not be sent!!!" addresses!!!";

Page 248 of 274

V 1.0 1* 2004 Aptech Limited

Wei) Scripting with PHP

Session 20

(APywcmWoa
LOWIDE

Handling E-mail with PHP

</BODY> < / HTML >

6. 7. 8.

Save the file as multiusers.php under the /var/ww4/htTn1 directory. Open the Mozilla Web browser. Type htt p ://localhost/multiusers.html ' - in the-Address bar and press the Enter key. The E-mail form appears, as shown in Figure 20.1.

Figure 20.1 : E-mail Form 10. Enter john@mail.com, jenny@hotmail.com, and samson@bluemountain.com as the recipient addresses. Enter Birthday Reminder as the subject. Enter the message, Wish you many many happy returns of the day H!, in the body. Click the SEND button. The output appears, as shown in Figure 20.2.

11. 12. 13.

Web Scripting with PHP

0 O 00 Elle edit ylew Go Bookmarks Tools Window Help

ptec

ted

age

9 o

Session 20 V..:

W 0A L D WIME

APFECAV

Handling E-mail with PHP : In: X


hn :1,1ocalhostimultiusers. Reload Stop Print **-Red Hat Network (:,~jSupporl EjjiShop (E jProducts dR- Training
,

File Edit .... ........ Bookmarks Tools Window Help View Go . . .......... Back Forward Home
1

To :john @ mail.comjcnn) @ hotinail.coiii.saiii-soiiC-lbluetiiouiitaiii.coiii From : jack (F-blueniountain.com Cc: l3cc Subject : Birthday Reminder Wish you many many happy returns of the day '!I

Mail Sent to all the addresses!!!

Lm t , Q "A*

ICI v

Figure 20.2 : Viewing the E-mail Information

20.2 Attaching Files. in E-mails


An attachment can also be sent with an e-mail. Attachment is any file that we want to send along with the e-mail. An attachment file can be any simple text file, document file, or a graphics file. A file is attached with the e-mail by setting up the header. To attach a file with an e-mail: 1. 2. Open the gedit text editor. Enter the following code to create a form for sending an e-mail with the attachment: <HTML> <BODY> <FORM METHOD

"GET" ACTION = "mail.pllp">

To: <INPUT TYPE "TEXT" NAME <BR><BR> From: <INPUT TYPE "TEXT" N11ME "jack@bluemounta-in-com" > Cc : <INPUT TYPE = "TEXT" NAME :

"to" SIZE=60>

"from" SIZE=60 VALUE=

"cc" SIZE = 60><BR><BR> Bcc

Page 250 of 274

V 1.0 2004 Aptech Limited

Web Scripting with PHP

Session 20

WO R L D'WO-D E

APBCj K,

Handling E-mail with PHP


<INPUT TYPE Subject: <INPUT TYPE Attachment: <INPUT TYPE <BR><BR> <TEXTAREA NAME "50"></TEXTAREA> <BR><BR>

<INPUT TYPE

Save the file as rnalLhtrnl under

$fp. fopeni($fi1'e""j'-,,#-k $content fread($fp,filesize($file)); fclose($fp); $to $GET['$to']; $ fr o m $GET['from']; $subject = $GET['subject'],$body = $GET['body']; $mirrieboundary = uniaid(""); $header.= $from; $header.= $to; $header.= $header.= $header.= $message. $message $message $message

"MIME-VERSION: 1.0\r\n"; "Content-type: multipart/mixed"; "boundary=\"".$l-ni-ineboundary."\".


="Urgent Requirement."; .="\r\n\r\n"; .="".$ir,i-meboundary."\r\ii"; .="Conten.t-type:text/plain;charset=\"3.so-8859n

1\"',\r\n";

$-m,e s s a g (-. ="". $iTtiiv.e_boundarv. Co n : ten t - Di snos i t i on: aa t t a c h m e n t ; $message name = \ . r., -, 1._-lename.extn\"\r\n'; $message $message - = " \ r \ n \ r \ n " ; .,f ile; $ --n C? s S a g C,
Web Scripting with PHP V
1.0

6. 2004 Aptech Limited

Page 251 of 274

S e s s i

n 20

W a-lit-Va W U.D*E

A PrEcAlff

Handling E-mail with PHP

$.content="< P>. $content.< Scontent=str.reiDlace(chr(IOi,"<P></P>",$co'ntent)

8. Type http://i66alhost/mail.html in ..the address bar and press the Enter key.,-., The form appears, as shown in Figure 20.3.

rF":-,-'.---,44'..t77:3r.,../:, e Edit View .0 Rookmarks Tools window Help 1 I!tjMorne : %fBookmarks "Red Hat Network !:ASupport rjShop CalProducts ATralrOng To:

From: Vack gblueniountain.com Cc: 1 13CC:rSubjeLt: I Attachnient: Foh.txt

SEND i

. .......... ... IYAI Of i

F i gu re 20.3 : E-ma il Form wi th the Attachment Field


Page 252 of 274 V 1.0 CcD 2004 Aptech Limited Web Scripting with PHP

Session 20
Handling E-mail with PH 9. Enter samson@bluemountain.com as the recipient address.

10. Enter An Urgent Opening as the subject. 11. Enter the message, Please check the job d&ahsAn -..the /var/ww/htm3-/Job.t-Xt file.
,

12. Click the SEND button. The output appears,.as-.,,shown in,.,Figure ;Q.4.
Mozilla

File Edit View Go Bookmarks Tools window Help --- --------Back Home Forward Not Reload Stop

)n

14 http:/Aocalhost/mail.php?tc~ -U~ '_%S.rch


-

0
i

Bookmarks **-Red Hat Network Ed Support EIShopAProd ts CATraJrgng uc

To : sam%onCd, bluernountain.com From : jack @bluemountain.com


Subject : An Urgent Opening Please check the job details in the /var/%v%%,Nv/htmLrJob.txt file.

The mail is sent to sa.mson@bltien)ountain.coni from jack 6)bluenw)untain.com.

Done

Figure 20.4 : Viewing the E-mail Information

Web Scripting with PHP

V 1.0 2004 Aptech Limited

Page 253 of 2

Session 20

WO R CD W I D'E

A P FECH

Handling E-mail with PHP

TRY IT YOUR SELF


Part II - For the next half an hour:

1. Send a picture file as an attachment to all your friends.

If

Page 254 of 274

V 1.0 0, 2004 Aptech Limited

Web Scripting with PHP

Objeedves
At the end of this session, you will be able to:
Explain the OOP concepts Explain inheritances Create classes Create constructors Create and use objects

Introductio
In object-oriented programming, programs are viewed as a collection of distinct objects. These objects are self-contained collection of data structures and functions and interact with each other. C++ and Java are the most common examples of object-oriented programming languages. In this session, we will learn how to create a class in PHP and how to derive a new class from a base class. In addition, we will also learn to create a constructor for a class.

21.1 - Object-OrientedProgram ym pung


In object-oriented programming, we not only define the data type of the data structure but also the type of functions that can be performed on the data structure. It combines the data and functions into a single unit. Such a unit is called an object. An object function provides the only way to access the data. The basic concepts of an object-oriented programming are: 'i,-Object - Consists of data structures and functions for manipulating the data. Data structure refers to the type of data while function refers to the operation applied to the data structures. An object is a self-contained run-time entity Class - Contains variables and functions working with these variables. A class has its own properties. An object is an instance of a class Abstraction - Process of selecting the common features from different functions and objects. The functions those perform same actions can be joined into a single function using abstraction Encapsulation - Process of joining data and objects into another object is called encapsulation. It hides the details of the data

Web Scripting with PHP

V 1.0 c) 2004 Aptech Limited

Page 255 of 274

Session 21

(APFECH
WORIOW W 1.0 E

OOP Concepts Polymorphism - Process of using a single function or an operator in different ways. The behavior of that function will depend on the type of the data used in it Inheritance - Process of creating a new class from the existing class. The new class is called the derived class while the existing class from which the new class is derived is called the base class iL21-.2

Inheritance

The process in which objects of one class acquires the properties of objects of another class is called inheritance. For example, the Lancer car is a part of the class Car, which is again a part of the class Vehicles. Inheritance means creating a new class with the help of a base class. A base class is also known as the parent class and a derived class is also known as the child class. A class is an object that contains variables and functions of different data types. The properties such as variables, functions, and methods of the base class are transferred to the newly derived class. We use the extends keyword for inheriting a new class from the base class. A derived class can also have its own variables and functions. The different types of inheritances are:
I>

Single Inheritance - Contains only one base class- The derived class inherits the properties of the base class. In single inheritance, the derived class works with the derived properties of the base class along with its own properties.

Multiple Inheritance - Contains more than one base class. The derived class inherits the properties of all the base classes. A derived class in this inheritance works with the derived properties along with its own properties. Hierarchical Inheritance - Contains one base class. In hierarchical inheritance, the properties of a single base class can be used multiple times in multiple subclasses. The derived class contains its own properties. It also uses the derived properties of all the base classes. Multilevel Inheritance - Contains one base class. The base class of the derived class can be a derived class from another base class. The properties of one base class are inherited to another base class and the derived class may become a base class for another derived class. Hybrid Inheritance - Uses the combination of two or more inheritances. This inheritance is normally a combination of multiple and multilevel inheritances. In PHP, multiple inheritances is not supported.
Page 256 of 274

V 1.0 2004 Aptech Limited

Web

Sess~cn 21

APFIC-ClAf
W O-R,L. 0 IMMO E

OOP Concepts

21-.3 Creating a
A class is a collection of variables and functions that operate on that data. A class can be inherited from a base class to create a new derived class. A new derived class uses all the properties of the base class including its own properties. The syntax for declaring a class is: class class nam var class-variable; function function-name{)

Where, class - Is the keyword used to declare a class class-name - Specifies the class name var - Specifies that the variable is not just an ordinary variable but a property class-variable - Specifies the variable name functon - Is the keyword used to define a function function-name Specifies the function name

The class definition is placed within the curly braces. The variables defined in the class are local to the class. A class can also use global variables. The variable inside a class is declared with the var keyword. The functions inside a class may use its own local variables or may use the class variables. For example, to create a class named OR .]Ddet.ail in PHP:

.Pl1p class a ss emodeta-il var $e7',11, i'&; var $empname; var V1-7,i' S-imodepart; -,.0 S'r)z) i:' el . d : . 1 )

-, e
~Y)

-inc

a onLer nD

Web Scripting With PHP

V 1.0

- 1 I-

2004 Aptech Limited

Page 257 of 274

(Al"WrIEC'Ar,

Session 21

-3~-

O:RL'VW-VD-R

s t p e c n o C P O
$this->e.mpcity=c:i-ty;

function enterdet($depart, $design) $this->empdepart=depart; $this->empdesign=design;

We have to save this file with an extension, .inc. This is because the file that needs to be included in the .php file must have the extension, .inc. In the above example, the enLeremp () and enterdet ( ) functions are user defined. These functions are defined in the empdetail class. These two functions are used for entering data of an employee. The enteremp ( ) function enters the employee id, employee name, and city. The enterdet () function enters the employee department and the designation. The this is a pointer that points to the object. Here the class variables are the objects of the class. The filename.inc file is included in, the filename.php file with the help of the include keyword. This is done in order to create an instance for the classes those are defined in the filename.inc file. The include keyword helps in including any type of file with the main file. The syntax to include a file in the program is:
include "i-iiename.inc";

A new class can be inherited from an existing class. The new class uses the properties of the parent class along with its own properties. The syntax for inheriting a new class is:
class newcless extends class name{ va2:- classvariable; function functionmine

Where,
ne--.-,,c.1.ass Specifies the name of the derived class extends Is the keyword used to derive a new class from the base class class name Specifies the name of the class from which the new class is to be derived

Page 258 of 274

Session 21
OOP Concepts For example , to de rive the net sa l a ry class from the salary c lass in PHP: <?php
class salary
r

function hra($basic) { $hra = $basic * 0.25;

function travel_allow($basic) { $La = $basic * 0.08;

function tax($basic) $tax = $basic * 0.05;

class netsalary extends salary function net($basic,$hra,$ta,$tax) return $basic i ($hra + $ta) $tax;

Save the above file with the name, salary.inc. In the above code, the n e r s a - l a n y class is derived from the base class, salary. The net. sa - lany class inherits the properties of the s a i , a r - , ' - c l ass . T h e n c t _ s a l a r y c lass us e s the f unc tion s de f in e d in the c l ass along with its own functions. and tax functions are the user-defined functions. The hra;%*! The hra(), travel__al low function calculates HRA from the basic salary of the employee. The trave~l_a' l low( ) function calculates traveling allowance from the basic salary of the employee. The Lax ( ) function calculates function calculates the net salary of the tax from the basic salary of the employee. The net the employee. 21.4 4Creating -a sConstructor ,t,

o,

. 4

A constructor is a special function that is a member of the class. This function has the same name as that of its class name. A constructor is called in the main program by using the new operator. We use the constructor t o initialize objects of the class of which it is a member. The constructor function is invoked whenever an object of the class is created.
scripting with PHP
V 1.0 20Vi Aptech

Limited

Page 259 of 274

I
TE CH Session 21
OOP Concepts When a constructor is declared, it provides a value to all the objects that are created in the class. This process is known as initialization. This allots a specific amount of memory to every object. The syntax for creating a constructor is:
class class nam var class variable; function constructor name(

Where, const ructor name

specifies the

name of the constructor.

For example, to create a constructor for the class named empdetail:


<?P?IP class empdetail. var $empid; var $empname; var $empcity; var $empdepart; function e=de f_- a i 1 ($ -i d,
$LIi s - >emp i d = i d;
$Z
nl`. s - > empri ar.',e = r am,7!;

$ 1-1 a-me, c 4L t Y, $deoart)

$t-lhis >eTr'PcIJ..V-c_Jt..Y; s - >enipdepar t= depa r-r; echo

Once the constructor is defined, we can call the constructor of the class using the nev .) operator. Before we call the constructor of the class, we need to include the file that contains the class. To call the constructor of the cmpaleta-ils class:
<?
p

hp
em,_'d e

include echo

t nc derails:
< fi T3

!--ew e!-, l P

",.J--

o hi -i

"T"roy", "I.1echarlical")

Page 260 of 274

V 1.0 Oc, 200A Aptech Urnited

Web Scripting with PHP

Session 21

ei?PrIECII LDWIDE
OOP Concepts

The new operator creates a new object of the empdetail class. It calls the functions that are defined in the empdetail class. For example, to call a constructor from the derived class

<?php class string function string() echo "This function is a constructor.";

function stringdispo echo "This is an example for constructor.";

class display extends string function displaystringo echo "This is a new class and a new function"; I

$disp $displ

new display; new string;

In this example, the display class is inherited from the string class. As a result, the display class uses all the properties of the string class. Here, the string() function of the string class is the constructor. As the display class is inherited from the string class, therefore the display class will behave as a constructor for the string class.

21.5

Creating and Using Objects

An object is a self-contained entity that consists of both data and procedures to manipulate the data. We use objects in programming because an object makes the codes easier to understand and are used for more than one time. It maintains the codes in the program. An object is an instance of a class. It gives a reference to the class. An object can be manipulated as needed. The new operator to initialize the object. There can be more than one object for a single class.

V 1.0 Oc 2004 Aptech Limited

Page 261 of 274

Web Scripting with PHP

6-1-PrECII

Session 21

OR L DWI WE

OOP Concepts The syntax for creating an object is: $objectname = new class name; Where, object_name Specifies the name of the object new Initializes the object class name Specifies the class name For example, to create an object for the class, usermail: <?php class usermail { var $username = "john"; var $password = "abc123"; function dispuser() echo "$username , $password";

class userdetails extends usermail var $secretquery = "favourite food"; var $answer = "chinese"; function dispdetail() echo "<BR><BR>$secretquery , $answer"; I

$mail $maill $displ $disp2

new userdetails; new usermail; $mail->dispdetail(); $maill->dispusero;

In the above example, the $mail object is created for the class, userdetails. The userdetails class is an extended class of the usermail class.

Page 262 of 274

V 1.0 @ 2004 Aptech Limited

(A_.~VFECH

Session 21

= L D-W I D E

OOP Concepts

In object-oriented programming, we not only define the data type of the data structure but also the type of functions that can be performed on the data structure The main concepts of an OOP are objects, class, abstraction, encapsulation, polymorphism, and inheritance A polymorphism is a process of using a single function or an operator in different ways A process of joining data and objects into another object is called encapsulation

A process of creating a new class from the existing class is termed as inheritance. Inheritance of a new class is done with the help of the extends keyword In hierarchical inheritance, the properties of a single base class can be used multiple times in multiple subclasses A class is a collection of variables and functions that operate on that data. A class can be inherited from a base class to create a new derived class A constructor is a special function that has the same name as that of its class name A constructor is called in the main program by using the new operator When a constructor is declared, it provides a value to all the objects that are created in the class An object is a self-contained entity that consists of both data and procedures to manipulate the data An object is an instance of a class. It can be manipulated as needed

Web Scripting with PHP

V 1.0 CO 2004 Aptech Limited

Page 203 of 274

Sessocn 21

W 0 8.W0 1W a 0 E,

00113 Concepts

1.

The process of selecting the common features from different functions and objects is known as _____________________ a. bC.

Inheritance Polymorphism Encapsulation.. Abstraction

d. 2.

The process of using a single function with its operators and variables in different ways is termed as ________________________ a. Abstraction Encapsulation Polymorphism Inheritance inheritance is a combination of multiple and multilevel inheritances, a. b.
C.

b.
C.

d. 3.

Hybrid Single Hierarchical Derived

d. 4.

The process of declaring a constructor is termed as a. b.


C.

declaration encapsulation initialization abstraction is a self-contained entity.

d. 5. a. b.
C.

Object Constructor Class Function

d.

Page 264 of 1/4

V 1.0 (c) 2004 Aptech Limited

Web Scripting with FHP

Ci-fprEcigt ORLDWIDE

Session 21

-1

s t p e c n o C P O

6.

An object is an ___________ of a class. a. b. C. d. entity reference instance constructor makes the codes easier to understand and can be used for more than one

7. An _________ time. a. b. C. d. 8. reference object instance constructor

A _________ inheritance contains more than one base class. a. b. C. d. multilevel multiple hybrid hierarchical

Scripting with PHP

Objecflves
At the end of this session, you will be able to > Create a class Create a derived class Create a constructor Create an object of a class
The steps given in the session are detailed, comprehensive and carefully thought through. This has been done so that the learning objectives are met and the understanding of the tool is complete. Please follow the steps carefully. Part I - For the first 1.5 Hours:

22.1 Creating a Derived Class


In object-oriented programming, we not only define the data type of the data structure but also the type of functions that can be performed on the data structure. It combines the data and functions into a single unit. Such a unit is called an object. An object's function provides the only way to access the data. A class is a collection of variables and functions that operate on that data. A class can be inherited from a base class to create a new derived class. A new derived class uses all the properties of the base class including its own properties. For example, to create a calculator:

P E I . , N A M E TYPE= 'r TE V1 NAME

Web Scripting with PHP

V 1.0 @ 2004 Aptech Limited

Page 267 of 274

Session 22

(A'PrECH \= LDWIDE
OOP Concepts

Calculate: <BR><BR> <INPUT TYPE T1PE RADIO NAME E - "RA',Dio,, -NAME= .tLb ~ ,NU . IPT
;

M u l t i p l i c a t i o nP U T " " ation. & .

Y-PE'

VALUE="DIVIS ION">Division <BR><BR>, ,INPUT TYPE "RADIO" .<INPUT TYPE -';v 0* <INPUT TYPE=AAbib, <BR><BR>" TYPE="SUBMIT"

Page 268 of 274

V 1.0 2004 Aptech Limited

Session 22

CP T E f f
LDWIDE

OOP Concepts
Page 269 of 274

the file as ''calculator Inc sunder .

$calculate $caiculate

new calculatoro; new ca~

$calculatel->subtracti6ii($first,$sedbnd); /,<BR><BR>"; 'The difference between $first & $seQond i:

Web Scripting with PHP

V 1.0 (D 2004 Aptech Limited

(A'~jPF,FCffg

Session 22

1-

L- D W 1 0 1E

OOP Concepts elseif($n3 ) $prod $calculatel->multiply($first, $second); echo "<BR><BR>"; echo "The product of $first elseif($n4) $div = $calculatel->division($first, $secoriO.", echo "<BR><BR>"; echo "The quotient for elseif($n5) .$pine $calqulate->sinvaluP1 echo "<.BR><1q)R5'"; echo "The sine::::. value

? r !

In this example, $calculate and $calculatel are the instances of the calculator and calci classes. The functions defined in these classes are called by using the class instances with the help of the '->' sign.

WO
?e ittpx'JN~aZo

VIN . ......

Irke A, i

PIUMMIM11

c c ow a n. h o s Tha d a m & t , eform" .mppears;-,as~.Aft- A

nonezaaaress

i - ar.; nagpress.m.,
~ 4X

Page 270 of 274

V 1.0 2004 Aptech Limited

S e s s i o n

2 2

(APr,FC,ff LO W I D E; OOP Concepts

Elie Edit view go Bookmarks rods Wndow L4elp h.,:Mocalhosticalculate.htral Back Forward Reload Stop Print
# ,-- ---

T~

] 40_5earch __________

*Bookmarks* Red HatNeNvorkC~~Support A Shop i:Vroducts 2jTrajrdng---Calculator


Fir. NunibLr: Second Number: Calculate:

Addition

Subtraction ( Multiplication Cosine (- Logarithm

Division

Sine
SUBMIT

, v

, 0 (V " Dli*

Figure 22.1 : Calculator Form


tlm--

ears ,0 ,'a" -.

ma c

Figure 22.2: Displaying the Result for

Division

..,.Click the Go. -erect


the

Back hyperlink. Enter the value forthe.first number as 47

1 T Cli k h l
Web Scripting with PHP o e g a V 1.0 2004 Aptech Limited o a

bt

(APPLD, EW

Session 22
OOP Concepts
J~n lix

Elie

Edit View Go Bookmarks Tools Reload Stop

Window Help

http:Mocalhost/cal Back Forward

&A_Search

CA Print
I

_4 Home 4Bookmarks

Red Hat Network (:,ASupport QjShop (~Products ~Tralninq

The cosine value of 47 is: -0.99233546915093 Go Ba c k

-A, LZI - / 1 90 ( 0 ~ Do ne

Figure 22.3 : Displaying the Cosine Value

22.2 Creating a-Construdtor.


A constructor is a special function that is a member of the class. This function has the same name as that of its class name. A constructor is called in the main program by using the new operator. We use the constructor to initialize objects of the class of which it is a member. The constructor function is invoked whenever. an object of the class is created. When a constructor is declared, it provides a value to all the objects that are created in the class. This process is known as initialization. This allots a specific amount of memory to every object. For example, to display the odd numbers in the reverse order using the constructor:

Page 272 of 274

V 1.0 C 2004 Aptech Limited

Web Scripting with PHP

Session 22

fIPTECIIO

RLDWIDE

OOP Concepts

In this example, oddnum is the user-defined class. This class has a function named, oddnum. The oddnum function is the constructor of the oddnum class.

3. Save the-;file as construct.inc under the:./var/WW/"`-hOpen a new file in theVedit text editor.' odd "order iiu rn W94 e- .Teve&i% r -

The new operator is used for calling the oddnum constructor. It is assigned to a variable x. The variable x is created as an object for the oddnum class.

Open the Mozilla Web br mser,ti,


Type nttp*. 71ocalh C.

Enter key. The OUPUL:a- 'Wears, 4 :aTv

File Edit View Go Bookmarks Tools Dndow Help hlp-14ocalhosticonstructor.plp 11F,;_~,;;rch] Back Forward Reload stop . Print f, ,Home 13ookmarks.**---Red Hat Netwoik Asupport [;Shop (6, Products ZITralning
Displaying odd numbers in reverse order
1.

_T

i Mp.

19 17 15 13 11 9 7 5 3

_115L1z1-~/_ M04 G9_ I Dorte

Figure 22.4 Displaying Odd Numbers in Reverse Order


V 1.0 2004 Aptech Limited

Web Scripting with PHP

Session 22

WORLDWIDE

OOP Concepts

TRY IT-YOURISSELF 1-Part II - For the next half an hour: 1. Create a class named Circle with a function that calculates the area of a circle. Derive another class from the Circle class. Create a function that calculates the circumference of i the circle in the derived class.

Page 274 of 274

V 1.0 2004 Aptech Limited

Web Scripting with PHP

Abstraction Process of selecting the common features from different functions and objects Arithmetic Operators Performs mathematical calculations Array Variable that can store a list of values. Array Identifier Enables us initialize value of a specific element in an array. arsort Function Similar to rsort() function that can sort both associative and indexed arrays Assignment Operators Enables us to set the operand on the left side to the value of the expression on the right side Associative Arrays An array where the index type is string

Bitwise Operator Operates on the bits of an operand. They are similar to the logical operators- They work on smallscale binary representation of data. Boolean Data type stores one of the two values, true or false
Web Scripting with PHP V 1.0 C 2004 Aptech Limited Page i

Ef A T CI R D I E P E IO L WD

Giossary
Glossary
Break Statement Stops the iteration of the loop from the current loop execution

AP-5111h %MP
Class Contains variables and functions working with these variables. It is an object that can be inherited from a base class to a derived class. It has its own properties. Constants Identifiers that contain values that do not change as the program executes. It has a global scope of existence. Constructor Special function that is a member of the class. This function has the same name as that of its class name. Continue Statement Used for breaking the iteration of the loop from the current loop execution Cookies Enables Web site stores user information on the hard disk of client system

Database Used to store the data. A database is connected to establish the database properties to the Web sites. It is done with the help of a data source name. Database API Enables developers to write applications that are movable or easily accessible between the database products

Page ii

V 1.0 2004 Aptech Limited

Web Scripting with PHP

(APJr,EC,ff

Glossary

woRtowIae

y r a s o l G

Date and Time functions Enables us to find the date and time on the system. Decrement Operator Decrease the value of the operand by one

Else Statement Executes a block of code when the specified condition is false. It is used along with i f statement. Elseif Statement Optional clause that allows testing alternative conditions. It is executed before the else statement and is used along with if statement. Encapsulation Process of joining data and objects into another object. It hides the details of the data. Environment Variables System-defined variable. It gives information about the transactions held between the client and the server. Error handling functions Enables to define the error handling rules. Exit Statement Used to break the loop while the loop is in the execution process. ( a Floating-point Data type that stores floating-point numbers.

Web Scripting with PHP

Glossary

E4 P E A O L WD 7 C TRD I ' E

Glossary
For Loop Executes a set of codes repetitively for a specified amount of time. In this, the counter variable is declared in the loop itself and is used for checking the specified condition. Form Provides an interface for the client and the server to interact with each other

43
GET Method Specifies the Web browser to send all the user information as part of the URL. Global Variables Retains its value throughout the lifetime of the web page.

a
Hidden Similar to the text field. The difference is that the user cannot view the hidden field and its contents. Hierarchical Inheritance

HTTP
I

HTTP is a Hyper-Text Transfer Protocol. This protocol is a network transmission protocol. HTTP protocol is used with the help of TCP/IP protocol. Hybrid Inheritance

multiple and multilevel inheritances. Ihriahn,eoeoigacsnud ut em niremenp rrsrchabeo ac bao ecnit t r o il ss i i mto n y n o I . a c b s e p i t l Uaolbac o tehn.lshnsr yli st f scc ir e oisnbTineen lam in ehi n o r ei e eacrce le i o s t hmnt s t smimi u h i t ae t af pf a e a p n ow

Page iv

V 1.0 CU 2004 Aptech Limited

(A"PirrCM

Glossary

W O R L D - W

Glossary

a
Identifiers

Names given to various elements of a program such as variables, constants, arrays, and classes in a program
If Statement Executes a block of code only when the specified condition is true

Increment Operator Increase the value of the operand by one Indexed Arrays An array where the index type is integer. Inheritance Process of creating a new class from an existing class. Integer Data type that stores numbers without decimal points. The value ranges from -2,147,483,648 to +2,147,483,647.

Local Variable Variable that is initialized and used inside a function. The lifetime of a local variable begins when the function is called and ends when the function is executed. Logical Operator Enables us to combine two or more test expression in a condition. They evaluate expressions and return a Boolean value.

Web Scripting with PHP

V 1.0 2004 Aptech Limited

Page v

Glossary
Glossary
Y.

Loop A loop is executed depending on the return value of the testing conditions by testing it- The return values are true and false.

Mathematical functions Mathematical functions operate on numerical data. Multidimensional Arrays Stores one array within another array Multiple Inheritances Contains more than one base class. The derived class inherits the properties of all the base classes.

Non-Persistent Cookie Cookies that are deleted from the Web browser as soon as the user exits the browser

Objects Used for any object reference. An object is an instance of a class. OOP A programming language model that is made up of objects and data. Objects can be manipulated as needed.

Web Scripting with PHP

Operators Pre-defined symbols that allow performing specific actions.


Page vi V 1.0 2004 Aptech Limited

(A,pr,Ecjv

Goossary

\ WORLDWIDE

Glossary

Persistent Cookies Cookies that exist in the Web browser for a period specified at the time of its creation. PHP PHP stands for PHP - Hypertext Preprocessor. It is a scripting language used for developing dynamic Web pages. PHPEd Has an integrated development environment for PHP. This tool helps a developer in developing applications by supporting PHP scripts and its syntaxes Polymorphism Process of using a single function or an operator in different ways. The behavior of that function will depend on the type of the data used in it. POST Method Specifies the Web browser to send ail the user information through the body of the HTTP request

Relational Operator Compares two operands that determine the relationship between operands Rsort Function The rsort ( ) function sorts the element values in the descending alphabetical order.

Scope of Variables The scope of a variable is the portion in the script within which the variable is defined. It indicates the lifetime of a variable.
V 1.0 rD 2004 Aptech Limited Web Scripting with PHP Page vii

rAJ:PTECH

Glossary

ORLDWIDE

Glossary Session

Refers to the time the user accesses information on a particular Web site
setcookie Function

Generates the cookie header field that is sent along with the rest of the header information
Single Inheritance

Contains only one base class. The derived class inherits the properties of the base class
sort Function

Arranges the element values into an alphabetical order


Static Variables

Retains its value even after the function terminates. The static variable is used in the recursive function.
String

Data type that stores a set of characterAhose are enclosed within single quotes or double quotes
String Functions

Operate on character type of data.


String Operator

Operates on character data. It is used concatenate character strings.


Switch Statement

Checks single variable against multiple values and executes a block of code based on the value it matches.

Page viii

V 1.0 2004 Aptech Limited

Web Scripting with PHP

Glossary
y r a s o l G

Ternary Operator Also known as conditional operator, simplifies complex conditions into one line statements Time Function 'Jeasures time in the number of seconds from ls' January 1970 00:00:00 GMT

0
UNIX Timestamp &gnifies the time and date that the time() function returns URL . URL is a Uniform Resource Locator. The URL locates the addresses of the resources on the Ddd Wide Web.

0
.P'#'hile Loop

::..`es loop statements depending on the return result of the testing condition after testing it. s loop is used for displaying the contents of the table of MySQL database.

th PHP

You might also like