web scripting with php

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 Definin g . 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. V 1.0 (9 2004 Aptech Limited Page 153 of 274 'Neb Scripting with PHP

Upload: mohaif

Post on 23-Oct-2014

102 views

Category:

Documents


24 download

TRANSCRIPT

Page 1: Web Scripting With PHP

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.

V 1.0 (9 2004 Aptech Limited Page 153 of 274 'Neb Scripting with PHP

Page 2: Web Scripting With PHP

6 WIDE

Session 13 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 value, [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', `HR' , 4

value)

Page 154 of 274

Page 3: Web Scripting With PHP

.'.,-eb Scripting with PHP V 3.0 C) 2004 Aptech Limited

s e s s i o n 1 3

~_~AprIE0 R L O W I D E

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] "element—value";

Where,

arry—name - 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

Page 155 of 274

Page 4: Web Scripting With PHP

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

I 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= "Finance"; $department[11= "Sales"; $department[21= "HR"; $department[31= "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 Finance 1 Sales 2 HR 3 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 5: Web Scripting With PHP

.:) Scripting with PHP V 1.5 CO 2004 Aptech Limited

(A—PrECM

Session 13 ~= 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, con ta ins va lues such a s Advertising and Marketing. To merge ITdept and SalesPurchasedept, use the following code:

<?php

$ I T d e p t = a r r a y ( O = > " T e s t i n g " , 1 = > " T r a i n i n g " ) ; $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 function, as shown in the following code:

$AdminDept = arraymerge($SalesPurchasedept, $ITdept); echo "\$Ad-TninDept[O] = ", $ AdminDept[O],-

In t he above code sn ippe t , we have changed the o r de r o f t he a r ray s ' spec i f i ed i n the array_merge ( ) function. The output for this code snippet would be, $AdminDept [ 0 1 Advertising. I

Page 157 of 274

Page 6: Web Scripting With PHP

Eil-PFECH WORLDWIDE

Working with ArraysSession 13

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,

$array–name – 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 key ind ices such a s USA, England, Australia, and Neva E a c h a r r a y e l e me 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"'

Page 7: Web Scripting With PHP

7_-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:

ze-moloyee_det = array( "Joe Brown" => array(

1 "$100", 2 "$150", 3 "$100", 4 "$160", 5 "$250", 6 -$148-),

"Todd Martin" => array(

1

2 3 4 5

6

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

"$180","$195","$200","$130","$280",

" $ 2 1 . 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 f ifth 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

Page 8: Web Scripting With PHP

(A—Precm

WOR LDWIDE S ess ion 13Working with Arrays

13.5.1 sort () Function

PHP enables us to sort an array based on the element value. The sort function arranges the element values into an alphabetical order.

The syntax for the sort function is:

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 Finance 1 HR 2 Purchase 3 Sales

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 Sales 1 Purchase 2 HR 3 Finance

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

Page 160 of 274 V 1.0 ©2004 Aptech Limited Web Scripting with PHF

Page 9: Web Scripting With PHP

Session 13

~PTEC'/SiWORLDWID

Working with Arrays

13.5.3 arsort 0function

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

The syntax for the arsort function is:

arsort(ArrayName)

For example, to apply arsort on the array, country, use the following code snippet:

arsort($department);

The above code snippet instructs PHP to modify the array, as shown in the following output.

1 Sales 3 Purchase 2 HR 0 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 : Othe r Funct ions Re la ted to Ar rays

Page 10: Web Scripting With PHP

Function Name Description count H

Indicates the number of elements in an array sizeof Indicates the number of elements in an array. We can use this function instead of count() () Keeps a count of the occurrences of same element values in an array. It returns the number of occurrences of same element values array _flip o

Converts the element values to index values and index values to element values array _intersect o Identifies and returns the common element value among a group of arrays () Displays all the key indices of the specified array array —reverse o

Reverses the order of the array elements () Rdturns and removes the first element of an array () Identifies whether or not a given key or index exists in an array array —pusho Adds one or more elements to the end of an array array pop o

a Scripting with PHP V 1.0 © 2004 Aptech Limited

Session 13Et.i117FECHLOWtOE

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:

$ d e p t = a r r a y _ f l i p ( $ d e pa r t m e n U ) ;

After using the array_f lip () function, the department array will be as follows:

F inance 0 S a l e s 1 HR 3 Purchase 3

To reverse the order of elements of the department array, enter the following code:

$dept array_reverse($department ) ;

After using the array—r eve rse ( function, the department array will be as follows:

0 Purchase 1 HR 2 S a l e s 3 F inance

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

• To remove an element value from the department array, enter the following code:

array_pop ($departizient) ;

After using the array-pop ()function, the department array will be as follows:

0 F inance 1 S a l e s 2 HR

To add an element value to the department array, enter the following code:

a r ray_push ($de p a rUr i en t , "Marke t ing " ) ;

After using the array—push ( ) function, the department array will be as follows:

0 F inance 1 S a l e s 2 1 1 R

3 Purchase 4 Marke t ing

Page 162 of 274 V 1.0 ©2004 Aptech Limited Web Scripting with PH:

Page 11: Web Scripting With PHP

Session 13

(A—PrECH\1WORLDWIDE

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

Working with Arrays

V 1.0

Page 12: Web Scripting With PHP

Session 13 ~PTE'CH 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

Page 13: Web Scripting With PHP

Page 13 of 274

.:;Sion 13 Working with Arrays

;1~11

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

a. array f u n c t i o n

b. array identifier

C. count() function

d. sort function

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

a. arrayO function c. array identifier

C. count() function

d. sort() function

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

function.

a. array_merge()

b. merge —array o )

C. array–combine( )

d ( The order

function arranges the element values into an alphabetic ascending

a. arsorz()

b. ksort

C. sort ()

d. asort

function keeps a count of the occurrences of same element values in an array. a- array–count(

b. count()

C. count –values o )

d. array_count–valueso

i

I

I

14*b Scripting with PHP V 1.0 © 2004 Aptech Limited

Page 14: Web Scripting With PHP

Page 14 of 274

Session 13Working with Arrays

Elf:PFECII— WORLDWIDE

6 function identifies the common element value among a specifiedgroup of array.

a. array --intersecto

b. array—merge{

C. array—group(

d. array—count—values(

7.

a. array_intersect_keys()

b. array_keyso

C. array_key_exist()

d. array_count:_va1uesO

functionreturnsallthekeyvaluesofanarray.

Page 15: Web Scripting With PHP

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. Thishas been done so that the learning objectives are m6t and the understanding of the tool iscomplete. Please follow the steps carefully.

Part I - For the first 1.5 Hours:

14.,JIJI &Iftift-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. Thenumber of key value pairs in the arrayo function determines the number of elements in anarray. 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. Open the gedit text editor.

2. To create an array named lang, enter the following code: <?php

$ l ang = a r r ay 1 = > - "VB" , 2 = > " J a v a " , 3 = > " P e r l " , 4 = > " P H P " , 5 = > I ' V c + + — , 6 = > " . N E T " , 7 = > " D e l p h i " )

,Veb Scripting with PHP V 1.0 © 2004 Aptech Limited Page 167 of 274

Page 16: Web Scripting With PHP

AP -T IECA- i l l -W Z ALLD W 4-0-4E

Page 16 of 274 V 1.0 Cc 2004 Aptech Limited Web Scripting with PHP

Session 14

Working with Arrays

,6w It'd M ,

6 -he'rArM 00-Mb store it in -a - varnts in t f

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

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

ew Open Paste 0 n~ Save Nnt Undo Redo Cut , C6py P 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 17: Web Scripting With PHP

Sessuon 14 APTECH

waa~ow1ae

Working wi th Arrays

P u n d e r v a r /

6. Open the Mozilla Web browser.

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 Ids' X

Page 169 of 274 Vi

Page 18: Web Scripting With PHP

Session 14 _ __________________________________________ Working with Arrays

After entering the code, the PHP file appears as shown in Figure 14.3.

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

4e2mts count ($1ang),;

fangiarray.,along.~ h th-jr.respecti B isplay',all: he values h e . . , v e d e x , v a l u e s ,

enter the following code;

f o r ( $ i t em =O ;

Untitled (modified) gedit —jfq!~_ tq~ -

<?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 /var/www/html directory.

Open the Mozilla Web browser.

Page 19: Web Scripting With PHP

zz Scripting with PHP

Session 14 C®rte« wonLowIoe

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.

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 indexedarrays and associative arrays.

Suppose we have two arrays, such as $serveros and $applicationOS that contain names ofthe operating systems. To combine the element values of these two arrays into one, we must usethe array_merge function.

File Edit View Go Bookmarks Tools Window Help

http:/Aocalhostfmylanlv LASearchl Back Forward Reload Stop Print

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

O V B I Java 2 Per] 3 PHP 4 VC++ 5 .NET 6 Delphi

1-*-Idl offilmawaffigm

Open the gedit text editor.

To: create . arrays named $serveio a n n n a t e r the fo l lowing s,,:and 1$applic ti PHP code:

?php

=> "Windows. NT", - 1 => . "Windows 2000".."Windows 2003");

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

Page 20: Web Scripting With PHP

zz Scripting with PHP

Sess~ n 14 (,-4PY-,EC,M = LMW I'DE

Working with Arrays

Web Scripting with PHP

logo*##94Wray, enter the

Page 21: Web Scripting With PHP

Scripting with PHP V 1.21 Cc) 2004 Aptech Limited

Working with Arrays

Page 173 of 274 echo, -$rec[keyl $rec[valuel

X -

echo -<br>-;

sN;

Save -.'the'. fi I ` 'op~ i e-as:

~' §pt.pqj&~ der -the recto

n on ht

Home 51i[440~ toduels~~Server Operating systems

0 Windows NT 1 Windows 2000 2 Windows 2003

Merged array of g Systems Operatin

Windows NT 1 Windows 2000 2 Windows 200

3 Windows 95 4 Windows 98

5 Windows ME

http./Aociilhostjop -Ij I&*, Search Back jWoad S t op

Application Operating systems

1 Windows 95

2 Windows 98 3 Windows ME

Q

Figure 14.5 : Content of the individual and Merged Arrays

1 4 . 4 U in, g Multidimen n s i on a l A r r a y

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

Page 22: Web Scripting With PHP

A P rECITIWOWk, D W I'D -9

S e s s i o n 1 4

Page 22 of 274 Web Scripting with PHP V 1.0 © 2004 Aptech Limited

I - APTECK Session 14

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:

O f i e g e d i t text editor. P '1

Enter the following code to -create:

'%ff6i 1 0:

"Grade-; "Gender" => "Female"),

".Luce - 'GrAc.

lace .'d 0

004 => array( "Name" => "Jack Thompson", "Email" => "[email protected]", "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 23: Web Scripting With PHP

A P Y"ECHW01A vo IW I DIE Session 14

Scripting with PHP V 1.23 Cc) 2004 Aptech Limited

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

V untitled I

Elie Edit View Search Tools p o c u m e n t s Eelp

ID t: [q 9 New Open Save Print Undo Redo Cut Copy Paste Find Replace

Urvided 1• •

$total—elint = 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 N

Figure 14.6 - Displaying Contents of the Multi-dimensional Array

v mozilla ;•x

Figure 14.7 : Viewing Contents of the Multi-dimensional Array

• Sle Edit Ylew Qo Rookmarks Iods Window _B & 4 S ~ ;-:~ , 31 ! ,& hI,,:j0..host/swdemDN.php *_Search G4

Back Formel Reload Stop - Print !,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 t

Grade : 13+ Gender: Male

-j-_ L.1 ~~ LA) (V I Done —1 .1 ............

Page 24: Web Scripting With PHP

W0::RLDWVD:E

Session 14

Page 24 of 274 Web Scripting with PHP V 1.0 © 2004 Aptech Limited

Working with Arrays

.1 4.5-:'Sorting -

PHP provides us with various functions, such as sor t r so r t and arsort that enables us to sort the element values of an-array.

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

$i<$total_elmt;.for($i=0;

echo echo

$rec = each ($lang)-echo "$rec (key] 6 c [value]echo "<br>";

echo "<br>"; To sort. the $immcr array inthe alphabetical

w . , "qr,,.:.~enter, 777 hefoIIO.wiing~, code ~-iin the P H P s c r i p t :

sort ($1axit'r)

The PHP file appears, as shown in Figure 14.8.

Page 25: Web Scripting With PHP

Scripting with IHP

Sess ion 14

(A—PrEcm0 R'L D W I VE

Figure 14.8 : Sorting the Array Alphabetically

fn rxE l i e E d i t V i e w S e a r c h g o d s D o c u m e n t s H e l p

New Open Save Print Undo Redo Cut Copy Paste Find :Replace

Untitled I* x

<?php Slang = array(

1 => "VB", 2 => "Java", 3 => "PHP", 4 => "Delphi",);

$total—elmt = count($lang); echo "Original array"; echo "<br>";

for ($i=0; $i<Stotal—elmt; $i++)

$rec = each($lang); echo "$rec[key] $rec[value] echo "<br>";

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

~ " M A W ~ ~ I M I N J ' /

5. To display all the: .- elements of. --,`tKfIIani'g 4rrayi, e prItIh§, th ',Viriray en er-W , e n t e r t h e

following code:

for($i=0; $i<$tota1–e1mt; $i++)

$rec = each($lang); echo "$rec (key] $rec [value]"; echo "<br>";

6. Save the file as modLang.php under the jv6tjww/htxnI dIfW ry.

7. Open the Mozilla Web browser.

8. 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.

Page 26: Web Scripting With PHP

I Web Scripting ,: :- = Page 26 of 274 V 1.0 @ 2004 Aptech Limited

Session 14 rA—Pywcm 11WOR VDW11-0Z

Working with Arrays

'i Ble Edit Mew . Go pockmarks Tools Vindow HelpIt F h 1v

I - F :..A.ack Forward Reload Stop

C-4 , Print

jp-Search

j Home 1( 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

Figure 14.10 : Sorting the Array in the Descending Order

Tqoj.ried) - gedit

R i i Edit olk I Bids ew

UT41 - f - d

Save Open e IPrint 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

Page 27: Web Scripting With PHP

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

4- s h 6 ,-the s000 ar i

r a y 4,. . . ~

Zg 0~gure pp e p g -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 El l e Ed i t View Go Bookmarks Tools window Help

Page 28: Web Scripting With PHP

Page 28 of 274 V 1.0 Ccj 2004 Aptech Limited Web Scripting with PHP

Session 14(A—PT.PCH

7" LOWIDE

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:

Working with Arrays

TRY IT YOURSELF - I

Page 29: 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

Web Scripting with PHP V 1.0 Cc 2004 Aptech Limited Page 181 of 274

Page 30: Web Scripting With PHP

Session 156-4py-'Ecm

D W " L D W

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 mysql–connec 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 = mysql–connect("host–name","user–name","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 I .

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 r-:z password.

15.2.2 Working .with the

Before we start to work with the database, we have to establish a connection with the MySC-server. 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_1ist–dbs($1ink_id);

Where, link_id specifies the return value of the connection.

Page 31: Web Scripting With PHP

Session 15 (A—Pr,ECJV

W O R L D W I D E 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 = "";

$connect—mysql = mysql—connect($server, $username, $password);

$db_list = mysql—list_dbs($connect—mysql); 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 $db—list variable.

mysq1_se1ect_dbO —Sets the specified database as the current database.

The syntax for the mysql—select_db() function is:

mysql—select—db("database_name", $link_id);

Where,

• database_name — Specifies the database name • link—id — Specifies the return value of the connection

For example, to connect to the MySQL database:

<?php

$server $username "root"; $password

$connect m sql mysql_connect($server, $username, $password); — Y I

$mysql—db = mysql—select—db("mysql", $connect—mysql);

if(!$inysql_db)

d i e C onnec t i on failed"); } else

Page 32: Web Scripting With PHP

Oft-LDWI•E Session 15

Page 32 of 274 V 1.0 Ccj 2004 Aptech Limited Web Scripting with PHP

Handling Databases with PHP

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 mysql–list–tables ( ) function is:

mysql_list_tables("database–name", $link_id);

Where,

database name– Specifies the database name link–id — 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("inysql", $connect–mysql);

it(!$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 themysq.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 33: Web Scripting With PHP

Web Scripting with PHP

Session 15 ('APr,FCM

11~w" LOWIDE

Handling Databases with PHP

The syntax for the mysal—num—rows ( )function is-,

mysql–num–rows("table–name");

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";

$connect—mysql = mysal_connect($server, $username, $password);

$row_num = mysql—num—rows("user—contact");

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 function.

The syntax for the mysql__close() function is:

mysql–close($link_id);

Where, link_i d specifies the return value of the connection

For example , to access the MySQL database :

V 1 . 0 C c , 2 0 0 4 A p t e c h L i m i t e d Page 185 of 274

<?php $se.rver

Page 34: Web Scripting With PHP

Web Scripting with PHP

Session 15(4,-;]7PECif

L D W A O - E

Handling Databases with PHP

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 mysql–list–tables() function is:

mysql_list_tables("database–name", $link_id);

Where,

• database–name – Specifies the database name • link–id – 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.

Page 35: Web Scripting With PHP

,",'eb Scripting with PHP

Session 15

(A—PY-ECMWORLDWORLDWIDE

Handling Databases with PHP

The syntax for the rnysal—num—rows ( )function is:

mysql—num—rows("table—naiiie");

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 "rooL"; $password 11 It ;

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

$row_num = mysql_num—rows("user—contact");

if(!$row_num)

echo "Table does not contains any data"; exit;

else

echo "Row number $row_num"; I

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 mysql—close () function.

The syntax for the mysql—close function is:

mysql—close($link_id);

Where, link—id specifies the return value of the connection

For example, to access the MySQL database:

<?php $server

Page 36: Web Scripting With PHP

Page 36 of 274 F -

ARTECAWWO R LDWIDE Session 15

Handling Databases with PHP

$username = "root"; $ p a s s w o r d = " " ;

$connect_mysql mysc i l -connect ($server , $username, $password ) ;

$ t a b _ l i s t r c t ysq l _ l i s t _ tab l es ( "mysq l " , $connect -mysq l ) ;

i f ( ! $ t a b _ l i s t ) f

e c h o " D a t a b a s e d o e s n o t c o n t a i n s a n y t a b l e " ; e x i t ;

e l se

$row-nuin = roysq l_num_rows($tab_ l i s t ) ; I i f ( !$row_num)

e c h o " T a b l e d o e s n o t c o n t a i n s a n y d a t a " ; e x i t ; I e l se

echo $row_num;

mysql_c lose ($connect_mYsql ) ;

echo "Connect ion i s closed";

15.3: Data - Access

PHP provides us with the fol lowing funct ions for accessing data f rom the database:

mysq1 query 0- Executes MySQL query for re t r iev ing da ta f rom tab les . Thi s func t ion sends queries to the act ive database . The MySQL commands such as SELECT, SHC-.•, - , EXPLAIN, and DESCRIBE works with this function

The syntax for the irvsql_query( )function is :

inysal_query(querv, link-id);

Where,

• query — Specifies the MySQL query.

11, ink—id — Specifies the return value of the connection

Page 37: Web Scripting With PHP

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

Page 38: Web Scripting With PHP

Page 38 of 274 V 1.0 C 2004 Aptech Limited Web Scripting wi-. _-= -

Session 15

Handling Databases with PHF

To display the records of the table from the USER database, enter the following code:

<?3Dhp $server $username $

1 11 ;

"root";11 if ;

$connect–mysql = mysql_connect($server, $username, $password);

if($connect–mysql) f

echo 'Connection established"; I else

die("Unable to connect");

$mysql–db = mysql–select–db(-USER");

if($mysql–db)

echo "Connected to the database"; I else

die("Unable to connect to the database"); I $sqlquery = mysql.-query ("SELECT FROM user–contact;");

while($row = mysql–fetch–array($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 39: Web Scripting With PHP

Field Name Data Type Constraint USER ID INT NOT NULL PRIMARY KEY USER—NAME CHAR(25) NOT NULL USER—EMAIL—ID CHAR(25)

.39.9b Scripting with PHP V 1.0 Oc, 2004 Aptech Limited

Session 15

C4-PTIECII 1 1

R LOM IV 6

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 USER—CONTACT in the USER database with the following fields:

Table 15.1 : user contactTable

To create a table using the SOL commands in PHP:

1. Open the gedit text editor.

2. Enter the following code:

<?php $server $username $password

U " ;

"root";

$connect—mysql = mysql—connect($server, $username, $password);

if($connect_inysql)

echo "Connection established";

else

die("Unable to connect");

$mysql_db = MYsql_select_db(,'USER");

if($mysql—db)

echo "Connected to the database"; el

se

die("Unable to connect to.the database");

Page 40: Web Scripting With PHP

Page 40 of 274 V 1.0 --P 2004 Aptcch Limited Wet.) Scripting with PHP

Wamllulb?. lam

Session 15 Handling Databases with PHP

$ sq l – t a b l e = "CREATE TABLE USER – CONTACT(".-USER –ID INT NOT NULL PR1M:L!.RY KEY,-."USER–NAME CHAR(25) NOT `d LL, "-"USER–EYLAIL–ID CHAR(25)".

if(jnysq1–query($sql–table))

echo "Table is created"; }

else

die("Unable to create a table");

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. Save the file as mysqltable.php under the, /var/www/html directory.

4. Open the Mozilla Web browser.

5. 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

http://loci v Search Back Forward Reload Stop I Print

!jHorne 'jBookmarks 4*f S upport "' C Products ;' Shop ~~ QTrainl Red Hat Network (: L 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 41: Web Scripting With PHP

.'.-41b Scripting with PHP

Ei-PTE-C 0 R V WWA DA

Handling Databases with PHP

To insert records in the USER CONTACTtable:

< ?php

$server S u s e rn am e = " r o o t " ; $password =

$ connec t – m ysq l = m ys q1 – connec t ( S se r v e r , $us e rn ame , $pass wo rd ) ;

i f ($connect_mysq l )

e c h o " C o n n e c t i o n e s t a b l i s h e d " ;

e l se r I

d i e ( " U n a b l e t o c o n n e c t " ) ; I

$ d b = " u s e r " ; $ m y s q l – d b = m y s q l _ s e l e c t _ d b ( $ d b ) ;

i f ($mysq l_db)

e cho " < BR><BR>Connec t ed t o t he da t abas e " ;

e lse

d i e ( " U n a b l e t o c o n n e c t t o t h e d a t a b a s e " ) ; I $SUJ_ 4 nsert " I NS ER T I N TO u s e r c o n t a c (user– id,user–name,user–emai- l– id)VAI-I IJES(101, 'John' , ' jol [email protected]'

Sresu l t = mysql –cruEry ( ' ; sq l - - i r i se i - t ) ;

4 1 ult)

{ f ( $ r e s echo "<BR><BR>THE RECORDS ARE INSERTED";

e lse

echo "RECORDS COULD NOT BE INSERTED IN THE TABLE"; mysq l _ e r r o ro ;

In the above code, records are inserted in the table using the - 1 - N S E R T command. If there exist any e r ro r , t he m y s q i — e r l o r ( ) f unc t ion re turns the e r ror message tha t i s sent by the MySQL server.

V 1.0 K) 2004 Aptech Limited Page 191 of 274

Page 42: Web Scripting With PHP

Page 42 of 274 V 1.0 (c) 2004 Aptech Limited Web Scripting with PHP

AprITCA41

Session 15Handling 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 = "";

$connect–mysql = mysql_connect($server, $username, $password);

if: ($connect–mysal.)

echo "Connection established"; } else

die("Unable to connect"); I

$db = "user"; $mysql–db = mysql_select_db($db); if($mysql–db) {

echo "Connected to the database";

else

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

$sql_disp=("SEIIECT FROM user–contact;");

$result=mysql_query($sql_disp,);

while($row = mysqi_fetch–array($rcsult)) f echo "<BR><BR>$row(user–id1"; echo "&nbsp;$row[user–namej"; echo "&nbsp;$row[user-_emai1--id1";

if (Mvsql–num–rows ($sqlq-,,](-.r-y) l) I

echo "No result"; I

Page 43: Web Scripting With PHP

Page 43 of 274 V 1.0 (c) 2004 Aptech Limited Web Scripting with PHP

session 15( .A;~PrFcmA4 L; WW 10 E WO-K

Handling Databases with PHP

In the above code, the records such as USER–ID, USER–NAME, and USER—EMAIL—ID 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 = "";

$connect–mysql = mysql–connect($server, $username, $password);

Jf($connect–mysql)

echo "Connection established";

else

die("Unable to connect"); I $mysql–db mysql_select–db("USER");

if($mysal_db)

ecl-)o "Connected to the database";

else

die("Unable to connect 4-o the database");

$sq7 –dolete= ("DELEETE FROM user–contact ',,,7.HERE user_id '101

$resul-t=mysql–qiiery($sql._delete);

if($result)

echo "$result- RECORDS ARE DELETED"; } else

echo "RECORDS NOT FOOND IN THE TABLE"; mvsql_erroro;

Page 44: Web Scripting With PHP

W *0 RALID W 1-10-6 Session 15

Page 44 of 274 V 1.0 (c) 2004 Aptech Limited Web Scripting with PHP

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 "root"; $password "";

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

if($connect_mysql) f

echo "Connection established";

else

die("Unable to connect");

$mysql_db = mysql—select_db("USER");-

if($mYsal—db)

echo "Connected to the database"; I else

die("Unable to connect to the database"); I I Y~sqi — update= ("UPDATE user —contact SET user—name ='Jenniffer' WHERE user—id ='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 45: Web Scripting With PHP

Web Scripting with PHP V 1 . 0 C ( ` 2 0 0 4 A p t e c h L i m i t e d

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 user—contact table using the HTML table structure:

<HTML> <BODY> <?php $server $username = "root"; $password = "';

$connect–mysql = mysql_connect($server, $username, $password);

if($connect–mysql) echo "Connection established";

$mysql–db = mysql–select–db("USER");

if ($my-sql_djD) echo "<BR><BR>Connected to the datahase<BR><BR>";

echo "<TABLE BORDER BGCOLOR="WIIITE">"; echo <TR><T]I>USER–I*Y)<'!'H><TH>US"--R–NAME<Tll><TII>USER–EMAI'L–ID </TH>"; echo "<DBQUERY q> select * from user contact"; echo "<DBROW><TR><TD><? qJJSER–ID>-:::/TD><TD><? q.USER–NAME></ TD><TD><? q.USEP--EM---"LL–I])><./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 DBIRlow 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

Page 46: Web Scripting With PHP

Web Scripting with PHP V 1 . 0 C ( ` 2 0 0 4 A p t e c h L i m i t e d

Sessoqn 15 EifprEchr O WLOAV1404r.

Handling Databases with PHP

• Database APIs allows developers to write applications that are

movable or between the database products. easily accessible

The common databases APIs are Native-Interface , 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

T h e b s i c P H P f u n c t i o n s t h o s e a r e u s e d w i t h r e s p e c t t o t h e d a t a b a s e a r e ysql–list–dbso, mysql–select–dbo, mysq1_1ist_Uab1esO, num_rows()

The mysql–close () function closes the connection with the MySQL server.

The data access functions used in PHP are mysql_query () , () mysql–fetch–rowo,mysql–fetch–fieldo,mysql_field–leno, mysq1–num–fieldso'•

-- -77

Page 47: Web Scripting With PHP

(-4-12TECH0OUILOW3:0

Session 15 Handling Databases with PHP

1. The database server is connected to PHP with the help of the function.

a. mysq1.–se1ect–dbO

b. mysgl_connect()

C. connect_mysq1()

2. The function displays the total number of rows of the specified table.

a. mysgl_fetch_array()

b. mysgl_select_db()

C. mysgl_list_tables()

d. mysql–num–rowso

3. Th function displays the details of the columns of the table.

a. mysql–fetch–fieldo

b. mysgl_fetch_row()

C. mysal_fetch_array()

d. mysgl_num_rows()

4. The _____________ function executes MySQL queries.

a. Mysqi_Quer,y ()

b. mysgl_connect()

C. mysal–query ()

connect-.–mysq1.()

5. Records can be inserted in the table using the _________________________ command in PHP.

a. INSERT

b. UPDATE

C. SELECT d. DELETE

Web Scripting with PHP

Page 48: Web Scripting With PHP

Page 48 of 274 V 1.0 © 2004 Aptech Limited Web Scripting with --=

Handling Databases with PHP

Records can be modified in the table using the ___________ command in PHP.

a . D E L E T E

b . I N S E R T

C . S E L E C T

d. U P D A T E

Page 49: Web Scripting With PHP

V 49.0 K) 2004 Aptech Lhnied Page 199 of 274 ..3b Scripting with PHP

Obi ec f lves

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 )01

Response

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 forfurther processing. For example, on an online shopping Web site, the user browses through theWeb site. The product that the user purchases are added to the shopping cart. On completion

Page 50: Web Scripting With PHP

Page 50 of 274

APYIEC"

0 : R L D W9.0 19

W0- Sessuon 16 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

Beforeorder ...................

.confirmation Temporary data For

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 Web Scripting with Pr-7 I ' — . . . . . . . . . . .

...... 1-1 ...... Temporary

cookie deleted 0

User cancels the order

Figure 16.4 : Deletion of Temporary Data

Page 51: Web Scripting With PHP

Web Scripting with PHPV 5 1 0 O c 2 0 0 4 A p t e c h L i m i t e d Page 203 of 274

Working with Cookies

The user enters sensitive information, such as the full name, address, credit card details on orderconfirmation. Such sensitive and confidential information is stored in the database of the Webserver.

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 sendsthe ID in the cookie to the Web browser. The browser stores the cookie and sends it back to theWeb site in subsequent requests. The Web server can read the information stored in the cookieonly when it is related to the Web site. The life of a cookie depends on the expiration time anddate.

The cookie is stored on the hard disk of the user. This enables the Web site to keep a track onthe user visiting the Web site. The information about the user is generally stored in the name-valuepair.

Web servers and Web browsers send cookies to each other in HTTP headers. The Web serversends the cookie to the browser in the Set-Cookie header field. This field is a part of the HTTPresponse. The Web browser stores the cookie and uses the same in subsequent requests to thesame Web server.

Consider the following HTTP response header:

HTTP/2.0 207 Content-Lengch: 8451 Coast e,n(:.-Type: text/]"itrnl D a t e : H o n , 2 7 D e c 2 0 0 4 0 5 : 2 9 : 2 4 G M T 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

Page 52: Web Scripting With PHP

.4 R F, U CifWORLDWISS Sessuon 16

V 1.0 (c) 2004 Aptech Limited Web Scripting with PHP Page 52 of 274

Session 16 Working with Cookies

w n ~

The Web browser records the cookie information and saves it on the hard disk of the system. Insubsequent requests made to the Web server for a Web page, the information is sent along withthe 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-cookiefunction. The above code snippet shows the subsequent request that a Web browser sends tothe Web server.

'16.2 Setting a Cookie

Cookies are incorporated in HTTP request and response headers. Setting a cookie means sendingthe cookie to the browser. PHP uses two functions, setcookie () and setrawcookie ()to set acookie. 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 theheader 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 53: Web Scripting With PHP

Page 53 of 274

Working with Cookies

path - Refers to the path on the server where the cookie will be available. It specifies thesubset 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 secure -

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 • HTTP connection exists.

When the cookie is set, the value is automatically URL encoded- When the script retrieves acookie, it automatically decodes the value. PHP executes codes in a particular sequence. HTTPheaders are executed before the scripts. Cookies are a part of the HTTP header. There can bemore than one cookie in the header but it should relate to the same domain or website- The coderelated 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 andreturn False. So before displaying any output or even the white space, setcookie ( ) function mustbe 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, /Webmap/", ".Webworldmaps.com");

In the above code snippet, fmapname is the variable that contains the country name that the userenters. 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 Nleb)woridlmaps.com – Domain that the cookie will use

Page 54: Web Scripting With PHP

Page 54 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 thevalue of uname that the GET method retrieves. The setcookie ( ) function in the above code snippetsets 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 thesame script can be made in a specific order depending on the version of PHP. In PHP 3, multiplesetcookie ( ) 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 isavailable only when the user loads the next page. The Web browser matches the URL against alist of all the cookies present on the client system. If the Web browser finds a match, a linecontaining 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 thesame directory can also access the cookie. To access the cookie, the documents outside thedirectory 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 thevariable as the cookie name. The following code displays a cookie value:

echo sc(Dokie–name;

The above method of retrieving the cookie value is not recommended- This is because PHPwill start searching all the variables present in the client system. The register_globalsoption must be enabled in the configuration file if we want to use this method to retrievecookie value.

Using $HTTP–COOKIE – VARS [I array - PHP uses cookie name as a variable to retrieve thecookie value. PHP can also use an associative array called $1zTTP–('O'0KIE VA.RS F 1 to retrievethe cookie value. The $HTTP_COOKIE_VARS [I is a global variable that reads a

Page 55: Web Scripting With PHP

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

Page 55 of 274

Working with Cookies

v a l u e o f t h e c o o k i e . T h e n a m e o f t h e c o o k i e m u s t b e p a s s e d a s t h e k e y t o t h e S.HJ"1'1'1_COOK1E_VARS[', array as follows:

E'(-.'110 $11TTP__COOKI E—VARS ( $ cook i e—nanie I

The above method i s more re l iab le and fas te r than re t r iev ing the cookie va lue through a variable.

U s i n g $--C O O K I E [ ] v a r i a b l e - We can a l so use the fo l lowing to r e t r i eve t he cook ie va lue :

$_COOKIE['$cooki.e_name'1;

The above method of ret rieving the cookie value is recommended, but i t requires PHP 4.1. I tis also considered the best method. I t is also known to be simpler and more secured thanusing 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 $cook ieva l " ; } else

echo "You need W log -in

</F301)y> </HTML>

I n t h e a b o v e - c o d e s n i p p e t , s t o r e s t h e c o o k i e v a l u e . T h e f u n c t i o nchecks whether the cookie is set. If the cookie is set, the echo statement will display awelcome message along with the cookie value. I f the cookie is not set , the messageappears prompting the user to log in.

Page 56: Web Scripting With PHP

Wo"ALID-W401E Session 16

V 1.0 (c) 2004 Aptech Limited Web Scripting with PHP Page 56 of 274

Working with Cookies

16'.4. Deleting ..-CI Codkie.:•.

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($cookie–name);

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 57: Web Scripting With PHP

W 0 . L D W * I • D E Session 16Working with Cookies

A browser can maintain a maximum of 300 cookies. Older cookies that were stored earlierare deleted to accommodate the newer cookies of the different Web site.

Storing large number of cookie files slows down the system. To enhance the performanceof the system, users often delete temporary files that contain cookies. Web site statisticsmay go wrong when users delete such cookies to improve the performance.

Some users disable cookies while accessing Web sites. The Web sites that depend oncookies lose information of such users.

There can be multiple users using the same system visiting the same Web site. Web sitesassign 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 lotsof information that we want to retrieve from a cookie. Retrieving larger amount of information oneach page requires repetitive coding across the pages.

Page 207 of 274 Web SCtI.

pzI,)g with FIHP V 1.0 rc7 2004 Aptech Limited

,04 Aptech U

Page 58: Web Scripting With PHP

I I AprECH Session 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

∗ Using $._COOKIE[]

0' 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 v 1 lotech Limited Web Scripting with PHP

Page 59: Web Scripting With PHP

Web Scripting with PHP

Session 16

(A'pr,EcmWORLDWIDE

Working with 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

Page 60: Web Scripting With PHP

P a g e 6 0 o f 2 7 4 •

Sesskon 16 ?py-Ecm -0 R.L.DIS.a W,

Working with Cookies

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

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

a. $–COOKIE[]

b. $HTTP–COOKIE–VARS[I

C. setcookie()

d. isset (

2. requires PHP 4.1 to retrieve cookie value.

a. $–COOKIE() b. $HTTP–COOKIE VARSH C. setcookie() d. isset Maximum

of cookies of a domain can be maintained :

a. 20 b. 30

C. 200 d. 300

3.

a- 20 b. 30 C. 200 d- 300

5. The _____

a. $_COOKIE[]

b. $HTT)-)_COOKIE_VARS

C. setcookie()

d . isset o

function checks whether the cookie is set.

6. The __________________________ option must be enabled in the configuration file to pass a variable as cookie name. a. register–cookies b. enable–register–cookies

C . reqister I o;:) a- I s _g l

d. er)ab1e_register__g1.oba1,,

V 1.0 2004 Aptech Limited Wel) Scr ipting with PH"

Page 61: Web Scripting With PHP

Web Scripting with PHP V 1.0 © 2004 Aptech Limited Page 61 of 274

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. Open the gedit text editor.

2. 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>

Page 62: Web Scripting With PHP

14,0F,,EC,f,F

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

Working with Cookies

To validate the information that the user enters in the form:

V

[: logname% ~t~Mk_ W ,

$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

~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 , / 4.~mi A ry irecto. .

Page 63: Web Scripting With PHP

Web Scripting with PHP V 1.0 @ 2004 Aptech Limited Page 63 of 274

Session 17 Et2_17TECif LOWIDE

Working with Cookies

echo "<BODY>";

"<A H EF='Information.htm1'> Back </A>"; </BODY>"•

echo' </14TML>",

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

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

The above code snippet uses the ,leader function to redirect the information to homepage.php that is the home page of the Web site

To create the home page of the Web site:

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 – L COOKTE _VARS['logname'];

2. Enter the following code to display the various items available for shopping:

echo "<HTML>11 ; echo "<HEAD>";

Page 64: Web Scripting With PHP

AprIC-CH WOULOW1,02 Session 17

Page 64 of 274 V 1.0 Cc-) 2004 Aptech Limited Web Scripting with PHP

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 65: Web Scripting With PHP

Web Scripting with PHP

APrecm WORLDWIDESession 17

Working with Cookies

3. Save the file as homepage.php under the /var/www/html directory.

4. Open a new file in the text editor.

5. 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");

File Edit View Go Bookmarks Tools Window Help /A. jp

j,4 http-alh.st/informE -s Search] Print Back Forward Reload Stop

Home 4 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.

Widdigs"

//Redirects ûsers. to the main. Information.ht-n page for login Header("Location: Inf6rmation.-Mm");

(V . Q 0 j - 77

Page 66: Web Scripting With PHP

Web Scripting with PHP

APTECH

Session 17

Working with Cookies

I..".: i21! xi,.File Edit.

Back

View Go Bookmarks

F o r w a r d Reload Stop

Tools Window Help

C-4

Print

1

.

i i

h,tp:j/loi:alhost/homepaq E, Search]~O 5-

;!,114orne IdBookmarks "Red Hat Network CtSupport JEjShop (ZiProducts L-jTraining

Plea,-v-- enter the name'.R a c k

Done UA. C4 -,?, 93 G9

- • . O G I N

. File Edit View Go Bookmarks Tools Window Help

http://1oi:alhostjhomepagf Print Back F.)nvxJ Reload Stop I - .. ......... .... 3 H o m e Bookmarks _ 00Red Hat Network :_4SUpport Shop j:; _—Products Training i L j

Shop till you

Con1*1.Ci:01)er%,

L.,s.::::sories

Perl'unu-, Apparel

4 z GE2 Done . . . . . . . . . . . . - ........... -

Figure 17.3 : Home Page

Figure 17.2 : Validating the Information NvOcolile John I 0~,M

MLX

i I WO R-L D W 1 0

V 1 . 0 (c- , 2004Aptech Li it d Wb Siti ith PHP

Page 67: Web Scripting With PHP

%veb Scripting with PHP V 1.0 2004 Aptech Limited Page 67 of 274

APYIIECSession 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:.

$HTTP–COOKIE–VARS['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 "<TR ALIGN='center'>"; echo "<TD>C001</TD>"; echo "<TD><A HREF= '' >Choco Delight</A></TD>"; echo "<TD>$40</TD>I echo "</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->";

Page 68: Web Scripting With PHP

Page 68 of 274 V 1.0 © 2004 Aptech Limited Web Scripting with PHP

Session 17

Working with Cookies

C o o : ' B o o k m a r k s I ools Wndow- LW 4 - '

Back' s w a r d ' . P r i n t .1 R e l o a d I t o /Axo dhost/conf.pllvi &.S, .- , h

r P Welcome John Logout

Shopper's Paradise

Shop till you drop!!!

C.d 7cF Na m e ; P r r c e l

.......... KtqiChoco-Dcli,zhd $401- 0002.1 Vanilla Grub 1: S70

--.- ..... ..... . ..... I - - - , 7

42 tZ nn~ G9 I Done

Figure 17.4 : Confectionery Web Page

Simi la r ly , c reate Web pages to d i sp lay var ious p roducts avai lab le for sa le under the Flowers . Accessor ies , Perfumes, and Apparel ca tegories . Table 17 .1 l i s t a l l the products and i t s detai ls under these categor ies .

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

W 1 1 1 i m - A l F I I I

I

Page 69: Web Scripting With PHP

rAJ:FrEcff WORLDWIDE Session 17

Web Scripting with PHP Page 219 of 274 V 1 . 0 O K 2 0 0 4 A p t e c h L i m i t e d

Working with Cookies

Product Category Product Code Name Price Flowers F004 Tulip Bouquet $75

F010 Red Rose $10 F011 Lily $8

Accessories A001 Diamond Bracelet $950 A006 Diamond Ring $800 A012 Diamond Anklet $500

Perfumes P002 Charlie $180 P008 Maui Rain $90 P018 Night Mist $80

Apparel AP001 Black Suit $480 AP018 Wrinkle-free Suit $190 AP020 Wrinkle-free shirt $180

Table 17.1 : Product Details

Page 70: Web Scripting With PHP

Page 70 of 274

Session 17Cil—P7'ECH OR L DW I WE

Working with Cookies

JRY IT YOURSELFPart II - For the next half an hour:

Full name

> Address

Email Address

Credit Card

Number Telephone

Number

1. Create a cookie that stores all the above-mentioned user information.

Shopper's Paradise is a shopping company that deals in selling goods online. The Web sites offers items, such as Confectionery, Flowers, A

Page 71: Web Scripting With PHP

.*.eh Scripting with PHP Page 71 of 274 V 1.0 (c) 2004 Aptech Limited

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

Page 72: Web Scripting With PHP

Page 72 of 274

S e s s u o n 1 8 rA JCPrEC,&,woe LDWIDS

Sess ion 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 refersto the time the user accesses information on a particular Web site. Session management involvesmanaging data related to a particular user in a specific session.

PHP sessions enable distinguishing the user specific information during the life of the session. Asession life refers to the total time a user spends on the Web site before the user exits the Website.

.19.12 'Importance of a Session

Suppose in a particular Web site, the user has to first register and then log on to access anyinformation. For such user authentication procedures, the Web sites require to maintain the state ofthe user across the Web site. Web sites traditionally use GET and POST methods to passuser information from one script to another. When these methods are used, PHP assigns userinformation variables in the following format:

$ n a m e = $ _ G E T [ ' n a m e ' ] ;

In the above code snippet, the variable $name stores the value that the script retrieves from the formthat a user fills. This process of transferring user information is unnecessary and timeconsuming, especially for a large Web site. Figure 18.2 shows the above code has to be usedacross all the Web pages of the Web site.

01 0.

Page 1

$ na . nc - S –CIEF[rlalnel;

_ F

Page 2

$riarne - $--Q.E–i [naMel

r-11

Page 3

$name =

$--GET[name]

r - /

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 73: Web Scripting With PHP

.*.eh Scripting with PHP Page 73 of 274 V 1.0 (c) 2004 Aptech Limited

Session Management in PHP

Page 4 Page 3

r).3 r Page 2 nar

naf Page 1

name = 'kin)"

r l

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 Website. 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 sharedcomputer. 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 placingthe order, the user enters all his personal information, such as name, age, address, credit cardinformation. 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 usingcookies.

There are some other disadvantages of using cookies:

Deletion of cookies – Users can easily delete cookies from the client system. We canaccess a list of cookies from the systems temporary file saving location. Users often deletethe temporary internet files to improve the performance of the system. Web sites allot a newcookie to the user without a cookie. This proves disadvantageous to the Web sites whokeep a count of the visitors who return to their Web sites.

Multiple cookies to the same user - Cookies enable Web sites identify the users accordingto the computers they use. Web sites aliot a different cookie to the same person every timethe user accesses the Web site from different computers. The statistics of the Web siterecords new user entry of the same person using different computer. In addition, a user hasto 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 storedin the cookie, larger is the page size. This results to lower performance because usersexperience slow browsing of the Web site.

Cookies disabled - Web sites store cookies on the hard disk of the client. This reducesthe performance of computers with the low memory space. To improve the performance ofsuch computers, users disable cookies. This makes the process of assigning cookiespointless.

Page 74: Web Scripting With PHP

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 Sessions Stores user information on the client system (Web Browser)

Stores user information on the Web server

Available even after the user exits the Web browser

Destroyed when the user exits the Web browser

Users can disable cookies Users cannot disable sessions Have size limits Do not have size limits

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 set–cookies 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.

ii

Page 224 of 274 V 1.0 (0 2004 Aptech Limited Web Scripting with PHP

Page 75: Web Scripting With PHP

AprIECH W O R L D W S O E Session 1

Session Management in PHP

Figure 18.4 shows the working of the session:

O First Request

1<

Response with

Session ID

Subsequent Request ~ with Session ID )01

Response with Information about User

1 <

Figure 18.4 : Working of the Session

PHP works with session in the following sequence:

1. User accesses the session-enabled Web site

2. Web site checks the identity of the user whether the user is a new visitor or an ongoing session user

3. 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.

4. 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.

5. When the user exits from the Web site, the session file is destroyed from the Web server.

-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

Starting the session Registering the session variable Ending the session

Web Scripting with PHP

Page 76: Web Scripting With PHP

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

Session Management in PHP

A session starts when a user logs on to the Web site. In PHP, the session–start ( ) 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, Bess–denkhu7869jhnkh789jas543hk87p5u3 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 session–start () 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

Page

Page 77: Web Scripting With PHP

Session 18

Er-Ecw O W I'D E

Session Management in PHP

Save the above code as sessl.php in 1var1wv,,w1html directory. In the above code, thesession—start ( ) function intializes a session. The session—id ( ) function displays the sessionid 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 thesession—start () function. For example, we will add an echo statement in the sessl.phpfile, as follows:

echo "Welcome to Shoppers Paradise"; <?php

s es s i on--s t ar t ( ) ; ethic, "The Sessior) i d i s session—id

PHP shows the error message as shown in Figure 18.6:

Figure 18.6 : Error Message

Web Scripting with PHP V 1.0 (P 2004 Aptech Limited Page 227 of 274 No Mp Li f f l a ; . i * ' F i l Ed i t V i G

V File Edit View Go Bookmarks Tools Window Help

hUp:[/localhostisess Back Forwaal 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

Page 78: Web Scripting With PHP

rA P Tr CH11!!~ L-D'W-2:tr-F

Session Management in PHPSession 18

-2 Registering the-S ession Variable

Variables in a session file contain user specific information. To work with the sessions across allthe Web pages, session variables need to be registered with the session library. Session libraryenables creation, serialization, and storage of session data. We can use three methods to set asession 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 storesthe session variables in a session file by serializing the values. PHP automatically handles theprocess of serializing the session variables.

s d fdrmin'J".

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

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> < A HRE F

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 ~ i

HEAD> <TITLE> Eoinepl,ge <,/'_7 1VLE>-:_ /HEAD> <BODY> Welcome < -- o l n .: caivame > l..o M Page.com P < BODY> < HTM L >

Page 228 of 274 V 1.0 Cm 2004 Aptech Limited

Page 79: Web Scripting With PHP

Session 18

EePTECIF ORLDWID8

Session Management in PHP

Save the file as mypage.php. In the above code, session value is retrieved and displayed. To viewthe output, open the Mozilla Web browser and type hULp://localhost/session.php. TheSessions 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 session–destroy () 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 - : ' r T P _ S F S S I O N – V A R S [ ' m y n a - n e ' ] ; session–destorv();

To see the effect of -iession — dosLroyo function, open the Sessions page in the Mozilla Web browser. Click on the Homepage oll- hyperlink. 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 session—destroy function is used.

P a g e 2 2 9 o f 2 7 4

Web Scripting with PHP V 1 . 0 ' P ) 2 0 0 4 A p t e c h L i m i t e d

Page 80: Web Scripting With PHP

Session 18

Session Management in PHP

To destroy the variable completely from the current page, add the following code before the session_des troy() function:

session—unseLo;

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:

Figure 18.7: PHP Configuration File

V 'xElie Edit View Terminal Go Help ::;-11v I

; WARNING ;

T h i s i s t h e d e f a u l t s e t t i n g s f i l e f o r n e w P H P i n s t a l l a i i o n s . B y de f a u l t , 1

114 P i n s t a l l s i t s e l f w i th a c o n f i gura t i o n su i t a b l e f o r

de ve l opme nt purpose s , and *NOT ' f o r p roduc t i o n purpose s . Fo r se ve ra l s e cur i t

y- o r i e n ted cons ide ra t i ons tha t shou ld be t ake n be fo re go ing on l

ine

w i th your s i t e , p lease consu l t php . in i - re commended and lit tp: //php. net/manual/en/security. phi).

; A bo u t t h i s f i l e :

l h is f i l e c o n t r o l s m a ny a s p e c t s o f P HP ' s b e h a v i o r . I n o r de r f o r P H P t o r e a d

i t , i t m u t i t b c - Wade d ' php . i n i ' . PHP l ooks f u r i t i n t he cu r ren t working d ir ,c lor%

,, in tho path designated by the environment var iable PHPRC. and

in the path that was de f ined i t,. comp i le t ime ( in that order ) . Under Windows,

the p a t h i s t h e W i n d o w s d i r e c t o r y . ' f i l e 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.

. . . . . . . . .

23,1 Top

J:t

WOR LOWIDIE

Page 230 of 274 V 1.0 Oc 2004 Aptech Limited

Page 81: Web Scripting With PHP

Sessuon 18

64-PTEC'H_ ~

ORLDWIVE

Sess ion Management in PHP

The php . in i f i l e conta ins d i rec t ive l i s ted in the directive = value format . We can use a semicolon to add a comment to the f i le . PHP ignores l ines that begin with semicolon or a s ingle whi te space. We can edi t the php.ini f i le to customize the se t t ings.

Table 18.2 lists the categories containing various options available in the php.ini file.

Tab l e 18 .2 : Ca t ego r i es of the PHP Conf igur a t ion F i le

Categories Options that

Page 82: Web Scripting With PHP

WO R LD'W I 81E

Session 18Session Management in PHP

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. save—path — 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. use—only—cookies — 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:

$ _ P O S T [ ' $ vari a ) . - ) 1 e —n a m e ' j or $ —GET[ 'svariabie—naiiie' I

Page 232 of 274 V 1.0 O. 2004 Aptech Limited Web Scripting with PF:

Page 83: Web Scripting With PHP

rA~Yrrcf- Sessaon 18

S e ss i o n M a n a g e m e n t i n P H I

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, variable–name is the name of the variable that holds sessiodata of another Web page. The variable storeValue stores the information included in thvariable name.

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

display errorsand display–startup–errors – Enables PHP to display error onthe Web browser. It is recommended to disable these variables, especially while creatingdynamic Web pages. Dynamic Web pages may display user sensitive information, such apassword, 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 recommendedenable the log errorsvariable, when the display–errors anddisplay–startup–e--r-ror! variables are disabled.

Web Scripting with PHP

Page 84: Web Scripting With PHP

APEUCH

WORLDWIDE

Session 18 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. I

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 window-

The scripts gain access to the session ID depending on two situations, such as:

Web user enables cookies

• Web user disables cookies

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.

Page 85: Web Scripting With PHP

Session 18

(AprEcAr LOWIDE

Session Management in PHP

The php.ini file contains options that are grouped under categories, such as :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

Page 86: Web Scripting With PHP

W 0 R L:D W PD :E

Session Session Management in PHP

C K YOU 8 PROGRESS

f

1. The __________________ option indicates whether or not the modules will use only cookies for storing session IDs.

a. session.cookies

b. session cookie lifetim

C. session.use–cookies

d. session.use_only_cookies

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

a. session destroy(

b. gc–maxlifetimeo

C. gc–probabilityo

d. session_unregister()

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

a. session destroy()

b. gc–max1j. f eLime () C. gc_,D--obabiIityO

d. sess-ion–unregistero

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

a. session.start

b. sessilon.auto—s-:--art

C. session. session –start

d. session.session_ auto –start

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

Page 87: Web Scripting With PHP

Sessi n 18 (AiPTECiirWORLDWIDE

Session Management in PHP

5. The ____________________ specifies whether or not the cookies should be secured connections.

a. session.cookie—secure

b. session.secure

C. session.secure connection

d. session.use— secure —connection

6. controls the functioning of server, forms, and environment variables,

a. register_globals

b. uploads_tmp_dir

C. session.control—variables

d. session.register_variablesI

. Web Scripting with PHP V 1.0 (g) 2004 Aptech Limited Page 237 of 274

Page 88: Web Scripting With PHP

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 Sending E-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

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

File Fdit View Search Tools Documents Help

New Open S ave P r in t Undohe l lo Cu t Copy Pa s t e F i nd Rep l acephp.ini x-

[ nail function] ; For Win32 only.

SMTP -- localhost ;

For Win32 only.

sendinail–from = ineZlocalhost. coin

For Unix onl y . You may supply arguments as we l l (de fault: sendinail -t -1 11 ).

sendmail_path = /usr/sbin/seiidinail -t -i 4

Lr. __01. 16 1N5

Page 89: Web Scripting With PHP

Sess~un 19 r

a L1D W 1.0-E

Handling E-mail with PHP

The syntax for the mail ( ) function is:

mail(to, subject, message [additi.onal–headers])

Where,

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

additional–headers – 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 "[email protected]"; $subject "Ilm example"; $body = "This is an example for showing the usage of the mail() function.";

$send = mail($to, $subject, $body, $from);

if($send)

echo "Mail sent to $to 'address! i ! 11;

else

echo "Mail could not be sent to $to address!!!";

</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 W eb Sc r ip t i ng w i th ( , ) PHP Page 240 of 274

Page 90: Web Scripting With PHP

Session 19

rAJi:Pr,ECff WO RLD WI D E

Handling E-mail with PHP

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

<HTML> <BODY> <?php

$to = "[email protected], [email protected], [email protected]"; $from = "[email protected]";

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 spaceplaced in between two recipient's e-mail address, the mail () function removes it. A commasymbol is used for separating recipient addresses. In this code, the for statement is used forreading the number of recipient addresses.

Suppose we have stored all the e-mail addresses of the recipients in the text file. PHP enablesus 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 $ -C. o_ma i i f i 10 (5AT-11-1 t i ) ; $from =-- " toi0bli-iemountain. com";

Web Scripting with PHP V 1.0 C0 2004 Aptech Limited

Page 91: Web Scripting With PHP

Session 19 Eifir2TECifOR OW101E

gro

Ha dling E-mail with PHP

for ($ i = 0; $ i<C0U3'1t ($ tO_Ma 11) ; $ -i A- 4-)

$to_ma_i l [ $ i 1 = t r i m ( $ t o _ m a i l [ $ i 1 ) ; $ t o = i m p l o d e ( " , " , $ t o _ m a i l ) ;

$ su b j e c t = "A - n exa m p l e " ; $ b o d y = " T h i s i s a n e x a m p l e f o r t h e m a i l ( ) f u n c t i o n . " ;

m a i l ( $ t o , $ s u b j e c t , $ b o d y , $ f r o m ) ;

e c h o " M a i l w a s s e n t t o a l l t h e a d d r e s s e s ! ! ! " ; }

</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-mailaddresses in an array. The trim() function removes the blank spaces inserted between the e-mail addresses. The implode () function joins all the e-mail addresses in the array by separatingeach 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 alongwith the e-mail. An attachment file can be any simple text file, document file, or a graphics file. Afile is attached with the e-mail by setting up the header.

For example, to attach a file with an e-mail:

<HTML> <BODY> < ?php

$ f i l e "/var/w%,,,,v,7/htlnl/exampl-e.txt"; $fp f o p e n ( $ f i l e , " r " ) ; $ c o n t e n t = f r e a d ( $ f p , f i l e s i z e ( $ f i l e ) ) ; f c l o s e ( $ f p ) ; / / $ f i l e = c h i i n k - s p l i t ( b a s e 6 4 _ e n c o d o ( $ f i - l e ) ) -

$to "[email protected]; $from "[email protected]";

$subject , "An example" ;

$ m i m e b o u n d a r y - u n i ( l i d ( " " ) ; $header .= $ f rom; $h eade r .= $ to ;

Page 242 of 274 V 1.0 ©2004 Aptech Limited Web Scripting with PHP

Page 92: Web Scripting With PHP

APYIECH

44R

O L D W I D ESession 19 Handling E-mail with PHP

Sheader.= "MIME-VERSION: 1-0\r\n"; $header.="Content-type: multipart/mixed"; $header.= "bounday,y=.\"".$mime–boundary."\""; $message.="This is an example for mail attachment.",- $message.="\r\n\r\n"; $message.="–".$mime–boundary."\r\n"; $message.="Content-type:text/plain;charset=\"iso-8859-

1\ " \r\n" ; V 1 . 0 ~ P 2 0 0 4 A p t e c h L i m i t e d Page 243 of 274

$inessage.="–".$mime–boundary."\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.="–".$mime–boundary."\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> < / 1-7 TI-1 L>

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 den () 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

Page 93: Web Scripting With PHP

Session 19 AprIECM 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 C c ) 2004 Aptech Limited Web Scripting with PHP

Page 94: Web Scripting With PHP

Session 19

(A,PY-,FC,ff7" LOWIDE

CHECK YOUR PROGRESS

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

a. implode ()

b- sendmail_from()

C . mail()

d. file()

2 The symbol is used for separating recipient addresses.

C.

d.

3. The trimo function removes ______________ from the recipient address.

a. ascii character b. comma operator

C. blank space

d. wide space

4. The function joins all the e-mail addresses in the array. a. file()

b. trim

C . -mail

d. implode

5. The boundary is created using the _____________ function.

a. file ()

b. uniqid

C . trim ()

d. implode .... ..... ..

Handling E-mail with PHP

Page 245 of 274 Web Scripting with PHP V 1.0 © 2004 Aptech Limited

Page 95: Web Scripting With PHP

IS e s s i o n 1 9 A p r E C HWORLDWI-DE

Harfd1ing E-mail with PHP

era re.......11110aMorairameiraryk

6, The function opens the attached file in read mode.

a . f read()

b- implode()

C . uniqid

d. fopen()

7. The _________ function splits the data into smaller portions.

a . chunk–split(

b- fread()

C. base64_encode()

d. fopen()

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

Page 96: Web Scripting With PHP

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:

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:

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 "[email protected]" 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 = "subject" SIZE = 60> <BR><BR> <TEXTAREA NAME = "mail–body" ROWS "6" COLD TS "50"></TEX'PAREA>

Web Scripting with PHP V 1 . 0 ` 2004 Aptech Limited Page 247 of 274

Page 97: Web Scripting With PHP

APMCCA?

Session 20 WORLDWIDE

Handling E-mail with PHP

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

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

<BR><BR> <INPUT TYPE

Al

N2

0"O' cc;

for(.$i=O;$i<count($mail–to);$i++)

$mail–to[$i] trim($mail_to[$i]); $mail_subject $–GET['subject'];

$body = $_GET['mail body'];

$confirm = mai-l($mail_to,$mail–subject,$bodv,$mail–header);

if($confirm) echo "To: $mail_to &nbsp"; echo "From: $mail_from <BR><BR>"; echo "Cc: $mail–cc &nbsp"; echo "Bcc: $mail_bcc <BR><BR>"; echo $body; echo fl<BR><BR>Mail Sent to all the e 1

addresses!!!";

echo "<BR><BR>Mail could not be sent!!!"

Page 248 of 274 V 1.0 1* 2004 Aptech Limited Wei) Scripting with PHP

Page 98: Web Scripting With PHP

Session 20

(A—Pywcm-Woa LOWIDE

Handling E-mail with PHP

</BODY> < / HTML >

6. Save the file as multiusers.php under the /var/ww4/htTn1 directory.

7. Open the Mozilla Web browser.

8. Type http://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 [email protected], [email protected], and [email protected] as the recipient addresses.

11. Enter Birthday Reminder as the subject.

12. Enter the message, Wish you many many happy returns of the day H!, in the body.

13. Click the SEND button. The output appears, as shown in Figure 20.2.

Web Scripting with PHP 0 O 00 ptec ted age 9 oElle edit ylew Go Bookmarks Tools Window Help

Page 99: Web Scripting With PHP

APFECAV

Session 20 W 0A L D WIME

Handling E-mail with PHP

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 alongwith 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. Open the gedit text editor.

2. 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 "to" SIZE=60> <BR><BR> From: <INPUT TYPE "TEXT" N11ME "from" SIZE=60 VALUE= "jack@bluemounta-in-com" > Cc : <INPUT TYPE = "TEXT" NAME "cc" SIZE = 60><BR><BR> Bcc :

V..: : In: X File Edit View Go Bookmarks Tools Window Help .... ........ . . ..........

hn :1,1ocalhostimultiusers. Back Forward Reload Stop Print

Home **-Red Hat Network (:,~jSupporl EjjiShop (E jProducts dR- Training

To :john @1mail.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* I C I v

Page 250 of 274 V 1.0 © 2004 Aptech Limited Web Scripting with PHP

Page 100: Web Scripting With PHP

Session 20 A P B C j K ,WO R L D'WO-D E

Handling E-mail with PHP

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

$fp . fopeni($fi1'e""j'-,,#-k$content f r e a d ( $ f p , f i l e s i z e ( $ f i l e ) ) ;f c lose ($ fp ) ;

Save the file as rnalLhtrnl under

$to $–GET[ '$ to ' ] ; $from $–GET[ ' f rom' ] ; $ s u b j e c t = $ – G E T [ ' s u b j e c t ' ] , - $ b o d y = $ – G E T [ ' b o d y ' ] ; $mi r r i e – boundary = un ia id ( " " ) ; $header .= $ f rom; $h eade r .= $ to ;

"MIME-VERSION: 1.0\r\n"; "Content-type: multipart/mixed";

"boundary=\"".$l-ni-ine–boundary."\". = " Urgen t R equ i r emen t . " ; .="\r\n\r\n"; .="–".$ir,i-me–boundary."\r\ii"; .= "Conten. t - type : tex t/pla in ;charset=\"3.so-8859-

$header.= $header.= $header.= $message. $message $message $message

1\"',\r\n"; $-m,e s s a g (-.$message $message $message $ --n C? s S a g C,

="–". $iTtiiv.e_boundarv. Con :at tachment ; n ten t - Di snos i t i on: a name = \ . r., -,

1._-lename.extn\"\r\n'; -="\r\n\r\n"; .,f ile;

Web Scripting with PHP V 1.0 6. 2004 Aptech Limited Page 251 of 274

Page 101: Web Scripting With PHP

A PrEcAlff

S e s s i n 20 W a-lit-Va W U.D*E

•Handling E-mail with PHP

:$ . c o n t e n t = " < P > . $ c o n t e n t . < 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.

Figure 20.3 : E-mail Form with the Attachment Field

r F " : - , - ' . - - - , 4 4 ' . . t 7 7 : 3 r . , . . / : , e Edit View §.0 Rookmarks Tools window Help

1 I!tjMorne : %fBookmarks "Red Hat Network !:ASupport rjShop CalProducts ATralrOng

To: F From: Vack gblueniountain.com

Cc: 1

1 3 C C : r -

SubjeLt: I Attachnient: Foh.txt

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

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

Page 102: Web Scripting With PHP

Session 20 Handling E-mail with PH

9. Enter [email protected] 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.

Figure 20.4 : Viewing the E-mail Information

Mozilla )n

File Edit View Go Bookmarks Tools window Help--- ------ ---

14 http:/Aocalhost/mail.php?tc~--U~ '_%S.rch Back Forward Reload Stop Not

Home 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

0

i

Web Scripting with PHP V 1.0 © 2004 Aptech Limited Page 253 of 2

Page 103: Web Scripting With PHP

A P FECHSession 20 WO R CD W I D'E

Handling E-mail with PHP

If

TRY IT YOUR SELF

Part II - For the next half an hour:

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

Page 254 of 274 V 1.0 0, 2004 Aptech Limited Web Scripting with PHP

Page 104: Web Scripting With PHP

Objeedves

At the end of th is sess ion, you wi l l be ab le 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

Page 105: Web Scripting With PHP

Session 21 (APFECHWORIOW 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 iscalled the derived class while the existing class from which the new class is derived iscalled the base class

iL21-.2 Inheritance

The process in which objects of one class acquires the properties of objects of another class iscalled inheritance. For example, the Lancer car is a part of the class Car, which is again a partof the class Vehicles.

Inheritance means creating a new class with the help of a base class. A base class is also knownas the parent class and a derived class is also known as the child class. A class is an objectthat 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 theextends keyword for inheriting a new class from the base class. A derived class can also haveits own variables and functions. The different types of inheritances are: I>

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

Multiple Inheritance - Contains more than one base class. The derived class inherits theproperties of all the base classes. A derived class in this inheritance works with the derivedproperties along with its own properties.

Hierarchical Inheritance - Contains one base class. In hierarchical inheritance, the properties ofa single base class can be used multiple times in multiple subclasses. The derived classcontains 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 canbe a derived class from another base class. The properties of one base class are inheritedto another base class and the derived class may become a base class for another derivedclass.

Hybrid Inheritance - Uses the combination of two or more inheritances. This inheritanceis normally a combination of multiple and multilevel inheritances.

In PHP, multiple inheritances is not supported.

Page 256 of 274 V 1 .0 ©2004 Ap tech L im i ted Web

Page 106: Web Scripting With PHP

I -

APFIC-ClAf S e s s ~ c n 21 W O-R,L. 0 IMMO

E

OOP Concepts

21- .3 C reat ing a

A class is a collection of variables and functions that operate on that data. A class can be inheritedfrom a base class to create a new derived class. A new derived class uses all the properties ofthe base class including its own properties.

The syntax for declaring a class is:

class class nam

v a r c l a s s - v a r i a b l e ; 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 tothe class. A class can also use global variables. The variable inside a class is declared with thevar keyword. The functions inside a class may use its own local variables or may use the classvariables. 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 'erl) z.)d °: i.:1')

-e,

-inc a onLer nD $

~Y)

Web Scripting With PHP V 1.0 - 1ZI- 2004 Aptech Limited Page 257 of 274

Page 107: Web Scripting With PHP

Session 21 (Al"WrIEC'Ar, -3~- O:RL'VW-VD-R

OOP Concepts

$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 thefilename.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 new–cless extends class name{

va2:- class–variable; function function–mine

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

Page 108: Web Scripting With PHP

Session 21 OOP Concepts

For example , to der ive the net–salary class from the sa lary 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 net—salary extends salary

function net($basic,$hra,$ta,$tax)

return $basic i ($hra + $ta) $tax;

Save the above f i le with the name, salary. inc . In the above code, the ner–sa- lany class is derived from the base class, salary. The net.–sa -lany class inherits the properties of the sai ,ar- , '- c lass . The nct_ salary c lass uses the funct ions def ined in the c lass a long with its own functions.

The hra(), travel__al low o, and tax functions are the user-defined functions. The hra;%*! 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 the tax from the basic salary of the employee. The net function calculates the net salary ofthe employee.

2 1 . 4 . 4 , 4 C r e a t i n g - a s C o n s t r u c t o r , t ,

A constructor is a special function that is a member of the class . This function has the same name as that of its c lass name. A constructor is cal led 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.

scripting with PHP V 1 . 0 2 0 V i A p t e c h Limited Page 259 of 274

Page 109: Web Scripting With PHP

TE CH

I

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, constructor name s p e c i f i e s t h e 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, $ 1-1 a-me, c 4L t Y, $deoart)

$ L II i s - >emp i d = i d; $ Z nl`. s - > empri ar.',e = r am,7!;

$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 h p

include em,_'d e t nc

echo derails: < fi T3

!--ew e!-,l " , . J - - o hi -i "T"roy", "I.1echarlical") P

Page 260 of 274 V 1.0 Oc, 200A Aptech Urnited Web Scripting with PHP

Page 110: Web Scripting With PHP

Session 21

ei?PrIECII L D W I D E

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 new display; $displ 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

Page 111: Web Scripting With PHP

Session 216-1-PrECIIOR L DWI WE

OOP Concepts

The syntax for creating an object is:

$object–name = 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 new userdetails; •$maill new usermail; $displ $mail->dispdetail(); $disp2 $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

Page 112: Web Scripting With PHP

S e s s i o n 2 1

(A_.~VFECH= L D - W I D E

OOP Concepts

Web Scripting with PHP V 1.0 CO 2004 Aptech Limited Page 203 of 274

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

I

Page 113: Web Scripting With PHP

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. Inheritance

b- Polymorphism

C. Encapsulation..

d. Abstraction

2. The process of using a single function with its operators and variables in different ways is termed as ________________________

a. Abstraction

b. Encapsulation

C. Polymorphism

d. Inheritance 3. inheritance is a combination of multiple and multilevel inheritances,

a. Hybrid

b. Single

C. Hierarchical

d. Derived

4. The process of declaring a constructor is termed as

a. declaration

b. encapsulation

C. initialization

d. abstraction

5. is a self-contained entity.

a. Object

b. Constructor

C. Class

d. Function

I

i

Page 264 of 1/4 V 1.0 (c) 2004 Aptech Limited Web Scripting with FHP

Page 114: Web Scripting With PHP

-1

Ci-fprEcigt O R L D W I D E

Session 21 OOPConcepts

6. An object is an ___________ of a class.

a. entity b. reference

C. instance

d. constructor

7. An _________ makes the codes easier to understand and can be used for more than one time.

a. reference

b. object

C. instance

d. constructor

8. A _________ inheritance contains more than one base class.

a. multilevel b. multiple

C. hybrid

d. hierarchical

Scripting with PHP

Page 115: Web 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

Page 116: Web Scripting With PHP

Session 22 (A'PrECH\= LDWIDE

OOP Concepts

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

~ ,INPUT .

M u l t i p l i c a t i o n P U T " " Y - P E ' ation & n . .

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

Page 117: Web Scripting With PHP

OOP Concepts

Page 269 of 274

Session 22

the file as ''calculator Inc sunder .

$calculate $caiculate

new calculatoro; new ca~

$calculatel->subtracti6ii($first,$sedbnd); /,<BR><BR>";

'The difference between $first & $seQond i:

CP T E f fLDWIDE

Web Scripting with PHP V 1.0 (D 2004 Aptech Limited

Page 118: Web Scripting With PHP

OOP Concepts

Session 22

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 andcalci classes. The functions defined in these classes are called by using the class instanceswith the help of the '->' sign.

Irke A, i WO VIN . ...... PIUMMIM11

? e i t t p x ' J N ~ a Z o c a . h o s c a d a m & t ow n , Theform" . m p p e a r s ; - , a s ~ . A f t - A

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

(A'~jPF,FCffg

1-~ L- D W 1 0 1E

Page 270 of 274 V 1.0 © 2004 Aptech Limited

Page 119: Web Scripting With PHP

S e s s i o n 2 2

(A—Pr,FC,ffLO W I D E;

OOP Concepts

Elie Edit view go Bookmarks rods Wndow L4elp h.,:Mocalhosticalculate.htral ] 40_5earch

Back Forward Reload Stop T ~ __________ Print *Bookmarks*

#Red HatNeNvorkC~~Support,--A---Shop i:Vroducts 2jTrajrdng---- Calculator

Fir. NunibLr:

Second Number:

Calculate:

r Addition r Subtraction (— Multiplication Division

Sine Cosine (- Logarithm

SUBMIT

i

,4

v, 0 (V " Dli*

Figure 22.1 : Calculator Form

tlm--

M

JO

ears , , " -. 0 'ama

c

Figure 22.2: Displaying the Result for Division

..,.Click the Go.

-erect the

1 T Cli k h l

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

Web Scripting with PHP V 1.0 © 2004 Aptech Limited ageo o a bt

Page 120: Web Scripting With PHP

Session 22 (A—PPLD, EW

OOP Concepts

J~n lix

Elie Edit View Go Bookmarks Tools —Window Help

http:Mocalhost/cal &A_Search CA Back Forward Reload Stop Print _4 Home 4Bookmarks Red Hat Network (:,ASupport QjShop (~Products ~Tralninq

The cosine value of 47 is: -0.99233546915093

Go Ba c k

I

-A, LZI - / 1 90 ( 0 ~ Done

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 samename as that of its class name. A constructor is called in the main program by using the newoperator. We use the constructor to initialize objects of the class of which it is a member. Theconstructor 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

Page 121: Web Scripting With PHP

Ef—IPTECIIORLDWIDESession 22

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/"`-h-

Open a new file in theVedit text editor.'

"orderodd 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 :a-

_T

i3 hlp-14ocalhosticonstructor.plp 11F,;_~,;;rch] Mp. Back Forward Reload stop . Print f,-,Home 13ookmarks.**---Red Hat Netwoik Asupport [;Shop (6, Products ZITralning

Displaying odd numbers in reverse order

Tv File Edit View Go Bookmarks Tools Dndow Help

19 17 15 13 11 9 7 5 3

_115L1z1-~/_ M04 G9_ I Dorte

1.

Figure 22.4 Displaying Odd Numbers in Reverse Order

Web Scripting with PHP V 1.0 © 2004 Aptech Limited

Page 122: Web Scripting With PHP

Session 22 WORLDWIDE

OOP Concepts

1-- TRY IT-YOURISSELF

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 the circle in the derived class. i

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

Page 123: 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 small- scale 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

Page 124: Web Scripting With PHP

Giossary Ef—APTECIIORLDWIDE

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

V 1.0 ©2004 Aptech Limited Web Scripting with PHP Page i i

Page 125: Web Scripting With PHP

Glossary

(A—PJr,EC,ffwoRtowIae

Glossary

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

Page 126: Web Scripting With PHP

Glossary E4—P7'ECATORLDWIDE

Glossary

For Loop

Executes a set of codes repetitively for a specified amount of time. In this, the counter variable isdeclared 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. In hierarchical inheritance, the properties of a single base class can be used multiple times in multiple subclasses. It contains only one base class. Uses the combination of two or more inheritances. This inheritance is normally a combination of

Page iv V 1.0 CU 2004 Aptech Limited

Page 127: Web Scripting With PHP

Glossary ( A " P i r r C MW 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

Page 128: Web Scripting With PHP

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

Page 129: Web Scripting With PHP

(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 r—D 2004 Aptech Limited Page vii Web Scripting with PHP

Page 130: Web Scripting With PHP

Glossary rAJ:PTECH

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

Page 131: Web Scripting With PHP

Glossary

Glossary

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